Path: blob/jdk8u272-b10-aarch32-20201026/hotspot/src/share/vm/runtime/deoptimization.cpp
48785 views
/*1* Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/systemDictionary.hpp"26#include "code/debugInfoRec.hpp"27#include "code/nmethod.hpp"28#include "code/pcDesc.hpp"29#include "code/scopeDesc.hpp"30#include "interpreter/bytecode.hpp"31#include "interpreter/interpreter.hpp"32#include "interpreter/oopMapCache.hpp"33#include "memory/allocation.inline.hpp"34#include "memory/oopFactory.hpp"35#include "memory/resourceArea.hpp"36#include "oops/method.hpp"37#include "oops/oop.inline.hpp"38#include "prims/jvmtiThreadState.hpp"39#include "runtime/biasedLocking.hpp"40#include "runtime/compilationPolicy.hpp"41#include "runtime/deoptimization.hpp"42#include "runtime/interfaceSupport.hpp"43#include "runtime/sharedRuntime.hpp"44#include "runtime/signature.hpp"45#include "runtime/stubRoutines.hpp"46#include "runtime/thread.hpp"47#include "runtime/vframe.hpp"48#include "runtime/vframeArray.hpp"49#include "runtime/vframe_hp.hpp"50#include "utilities/events.hpp"51#include "utilities/xmlstream.hpp"52#ifdef TARGET_ARCH_x8653# include "vmreg_x86.inline.hpp"54#endif55#ifdef TARGET_ARCH_aarch6456# include "vmreg_aarch64.inline.hpp"57#endif58#ifdef TARGET_ARCH_sparc59# include "vmreg_sparc.inline.hpp"60#endif61#ifdef TARGET_ARCH_zero62# include "vmreg_zero.inline.hpp"63#endif64#ifdef TARGET_ARCH_arm65# include "vmreg_arm.inline.hpp"66#endif67#ifdef TARGET_ARCH_ppc68# include "vmreg_ppc.inline.hpp"69#endif70#ifdef TARGET_ARCH_aarch3271# include "vmreg_aarch32.inline.hpp"72#endif73#ifdef COMPILER274#if defined AD_MD_HPP75# include AD_MD_HPP76#elif defined TARGET_ARCH_MODEL_x86_3277# include "adfiles/ad_x86_32.hpp"78#elif defined TARGET_ARCH_MODEL_x86_6479# include "adfiles/ad_x86_64.hpp"80#elif defined TARGET_ARCH_MODEL_aarch6481# include "adfiles/ad_aarch64.hpp"82#elif defined TARGET_ARCH_MODEL_sparc83# include "adfiles/ad_sparc.hpp"84#elif defined TARGET_ARCH_MODEL_zero85# include "adfiles/ad_zero.hpp"86#elif defined TARGET_ARCH_MODEL_ppc_6487# include "adfiles/ad_ppc_64.hpp"88#elif defined TARGET_ARCH_MODEL_aarch3289# include "adfiles/ad_aarch32.hpp"90#endif91#endif // COMPILER29293PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC9495bool DeoptimizationMarker::_is_active = false;9697Deoptimization::UnrollBlock::UnrollBlock(int size_of_deoptimized_frame,98int caller_adjustment,99int caller_actual_parameters,100int number_of_frames,101intptr_t* frame_sizes,102address* frame_pcs,103BasicType return_type) {104_size_of_deoptimized_frame = size_of_deoptimized_frame;105_caller_adjustment = caller_adjustment;106_caller_actual_parameters = caller_actual_parameters;107_number_of_frames = number_of_frames;108_frame_sizes = frame_sizes;109_frame_pcs = frame_pcs;110_register_block = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);111_return_type = return_type;112_initial_info = 0;113// PD (x86 only)114_counter_temp = 0;115_unpack_kind = 0;116_sender_sp_temp = 0;117118_total_frame_sizes = size_of_frames();119}120121122Deoptimization::UnrollBlock::~UnrollBlock() {123FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes, mtCompiler);124FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs, mtCompiler);125FREE_C_HEAP_ARRAY(intptr_t, _register_block, mtCompiler);126}127128129intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const {130assert(register_number < RegisterMap::reg_count, "checking register number");131return &_register_block[register_number * 2];132}133134135136int Deoptimization::UnrollBlock::size_of_frames() const {137// Acount first for the adjustment of the initial frame138int result = _caller_adjustment;139for (int index = 0; index < number_of_frames(); index++) {140result += frame_sizes()[index];141}142return result;143}144145146void Deoptimization::UnrollBlock::print() {147ttyLocker ttyl;148tty->print_cr("UnrollBlock");149tty->print_cr(" size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);150tty->print( " frame_sizes: ");151for (int index = 0; index < number_of_frames(); index++) {152tty->print("%d ", frame_sizes()[index]);153}154tty->cr();155}156157158// In order to make fetch_unroll_info work properly with escape159// analysis, The method was changed from JRT_LEAF to JRT_BLOCK_ENTRY and160// ResetNoHandleMark and HandleMark were removed from it. The actual reallocation161// of previously eliminated objects occurs in realloc_objects, which is162// called from the method fetch_unroll_info_helper below.163JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* thread))164// It is actually ok to allocate handles in a leaf method. It causes no safepoints,165// but makes the entry a little slower. There is however a little dance we have to166// do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro167168// fetch_unroll_info() is called at the beginning of the deoptimization169// handler. Note this fact before we start generating temporary frames170// that can confuse an asynchronous stack walker. This counter is171// decremented at the end of unpack_frames().172thread->inc_in_deopt_handler();173174return fetch_unroll_info_helper(thread);175JRT_END176177178// This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)179Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* thread) {180181// Note: there is a safepoint safety issue here. No matter whether we enter182// via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once183// the vframeArray is created.184//185186// Allocate our special deoptimization ResourceMark187DeoptResourceMark* dmark = new DeoptResourceMark(thread);188assert(thread->deopt_mark() == NULL, "Pending deopt!");189thread->set_deopt_mark(dmark);190191frame stub_frame = thread->last_frame(); // Makes stack walkable as side effect192RegisterMap map(thread, true);193RegisterMap dummy_map(thread, false);194// Now get the deoptee with a valid map195frame deoptee = stub_frame.sender(&map);196// Set the deoptee nmethod197assert(thread->deopt_nmethod() == NULL, "Pending deopt!");198thread->set_deopt_nmethod(deoptee.cb()->as_nmethod_or_null());199200if (VerifyStack) {201thread->validate_frame_layout();202}203204// Create a growable array of VFrames where each VFrame represents an inlined205// Java frame. This storage is allocated with the usual system arena.206assert(deoptee.is_compiled_frame(), "Wrong frame type");207GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);208vframe* vf = vframe::new_vframe(&deoptee, &map, thread);209while (!vf->is_top()) {210assert(vf->is_compiled_frame(), "Wrong frame type");211chunk->push(compiledVFrame::cast(vf));212vf = vf->sender();213}214assert(vf->is_compiled_frame(), "Wrong frame type");215chunk->push(compiledVFrame::cast(vf));216217bool realloc_failures = false;218219#ifdef COMPILER2220// Reallocate the non-escaping objects and restore their fields. Then221// relock objects if synchronization on them was eliminated.222if (DoEscapeAnalysis || EliminateNestedLocks) {223if (EliminateAllocations) {224assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames");225GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects();226227// The flag return_oop() indicates call sites which return oop228// in compiled code. Such sites include java method calls,229// runtime calls (for example, used to allocate new objects/arrays230// on slow code path) and any other calls generated in compiled code.231// It is not guaranteed that we can get such information here only232// by analyzing bytecode in deoptimized frames. This is why this flag233// is set during method compilation (see Compile::Process_OopMap_Node()).234// If the previous frame was popped, we don't have a result.235bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution();236Handle return_value;237if (save_oop_result) {238// Reallocation may trigger GC. If deoptimization happened on return from239// call which returns oop we need to save it since it is not in oopmap.240oop result = deoptee.saved_oop_result(&map);241assert(result == NULL || result->is_oop(), "must be oop");242return_value = Handle(thread, result);243assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");244if (TraceDeoptimization) {245ttyLocker ttyl;246tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, (void *)result, thread);247}248}249if (objects != NULL) {250JRT_BLOCK251realloc_failures = realloc_objects(thread, &deoptee, objects, THREAD);252JRT_END253reassign_fields(&deoptee, &map, objects, realloc_failures);254#ifndef PRODUCT255if (TraceDeoptimization) {256ttyLocker ttyl;257tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, thread);258print_objects(objects, realloc_failures);259}260#endif261}262if (save_oop_result) {263// Restore result.264deoptee.set_saved_oop_result(&map, return_value());265}266}267if (EliminateLocks) {268#ifndef PRODUCT269bool first = true;270#endif271for (int i = 0; i < chunk->length(); i++) {272compiledVFrame* cvf = chunk->at(i);273assert (cvf->scope() != NULL,"expect only compiled java frames");274GrowableArray<MonitorInfo*>* monitors = cvf->monitors();275if (monitors->is_nonempty()) {276relock_objects(monitors, thread, realloc_failures);277#ifndef PRODUCT278if (TraceDeoptimization) {279ttyLocker ttyl;280for (int j = 0; j < monitors->length(); j++) {281MonitorInfo* mi = monitors->at(j);282if (mi->eliminated()) {283if (first) {284first = false;285tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, thread);286}287if (mi->owner_is_scalar_replaced()) {288Klass* k = java_lang_Class::as_Klass(mi->owner_klass());289tty->print_cr(" failed reallocation for klass %s", k->external_name());290} else {291tty->print_cr(" object <" INTPTR_FORMAT "> locked", (void *)mi->owner());292}293}294}295}296#endif297}298}299}300}301#endif // COMPILER2302// Ensure that no safepoint is taken after pointers have been stored303// in fields of rematerialized objects. If a safepoint occurs from here on304// out the java state residing in the vframeArray will be missed.305No_Safepoint_Verifier no_safepoint;306307vframeArray* array = create_vframeArray(thread, deoptee, &map, chunk, realloc_failures);308#ifdef COMPILER2309if (realloc_failures) {310pop_frames_failed_reallocs(thread, array);311}312#endif313314assert(thread->vframe_array_head() == NULL, "Pending deopt!");315thread->set_vframe_array_head(array);316317// Now that the vframeArray has been created if we have any deferred local writes318// added by jvmti then we can free up that structure as the data is now in the319// vframeArray320321if (thread->deferred_locals() != NULL) {322GrowableArray<jvmtiDeferredLocalVariableSet*>* list = thread->deferred_locals();323int i = 0;324do {325// Because of inlining we could have multiple vframes for a single frame326// and several of the vframes could have deferred writes. Find them all.327if (list->at(i)->id() == array->original().id()) {328jvmtiDeferredLocalVariableSet* dlv = list->at(i);329list->remove_at(i);330// individual jvmtiDeferredLocalVariableSet are CHeapObj's331delete dlv;332} else {333i++;334}335} while ( i < list->length() );336if (list->length() == 0) {337thread->set_deferred_locals(NULL);338// free the list and elements back to C heap.339delete list;340}341342}343344#ifndef SHARK345// Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.346CodeBlob* cb = stub_frame.cb();347// Verify we have the right vframeArray348assert(cb->frame_size() >= 0, "Unexpected frame size");349intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();350351// If the deopt call site is a MethodHandle invoke call site we have352// to adjust the unpack_sp.353nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null();354if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc()))355unpack_sp = deoptee.unextended_sp();356357#ifdef ASSERT358assert(cb->is_deoptimization_stub() || cb->is_uncommon_trap_stub(), "just checking");359#endif360#else361intptr_t* unpack_sp = stub_frame.sender(&dummy_map).unextended_sp();362#endif // !SHARK363364// This is a guarantee instead of an assert because if vframe doesn't match365// we will unpack the wrong deoptimized frame and wind up in strange places366// where it will be very difficult to figure out what went wrong. Better367// to die an early death here than some very obscure death later when the368// trail is cold.369// Note: on ia64 this guarantee can be fooled by frames with no memory stack370// in that it will fail to detect a problem when there is one. This needs371// more work in tiger timeframe.372guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");373374int number_of_frames = array->frames();375376// Compute the vframes' sizes. Note that frame_sizes[] entries are ordered from outermost to innermost377// virtual activation, which is the reverse of the elements in the vframes array.378intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);379// +1 because we always have an interpreter return address for the final slot.380address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);381int popframe_extra_args = 0;382// Create an interpreter return address for the stub to use as its return383// address so the skeletal frames are perfectly walkable384frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);385386// PopFrame requires that the preserved incoming arguments from the recently-popped topmost387// activation be put back on the expression stack of the caller for reexecution388if (JvmtiExport::can_pop_frame() && thread->popframe_forcing_deopt_reexecution()) {389popframe_extra_args = in_words(thread->popframe_preserved_args_size_in_words());390}391392// Find the current pc for sender of the deoptee. Since the sender may have been deoptimized393// itself since the deoptee vframeArray was created we must get a fresh value of the pc rather394// than simply use array->sender.pc(). This requires us to walk the current set of frames395//396frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame397deopt_sender = deopt_sender.sender(&dummy_map); // Now deoptee caller398399// It's possible that the number of paramters at the call site is400// different than number of arguments in the callee when method401// handles are used. If the caller is interpreted get the real402// value so that the proper amount of space can be added to it's403// frame.404bool caller_was_method_handle = false;405if (deopt_sender.is_interpreted_frame()) {406methodHandle method = deopt_sender.interpreter_frame_method();407Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci());408if (cur.is_invokedynamic() || cur.is_invokehandle()) {409// Method handle invokes may involve fairly arbitrary chains of410// calls so it's impossible to know how much actual space the411// caller has for locals.412caller_was_method_handle = true;413}414}415416//417// frame_sizes/frame_pcs[0] oldest frame (int or c2i)418// frame_sizes/frame_pcs[1] next oldest frame (int)419// frame_sizes/frame_pcs[n] youngest frame (int)420//421// Now a pc in frame_pcs is actually the return address to the frame's caller (a frame422// owns the space for the return address to it's caller). Confusing ain't it.423//424// The vframe array can address vframes with indices running from425// 0.._frames-1. Index 0 is the youngest frame and _frame - 1 is the oldest (root) frame.426// When we create the skeletal frames we need the oldest frame to be in the zero slot427// in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.428// so things look a little strange in this loop.429//430int callee_parameters = 0;431int callee_locals = 0;432for (int index = 0; index < array->frames(); index++ ) {433// frame[number_of_frames - 1 ] = on_stack_size(youngest)434// frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))435// frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))436frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,437callee_locals,438index == 0,439popframe_extra_args);440// This pc doesn't have to be perfect just good enough to identify the frame441// as interpreted so the skeleton frame will be walkable442// The correct pc will be set when the skeleton frame is completely filled out443// The final pc we store in the loop is wrong and will be overwritten below444frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;445446callee_parameters = array->element(index)->method()->size_of_parameters();447callee_locals = array->element(index)->method()->max_locals();448popframe_extra_args = 0;449}450451// Compute whether the root vframe returns a float or double value.452BasicType return_type;453{454HandleMark hm;455methodHandle method(thread, array->element(0)->method());456Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());457return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;458}459460// Compute information for handling adapters and adjusting the frame size of the caller.461int caller_adjustment = 0;462463// Compute the amount the oldest interpreter frame will have to adjust464// its caller's stack by. If the caller is a compiled frame then465// we pretend that the callee has no parameters so that the466// extension counts for the full amount of locals and not just467// locals-parms. This is because without a c2i adapter the parm468// area as created by the compiled frame will not be usable by469// the interpreter. (Depending on the calling convention there470// may not even be enough space).471472// QQQ I'd rather see this pushed down into last_frame_adjust473// and have it take the sender (aka caller).474475if (deopt_sender.is_compiled_frame() || caller_was_method_handle) {476caller_adjustment = last_frame_adjust(0, callee_locals);477} else if (callee_locals > callee_parameters) {478// The caller frame may need extending to accommodate479// non-parameter locals of the first unpacked interpreted frame.480// Compute that adjustment.481caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);482}483484// If the sender is deoptimized the we must retrieve the address of the handler485// since the frame will "magically" show the original pc before the deopt486// and we'd undo the deopt.487488frame_pcs[0] = deopt_sender.raw_pc();489490#ifndef SHARK491assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc");492#endif // SHARK493494UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,495caller_adjustment * BytesPerWord,496caller_was_method_handle ? 0 : callee_parameters,497number_of_frames,498frame_sizes,499frame_pcs,500return_type);501// On some platforms, we need a way to pass some platform dependent502// information to the unpacking code so the skeletal frames come out503// correct (initial fp value, unextended sp, ...)504info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());505506if (array->frames() > 1) {507if (VerifyStack && TraceDeoptimization) {508ttyLocker ttyl;509tty->print_cr("Deoptimizing method containing inlining");510}511}512513array->set_unroll_block(info);514return info;515}516517// Called to cleanup deoptimization data structures in normal case518// after unpacking to stack and when stack overflow error occurs519void Deoptimization::cleanup_deopt_info(JavaThread *thread,520vframeArray *array) {521522// Get array if coming from exception523if (array == NULL) {524array = thread->vframe_array_head();525}526thread->set_vframe_array_head(NULL);527528// Free the previous UnrollBlock529vframeArray* old_array = thread->vframe_array_last();530thread->set_vframe_array_last(array);531532if (old_array != NULL) {533UnrollBlock* old_info = old_array->unroll_block();534old_array->set_unroll_block(NULL);535delete old_info;536delete old_array;537}538539// Deallocate any resource creating in this routine and any ResourceObjs allocated540// inside the vframeArray (StackValueCollections)541542delete thread->deopt_mark();543thread->set_deopt_mark(NULL);544thread->set_deopt_nmethod(NULL);545546547if (JvmtiExport::can_pop_frame()) {548#ifndef CC_INTERP549// Regardless of whether we entered this routine with the pending550// popframe condition bit set, we should always clear it now551thread->clear_popframe_condition();552#else553// C++ interpeter will clear has_pending_popframe when it enters554// with method_resume. For deopt_resume2 we clear it now.555if (thread->popframe_forcing_deopt_reexecution())556thread->clear_popframe_condition();557#endif /* CC_INTERP */558}559560// unpack_frames() is called at the end of the deoptimization handler561// and (in C2) at the end of the uncommon trap handler. Note this fact562// so that an asynchronous stack walker can work again. This counter is563// incremented at the beginning of fetch_unroll_info() and (in C2) at564// the beginning of uncommon_trap().565thread->dec_in_deopt_handler();566}567568569// Return BasicType of value being returned570JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))571572// We are already active int he special DeoptResourceMark any ResourceObj's we573// allocate will be freed at the end of the routine.574575// It is actually ok to allocate handles in a leaf method. It causes no safepoints,576// but makes the entry a little slower. There is however a little dance we have to577// do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro578ResetNoHandleMark rnhm; // No-op in release/product versions579HandleMark hm;580581frame stub_frame = thread->last_frame();582583// Since the frame to unpack is the top frame of this thread, the vframe_array_head584// must point to the vframeArray for the unpack frame.585vframeArray* array = thread->vframe_array_head();586587#ifndef PRODUCT588if (TraceDeoptimization) {589ttyLocker ttyl;590tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d", thread, array, exec_mode);591}592#endif593Events::log(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d",594stub_frame.pc(), stub_frame.sp(), exec_mode);595596UnrollBlock* info = array->unroll_block();597598// Unpack the interpreter frames and any adapter frame (c2 only) we might create.599array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());600601BasicType bt = info->return_type();602603// If we have an exception pending, claim that the return type is an oop604// so the deopt_blob does not overwrite the exception_oop.605606if (exec_mode == Unpack_exception)607bt = T_OBJECT;608609// Cleanup thread deopt data610cleanup_deopt_info(thread, array);611612#ifndef PRODUCT613if (VerifyStack) {614ResourceMark res_mark;615616thread->validate_frame_layout();617618// Verify that the just-unpacked frames match the interpreter's619// notions of expression stack and locals620vframeArray* cur_array = thread->vframe_array_last();621RegisterMap rm(thread, false);622rm.set_include_argument_oops(false);623bool is_top_frame = true;624int callee_size_of_parameters = 0;625int callee_max_locals = 0;626for (int i = 0; i < cur_array->frames(); i++) {627vframeArrayElement* el = cur_array->element(i);628frame* iframe = el->iframe();629guarantee(iframe->is_interpreted_frame(), "Wrong frame type");630631// Get the oop map for this bci632InterpreterOopMap mask;633int cur_invoke_parameter_size = 0;634bool try_next_mask = false;635int next_mask_expression_stack_size = -1;636int top_frame_expression_stack_adjustment = 0;637methodHandle mh(thread, iframe->interpreter_frame_method());638OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask);639BytecodeStream str(mh);640str.set_start(iframe->interpreter_frame_bci());641int max_bci = mh->code_size();642// Get to the next bytecode if possible643assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");644// Check to see if we can grab the number of outgoing arguments645// at an uncommon trap for an invoke (where the compiler646// generates debug info before the invoke has executed)647Bytecodes::Code cur_code = str.next();648if (cur_code == Bytecodes::_invokevirtual ||649cur_code == Bytecodes::_invokespecial ||650cur_code == Bytecodes::_invokestatic ||651cur_code == Bytecodes::_invokeinterface ||652cur_code == Bytecodes::_invokedynamic) {653Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci());654Symbol* signature = invoke.signature();655ArgumentSizeComputer asc(signature);656cur_invoke_parameter_size = asc.size();657if (invoke.has_receiver()) {658// Add in receiver659++cur_invoke_parameter_size;660}661if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) {662callee_size_of_parameters++;663}664}665if (str.bci() < max_bci) {666Bytecodes::Code bc = str.next();667if (bc >= 0) {668// The interpreter oop map generator reports results before669// the current bytecode has executed except in the case of670// calls. It seems to be hard to tell whether the compiler671// has emitted debug information matching the "state before"672// a given bytecode or the state after, so we try both673switch (cur_code) {674case Bytecodes::_invokevirtual:675case Bytecodes::_invokespecial:676case Bytecodes::_invokestatic:677case Bytecodes::_invokeinterface:678case Bytecodes::_invokedynamic:679case Bytecodes::_athrow:680break;681default: {682InterpreterOopMap next_mask;683OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask);684next_mask_expression_stack_size = next_mask.expression_stack_size();685// Need to subtract off the size of the result type of686// the bytecode because this is not described in the687// debug info but returned to the interpreter in the TOS688// caching register689BasicType bytecode_result_type = Bytecodes::result_type(cur_code);690if (bytecode_result_type != T_ILLEGAL) {691top_frame_expression_stack_adjustment = type2size[bytecode_result_type];692}693assert(top_frame_expression_stack_adjustment >= 0, "");694try_next_mask = true;695break;696}697}698}699}700701// Verify stack depth and oops in frame702// This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc)703if (!(704/* SPARC */705(iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) ||706/* x86 */707(iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) ||708(try_next_mask &&709(iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size -710top_frame_expression_stack_adjustment))) ||711(is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) ||712(is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute || el->should_reexecute()) &&713(iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size))714)) {715ttyLocker ttyl;716717// Print out some information that will help us debug the problem718tty->print_cr("Wrong number of expression stack elements during deoptimization");719tty->print_cr(" Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1);720tty->print_cr(" Fabricated interpreter frame had %d expression stack elements",721iframe->interpreter_frame_expression_stack_size());722tty->print_cr(" Interpreter oop map had %d expression stack elements", mask.expression_stack_size());723tty->print_cr(" try_next_mask = %d", try_next_mask);724tty->print_cr(" next_mask_expression_stack_size = %d", next_mask_expression_stack_size);725tty->print_cr(" callee_size_of_parameters = %d", callee_size_of_parameters);726tty->print_cr(" callee_max_locals = %d", callee_max_locals);727tty->print_cr(" top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);728tty->print_cr(" exec_mode = %d", exec_mode);729tty->print_cr(" cur_invoke_parameter_size = %d", cur_invoke_parameter_size);730tty->print_cr(" Thread = " INTPTR_FORMAT ", thread ID = " UINTX_FORMAT, thread, thread->osthread()->thread_id());731tty->print_cr(" Interpreted frames:");732for (int k = 0; k < cur_array->frames(); k++) {733vframeArrayElement* el = cur_array->element(k);734tty->print_cr(" %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());735}736cur_array->print_on_2(tty);737guarantee(false, "wrong number of expression stack elements during deopt");738}739VerifyOopClosure verify;740iframe->oops_interpreted_do(&verify, NULL, &rm, false);741callee_size_of_parameters = mh->size_of_parameters();742callee_max_locals = mh->max_locals();743is_top_frame = false;744}745}746#endif /* !PRODUCT */747748749return bt;750JRT_END751752753int Deoptimization::deoptimize_dependents() {754Threads::deoptimized_wrt_marked_nmethods();755return 0;756}757758759#ifdef COMPILER2760bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, GrowableArray<ScopeValue*>* objects, TRAPS) {761Handle pending_exception(thread->pending_exception());762const char* exception_file = thread->exception_file();763int exception_line = thread->exception_line();764thread->clear_pending_exception();765766bool failures = false;767768for (int i = 0; i < objects->length(); i++) {769assert(objects->at(i)->is_object(), "invalid debug information");770ObjectValue* sv = (ObjectValue*) objects->at(i);771772KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));773oop obj = NULL;774775if (k->oop_is_instance()) {776InstanceKlass* ik = InstanceKlass::cast(k());777obj = ik->allocate_instance(THREAD);778} else if (k->oop_is_typeArray()) {779TypeArrayKlass* ak = TypeArrayKlass::cast(k());780assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");781int len = sv->field_size() / type2size[ak->element_type()];782obj = ak->allocate(len, THREAD);783} else if (k->oop_is_objArray()) {784ObjArrayKlass* ak = ObjArrayKlass::cast(k());785obj = ak->allocate(sv->field_size(), THREAD);786}787788if (obj == NULL) {789failures = true;790}791792assert(sv->value().is_null(), "redundant reallocation");793assert(obj != NULL || HAS_PENDING_EXCEPTION, "allocation should succeed or we should get an exception");794CLEAR_PENDING_EXCEPTION;795sv->set_value(obj);796}797798if (failures) {799THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);800} else if (pending_exception.not_null()) {801thread->set_pending_exception(pending_exception(), exception_file, exception_line);802}803804return failures;805}806807// This assumes that the fields are stored in ObjectValue in the same order808// they are yielded by do_nonstatic_fields.809class FieldReassigner: public FieldClosure {810frame* _fr;811RegisterMap* _reg_map;812ObjectValue* _sv;813InstanceKlass* _ik;814oop _obj;815816int _i;817public:818FieldReassigner(frame* fr, RegisterMap* reg_map, ObjectValue* sv, oop obj) :819_fr(fr), _reg_map(reg_map), _sv(sv), _obj(obj), _i(0) {}820821int i() const { return _i; }822823824void do_field(fieldDescriptor* fd) {825intptr_t val;826StackValue* value =827StackValue::create_stack_value(_fr, _reg_map, _sv->field_at(i()));828int offset = fd->offset();829switch (fd->field_type()) {830case T_OBJECT: case T_ARRAY:831assert(value->type() == T_OBJECT, "Agreement.");832_obj->obj_field_put(offset, value->get_obj()());833break;834835case T_LONG: case T_DOUBLE: {836assert(value->type() == T_INT, "Agreement.");837StackValue* low =838StackValue::create_stack_value(_fr, _reg_map, _sv->field_at(++_i));839#ifdef _LP64840jlong res = (jlong)low->get_int();841#else842#ifdef SPARC843// For SPARC we have to swap high and low words.844jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());845#else846jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());847#endif //SPARC848#endif849_obj->long_field_put(offset, res);850break;851}852// Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.853case T_INT: case T_FLOAT: // 4 bytes.854assert(value->type() == T_INT, "Agreement.");855val = value->get_int();856_obj->int_field_put(offset, (jint)*((jint*)&val));857break;858859case T_SHORT:860assert(value->type() == T_INT, "Agreement.");861val = value->get_int();862_obj->short_field_put(offset, (jshort)*((jint*)&val));863break;864865case T_CHAR:866assert(value->type() == T_INT, "Agreement.");867val = value->get_int();868_obj->char_field_put(offset, (jchar)*((jint*)&val));869break;870871case T_BYTE:872assert(value->type() == T_INT, "Agreement.");873val = value->get_int();874_obj->byte_field_put(offset, (jbyte)*((jint*)&val));875break;876877case T_BOOLEAN:878assert(value->type() == T_INT, "Agreement.");879val = value->get_int();880_obj->bool_field_put(offset, (jboolean)*((jint*)&val));881break;882883default:884ShouldNotReachHere();885}886_i++;887}888};889890// restore elements of an eliminated type array891void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {892int index = 0;893intptr_t val;894895for (int i = 0; i < sv->field_size(); i++) {896StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));897switch(type) {898case T_LONG: case T_DOUBLE: {899assert(value->type() == T_INT, "Agreement.");900StackValue* low =901StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));902#ifdef _LP64903jlong res = (jlong)low->get_int();904#else905#ifdef SPARC906// For SPARC we have to swap high and low words.907jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());908#else909jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());910#endif //SPARC911#endif912obj->long_at_put(index, res);913break;914}915916// Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.917case T_INT: case T_FLOAT: // 4 bytes.918assert(value->type() == T_INT, "Agreement.");919val = value->get_int();920obj->int_at_put(index, (jint)*((jint*)&val));921break;922923case T_SHORT:924assert(value->type() == T_INT, "Agreement.");925val = value->get_int();926obj->short_at_put(index, (jshort)*((jint*)&val));927break;928929case T_CHAR:930assert(value->type() == T_INT, "Agreement.");931val = value->get_int();932obj->char_at_put(index, (jchar)*((jint*)&val));933break;934935case T_BYTE:936assert(value->type() == T_INT, "Agreement.");937val = value->get_int();938obj->byte_at_put(index, (jbyte)*((jint*)&val));939break;940941case T_BOOLEAN:942assert(value->type() == T_INT, "Agreement.");943val = value->get_int();944obj->bool_at_put(index, (jboolean)*((jint*)&val));945break;946947default:948ShouldNotReachHere();949}950index++;951}952}953954955// restore fields of an eliminated object array956void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {957for (int i = 0; i < sv->field_size(); i++) {958StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));959assert(value->type() == T_OBJECT, "object element expected");960obj->obj_at_put(i, value->get_obj()());961}962}963964965// restore fields of all eliminated objects and arrays966void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures) {967for (int i = 0; i < objects->length(); i++) {968ObjectValue* sv = (ObjectValue*) objects->at(i);969KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));970Handle obj = sv->value();971assert(obj.not_null() || realloc_failures, "reallocation was missed");972if (obj.is_null()) {973continue;974}975976if (k->oop_is_instance()) {977InstanceKlass* ik = InstanceKlass::cast(k());978FieldReassigner reassign(fr, reg_map, sv, obj());979ik->do_nonstatic_fields(&reassign);980} else if (k->oop_is_typeArray()) {981TypeArrayKlass* ak = TypeArrayKlass::cast(k());982reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());983} else if (k->oop_is_objArray()) {984reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());985}986}987}988989990// relock objects for which synchronization was eliminated991void Deoptimization::relock_objects(GrowableArray<MonitorInfo*>* monitors, JavaThread* thread, bool realloc_failures) {992for (int i = 0; i < monitors->length(); i++) {993MonitorInfo* mon_info = monitors->at(i);994if (mon_info->eliminated()) {995assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");996if (!mon_info->owner_is_scalar_replaced()) {997Handle obj = Handle(mon_info->owner());998markOop mark = obj->mark();999if (UseBiasedLocking && mark->has_bias_pattern()) {1000// New allocated objects may have the mark set to anonymously biased.1001// Also the deoptimized method may called methods with synchronization1002// where the thread-local object is bias locked to the current thread.1003assert(mark->is_biased_anonymously() ||1004mark->biased_locker() == thread, "should be locked to current thread");1005// Reset mark word to unbiased prototype.1006markOop unbiased_prototype = markOopDesc::prototype()->set_age(mark->age());1007obj->set_mark(unbiased_prototype);1008}1009BasicLock* lock = mon_info->lock();1010ObjectSynchronizer::slow_enter(obj, lock, thread);1011assert(mon_info->owner()->is_locked(), "object must be locked now");1012}1013}1014}1015}101610171018#ifndef PRODUCT1019// print information about reallocated objects1020void Deoptimization::print_objects(GrowableArray<ScopeValue*>* objects, bool realloc_failures) {1021fieldDescriptor fd;10221023for (int i = 0; i < objects->length(); i++) {1024ObjectValue* sv = (ObjectValue*) objects->at(i);1025KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));1026Handle obj = sv->value();10271028tty->print(" object <" INTPTR_FORMAT "> of type ", (void *)sv->value()());1029k->print_value();1030assert(obj.not_null() || realloc_failures, "reallocation was missed");1031if (obj.is_null()) {1032tty->print(" allocation failed");1033} else {1034tty->print(" allocated (%d bytes)", obj->size() * HeapWordSize);1035}1036tty->cr();10371038if (Verbose && !obj.is_null()) {1039k->oop_print_on(obj(), tty);1040}1041}1042}1043#endif1044#endif // COMPILER210451046vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {1047Events::log(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, fr.pc(), fr.sp());10481049#ifndef PRODUCT1050if (TraceDeoptimization) {1051ttyLocker ttyl;1052tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", thread);1053fr.print_on(tty);1054tty->print_cr(" Virtual frames (innermost first):");1055for (int index = 0; index < chunk->length(); index++) {1056compiledVFrame* vf = chunk->at(index);1057tty->print(" %2d - ", index);1058vf->print_value();1059int bci = chunk->at(index)->raw_bci();1060const char* code_name;1061if (bci == SynchronizationEntryBCI) {1062code_name = "sync entry";1063} else {1064Bytecodes::Code code = vf->method()->code_at(bci);1065code_name = Bytecodes::name(code);1066}1067tty->print(" - %s", code_name);1068tty->print_cr(" @ bci %d ", bci);1069if (Verbose) {1070vf->print();1071tty->cr();1072}1073}1074}1075#endif10761077// Register map for next frame (used for stack crawl). We capture1078// the state of the deopt'ing frame's caller. Thus if we need to1079// stuff a C2I adapter we can properly fill in the callee-save1080// register locations.1081frame caller = fr.sender(reg_map);1082int frame_size = caller.sp() - fr.sp();10831084frame sender = caller;10851086// Since the Java thread being deoptimized will eventually adjust it's own stack,1087// the vframeArray containing the unpacking information is allocated in the C heap.1088// For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().1089vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures);10901091// Compare the vframeArray to the collected vframes1092assert(array->structural_compare(thread, chunk), "just checking");10931094#ifndef PRODUCT1095if (TraceDeoptimization) {1096ttyLocker ttyl;1097tty->print_cr(" Created vframeArray " INTPTR_FORMAT, array);1098}1099#endif // PRODUCT11001101return array;1102}11031104#ifdef COMPILER21105void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) {1106// Reallocation of some scalar replaced objects failed. Record1107// that we need to pop all the interpreter frames for the1108// deoptimized compiled frame.1109assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?");1110thread->set_frames_to_pop_failed_realloc(array->frames());1111// Unlock all monitors here otherwise the interpreter will see a1112// mix of locked and unlocked monitors (because of failed1113// reallocations of synchronized objects) and be confused.1114for (int i = 0; i < array->frames(); i++) {1115MonitorChunk* monitors = array->element(i)->monitors();1116if (monitors != NULL) {1117for (int j = 0; j < monitors->number_of_monitors(); j++) {1118BasicObjectLock* src = monitors->at(j);1119if (src->obj() != NULL) {1120ObjectSynchronizer::fast_exit(src->obj(), src->lock(), thread);1121}1122}1123array->element(i)->free_monitors(thread);1124#ifdef ASSERT1125array->element(i)->set_removed_monitors();1126#endif1127}1128}1129}1130#endif11311132static void collect_monitors(compiledVFrame* cvf, GrowableArray<Handle>* objects_to_revoke) {1133GrowableArray<MonitorInfo*>* monitors = cvf->monitors();1134for (int i = 0; i < monitors->length(); i++) {1135MonitorInfo* mon_info = monitors->at(i);1136if (!mon_info->eliminated() && mon_info->owner() != NULL) {1137objects_to_revoke->append(Handle(mon_info->owner()));1138}1139}1140}114111421143void Deoptimization::revoke_biases_of_monitors(JavaThread* thread, frame fr, RegisterMap* map) {1144if (!UseBiasedLocking) {1145return;1146}11471148GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();11491150// Unfortunately we don't have a RegisterMap available in most of1151// the places we want to call this routine so we need to walk the1152// stack again to update the register map.1153if (map == NULL || !map->update_map()) {1154StackFrameStream sfs(thread, true);1155bool found = false;1156while (!found && !sfs.is_done()) {1157frame* cur = sfs.current();1158sfs.next();1159found = cur->id() == fr.id();1160}1161assert(found, "frame to be deoptimized not found on target thread's stack");1162map = sfs.register_map();1163}11641165vframe* vf = vframe::new_vframe(&fr, map, thread);1166compiledVFrame* cvf = compiledVFrame::cast(vf);1167// Revoke monitors' biases in all scopes1168while (!cvf->is_top()) {1169collect_monitors(cvf, objects_to_revoke);1170cvf = compiledVFrame::cast(cvf->sender());1171}1172collect_monitors(cvf, objects_to_revoke);11731174if (SafepointSynchronize::is_at_safepoint()) {1175BiasedLocking::revoke_at_safepoint(objects_to_revoke);1176} else {1177BiasedLocking::revoke(objects_to_revoke);1178}1179}118011811182void Deoptimization::revoke_biases_of_monitors(CodeBlob* cb) {1183if (!UseBiasedLocking) {1184return;1185}11861187assert(SafepointSynchronize::is_at_safepoint(), "must only be called from safepoint");1188GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();1189for (JavaThread* jt = Threads::first(); jt != NULL ; jt = jt->next()) {1190if (jt->has_last_Java_frame()) {1191StackFrameStream sfs(jt, true);1192while (!sfs.is_done()) {1193frame* cur = sfs.current();1194if (cb->contains(cur->pc())) {1195vframe* vf = vframe::new_vframe(cur, sfs.register_map(), jt);1196compiledVFrame* cvf = compiledVFrame::cast(vf);1197// Revoke monitors' biases in all scopes1198while (!cvf->is_top()) {1199collect_monitors(cvf, objects_to_revoke);1200cvf = compiledVFrame::cast(cvf->sender());1201}1202collect_monitors(cvf, objects_to_revoke);1203}1204sfs.next();1205}1206}1207}1208BiasedLocking::revoke_at_safepoint(objects_to_revoke);1209}121012111212void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr) {1213assert(fr.can_be_deoptimized(), "checking frame type");12141215gather_statistics(Reason_constraint, Action_none, Bytecodes::_illegal);12161217// Patch the nmethod so that when execution returns to it we will1218// deopt the execution state and return to the interpreter.1219fr.deoptimize(thread);1220}12211222void Deoptimization::deoptimize(JavaThread* thread, frame fr, RegisterMap *map) {1223// Deoptimize only if the frame comes from compile code.1224// Do not deoptimize the frame which is already patched1225// during the execution of the loops below.1226if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {1227return;1228}1229ResourceMark rm;1230DeoptimizationMarker dm;1231if (UseBiasedLocking) {1232revoke_biases_of_monitors(thread, fr, map);1233}1234deoptimize_single_frame(thread, fr);12351236}123712381239void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id) {1240assert(thread == Thread::current() || SafepointSynchronize::is_at_safepoint(),1241"can only deoptimize other thread at a safepoint");1242// Compute frame and register map based on thread and sp.1243RegisterMap reg_map(thread, UseBiasedLocking);1244frame fr = thread->last_frame();1245while (fr.id() != id) {1246fr = fr.sender(®_map);1247}1248deoptimize(thread, fr, ®_map);1249}125012511252void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {1253if (thread == Thread::current()) {1254Deoptimization::deoptimize_frame_internal(thread, id);1255} else {1256VM_DeoptimizeFrame deopt(thread, id);1257VMThread::execute(&deopt);1258}1259}126012611262// JVMTI PopFrame support1263JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))1264{1265thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);1266}1267JRT_END126812691270#if defined(COMPILER2) || defined(SHARK)1271void Deoptimization::load_class_by_index(constantPoolHandle constant_pool, int index, TRAPS) {1272// in case of an unresolved klass entry, load the class.1273if (constant_pool->tag_at(index).is_unresolved_klass()) {1274Klass* tk = constant_pool->klass_at(index, CHECK);1275return;1276}12771278if (!constant_pool->tag_at(index).is_symbol()) return;12791280Handle class_loader (THREAD, constant_pool->pool_holder()->class_loader());1281Symbol* symbol = constant_pool->symbol_at(index);12821283// class name?1284if (symbol->byte_at(0) != '(') {1285Handle protection_domain (THREAD, constant_pool->pool_holder()->protection_domain());1286SystemDictionary::resolve_or_null(symbol, class_loader, protection_domain, CHECK);1287return;1288}12891290// then it must be a signature!1291ResourceMark rm(THREAD);1292for (SignatureStream ss(symbol); !ss.is_done(); ss.next()) {1293if (ss.is_object()) {1294Symbol* class_name = ss.as_symbol(CHECK);1295Handle protection_domain (THREAD, constant_pool->pool_holder()->protection_domain());1296SystemDictionary::resolve_or_null(class_name, class_loader, protection_domain, CHECK);1297}1298}1299}130013011302void Deoptimization::load_class_by_index(constantPoolHandle constant_pool, int index) {1303EXCEPTION_MARK;1304load_class_by_index(constant_pool, index, THREAD);1305if (HAS_PENDING_EXCEPTION) {1306// Exception happened during classloading. We ignore the exception here, since it1307// is going to be rethrown since the current activation is going to be deoptimized and1308// the interpreter will re-execute the bytecode.1309CLEAR_PENDING_EXCEPTION;1310// Class loading called java code which may have caused a stack1311// overflow. If the exception was thrown right before the return1312// to the runtime the stack is no longer guarded. Reguard the1313// stack otherwise if we return to the uncommon trap blob and the1314// stack bang causes a stack overflow we crash.1315assert(THREAD->is_Java_thread(), "only a java thread can be here");1316JavaThread* thread = (JavaThread*)THREAD;1317bool guard_pages_enabled = thread->stack_yellow_zone_enabled();1318if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();1319assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");1320}1321}13221323JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* thread, jint trap_request)) {1324HandleMark hm;13251326// uncommon_trap() is called at the beginning of the uncommon trap1327// handler. Note this fact before we start generating temporary frames1328// that can confuse an asynchronous stack walker. This counter is1329// decremented at the end of unpack_frames().1330thread->inc_in_deopt_handler();13311332// We need to update the map if we have biased locking.1333RegisterMap reg_map(thread, UseBiasedLocking);1334frame stub_frame = thread->last_frame();1335frame fr = stub_frame.sender(®_map);1336// Make sure the calling nmethod is not getting deoptimized and removed1337// before we are done with it.1338nmethodLocker nl(fr.pc());13391340// Log a message1341Events::log(thread, "Uncommon trap: trap_request=" PTR32_FORMAT " fr.pc=" INTPTR_FORMAT,1342trap_request, fr.pc());13431344{1345ResourceMark rm;13461347// Revoke biases of any monitors in the frame to ensure we can migrate them1348revoke_biases_of_monitors(thread, fr, ®_map);13491350DeoptReason reason = trap_request_reason(trap_request);1351DeoptAction action = trap_request_action(trap_request);1352jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -113531354vframe* vf = vframe::new_vframe(&fr, ®_map, thread);1355compiledVFrame* cvf = compiledVFrame::cast(vf);13561357nmethod* nm = cvf->code();13581359ScopeDesc* trap_scope = cvf->scope();1360methodHandle trap_method = trap_scope->method();1361int trap_bci = trap_scope->bci();1362Bytecodes::Code trap_bc = trap_method->java_code_at(trap_bci);13631364// Record this event in the histogram.1365gather_statistics(reason, action, trap_bc);13661367// Ensure that we can record deopt. history:1368// Need MDO to record RTM code generation state.1369bool create_if_missing = ProfileTraps RTM_OPT_ONLY( || UseRTMLocking );13701371MethodData* trap_mdo =1372get_method_data(thread, trap_method, create_if_missing);13731374// Log a message1375Events::log_deopt_message(thread, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d",1376trap_reason_name(reason), trap_action_name(action), fr.pc(),1377trap_method->name_and_sig_as_C_string(), trap_bci);13781379// Print a bunch of diagnostics, if requested.1380if (TraceDeoptimization || LogCompilation) {1381ResourceMark rm;1382ttyLocker ttyl;1383char buf[100];1384if (xtty != NULL) {1385xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT "' %s",1386os::current_thread_id(),1387format_trap_request(buf, sizeof(buf), trap_request));1388nm->log_identity(xtty);1389}1390Symbol* class_name = NULL;1391bool unresolved = false;1392if (unloaded_class_index >= 0) {1393constantPoolHandle constants (THREAD, trap_method->constants());1394if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {1395class_name = constants->klass_name_at(unloaded_class_index);1396unresolved = true;1397if (xtty != NULL)1398xtty->print(" unresolved='1'");1399} else if (constants->tag_at(unloaded_class_index).is_symbol()) {1400class_name = constants->symbol_at(unloaded_class_index);1401}1402if (xtty != NULL)1403xtty->name(class_name);1404}1405if (xtty != NULL && trap_mdo != NULL) {1406// Dump the relevant MDO state.1407// This is the deopt count for the current reason, any previous1408// reasons or recompiles seen at this point.1409int dcnt = trap_mdo->trap_count(reason);1410if (dcnt != 0)1411xtty->print(" count='%d'", dcnt);1412ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);1413int dos = (pdata == NULL)? 0: pdata->trap_state();1414if (dos != 0) {1415xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));1416if (trap_state_is_recompiled(dos)) {1417int recnt2 = trap_mdo->overflow_recompile_count();1418if (recnt2 != 0)1419xtty->print(" recompiles2='%d'", recnt2);1420}1421}1422}1423if (xtty != NULL) {1424xtty->stamp();1425xtty->end_head();1426}1427if (TraceDeoptimization) { // make noise on the tty1428tty->print("Uncommon trap occurred in");1429nm->method()->print_short_name(tty);1430tty->print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d",1431fr.pc(),1432os::current_thread_id(),1433trap_reason_name(reason),1434trap_action_name(action),1435unloaded_class_index);1436if (class_name != NULL) {1437tty->print(unresolved ? " unresolved class: " : " symbol: ");1438class_name->print_symbol_on(tty);1439}1440tty->cr();1441}1442if (xtty != NULL) {1443// Log the precise location of the trap.1444for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {1445xtty->begin_elem("jvms bci='%d'", sd->bci());1446xtty->method(sd->method());1447xtty->end_elem();1448if (sd->is_top()) break;1449}1450xtty->tail("uncommon_trap");1451}1452}1453// (End diagnostic printout.)14541455// Load class if necessary1456if (unloaded_class_index >= 0) {1457constantPoolHandle constants(THREAD, trap_method->constants());1458load_class_by_index(constants, unloaded_class_index);1459}14601461// Flush the nmethod if necessary and desirable.1462//1463// We need to avoid situations where we are re-flushing the nmethod1464// because of a hot deoptimization site. Repeated flushes at the same1465// point need to be detected by the compiler and avoided. If the compiler1466// cannot avoid them (or has a bug and "refuses" to avoid them), this1467// module must take measures to avoid an infinite cycle of recompilation1468// and deoptimization. There are several such measures:1469//1470// 1. If a recompilation is ordered a second time at some site X1471// and for the same reason R, the action is adjusted to 'reinterpret',1472// to give the interpreter time to exercise the method more thoroughly.1473// If this happens, the method's overflow_recompile_count is incremented.1474//1475// 2. If the compiler fails to reduce the deoptimization rate, then1476// the method's overflow_recompile_count will begin to exceed the set1477// limit PerBytecodeRecompilationCutoff. If this happens, the action1478// is adjusted to 'make_not_compilable', and the method is abandoned1479// to the interpreter. This is a performance hit for hot methods,1480// but is better than a disastrous infinite cycle of recompilations.1481// (Actually, only the method containing the site X is abandoned.)1482//1483// 3. In parallel with the previous measures, if the total number of1484// recompilations of a method exceeds the much larger set limit1485// PerMethodRecompilationCutoff, the method is abandoned.1486// This should only happen if the method is very large and has1487// many "lukewarm" deoptimizations. The code which enforces this1488// limit is elsewhere (class nmethod, class Method).1489//1490// Note that the per-BCI 'is_recompiled' bit gives the compiler one chance1491// to recompile at each bytecode independently of the per-BCI cutoff.1492//1493// The decision to update code is up to the compiler, and is encoded1494// in the Action_xxx code. If the compiler requests Action_none1495// no trap state is changed, no compiled code is changed, and the1496// computation suffers along in the interpreter.1497//1498// The other action codes specify various tactics for decompilation1499// and recompilation. Action_maybe_recompile is the loosest, and1500// allows the compiled code to stay around until enough traps are seen,1501// and until the compiler gets around to recompiling the trapping method.1502//1503// The other actions cause immediate removal of the present code.15041505// Traps caused by injected profile shouldn't pollute trap counts.1506bool injected_profile_trap = trap_method->has_injected_profile() &&1507(reason == Reason_intrinsic || reason == Reason_unreached);1508bool update_trap_state = !injected_profile_trap;1509bool make_not_entrant = false;1510bool make_not_compilable = false;1511bool reprofile = false;1512switch (action) {1513case Action_none:1514// Keep the old code.1515update_trap_state = false;1516break;1517case Action_maybe_recompile:1518// Do not need to invalidate the present code, but we can1519// initiate another1520// Start compiler without (necessarily) invalidating the nmethod.1521// The system will tolerate the old code, but new code should be1522// generated when possible.1523break;1524case Action_reinterpret:1525// Go back into the interpreter for a while, and then consider1526// recompiling form scratch.1527make_not_entrant = true;1528// Reset invocation counter for outer most method.1529// This will allow the interpreter to exercise the bytecodes1530// for a while before recompiling.1531// By contrast, Action_make_not_entrant is immediate.1532//1533// Note that the compiler will track null_check, null_assert,1534// range_check, and class_check events and log them as if they1535// had been traps taken from compiled code. This will update1536// the MDO trap history so that the next compilation will1537// properly detect hot trap sites.1538reprofile = true;1539break;1540case Action_make_not_entrant:1541// Request immediate recompilation, and get rid of the old code.1542// Make them not entrant, so next time they are called they get1543// recompiled. Unloaded classes are loaded now so recompile before next1544// time they are called. Same for uninitialized. The interpreter will1545// link the missing class, if any.1546make_not_entrant = true;1547break;1548case Action_make_not_compilable:1549// Give up on compiling this method at all.1550make_not_entrant = true;1551make_not_compilable = true;1552break;1553default:1554ShouldNotReachHere();1555}15561557// Setting +ProfileTraps fixes the following, on all platforms:1558// 4852688: ProfileInterpreter is off by default for ia64. The result is1559// infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the1560// recompile relies on a MethodData* to record heroic opt failures.15611562// Whether the interpreter is producing MDO data or not, we also need1563// to use the MDO to detect hot deoptimization points and control1564// aggressive optimization.1565bool inc_recompile_count = false;1566ProfileData* pdata = NULL;1567if (ProfileTraps && update_trap_state && trap_mdo != NULL) {1568assert(trap_mdo == get_method_data(thread, trap_method, false), "sanity");1569uint this_trap_count = 0;1570bool maybe_prior_trap = false;1571bool maybe_prior_recompile = false;1572pdata = query_update_method_data(trap_mdo, trap_bci, reason,1573nm->method(),1574//outputs:1575this_trap_count,1576maybe_prior_trap,1577maybe_prior_recompile);1578// Because the interpreter also counts null, div0, range, and class1579// checks, these traps from compiled code are double-counted.1580// This is harmless; it just means that the PerXTrapLimit values1581// are in effect a little smaller than they look.15821583DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);1584if (per_bc_reason != Reason_none) {1585// Now take action based on the partially known per-BCI history.1586if (maybe_prior_trap1587&& this_trap_count >= (uint)PerBytecodeTrapLimit) {1588// If there are too many traps at this BCI, force a recompile.1589// This will allow the compiler to see the limit overflow, and1590// take corrective action, if possible. The compiler generally1591// does not use the exact PerBytecodeTrapLimit value, but instead1592// changes its tactics if it sees any traps at all. This provides1593// a little hysteresis, delaying a recompile until a trap happens1594// several times.1595//1596// Actually, since there is only one bit of counter per BCI,1597// the possible per-BCI counts are {0,1,(per-method count)}.1598// This produces accurate results if in fact there is only1599// one hot trap site, but begins to get fuzzy if there are1600// many sites. For example, if there are ten sites each1601// trapping two or more times, they each get the blame for1602// all of their traps.1603make_not_entrant = true;1604}16051606// Detect repeated recompilation at the same BCI, and enforce a limit.1607if (make_not_entrant && maybe_prior_recompile) {1608// More than one recompile at this point.1609inc_recompile_count = maybe_prior_trap;1610}1611} else {1612// For reasons which are not recorded per-bytecode, we simply1613// force recompiles unconditionally.1614// (Note that PerMethodRecompilationCutoff is enforced elsewhere.)1615make_not_entrant = true;1616}16171618// Go back to the compiler if there are too many traps in this method.1619if (this_trap_count >= per_method_trap_limit(reason)) {1620// If there are too many traps in this method, force a recompile.1621// This will allow the compiler to see the limit overflow, and1622// take corrective action, if possible.1623// (This condition is an unlikely backstop only, because the1624// PerBytecodeTrapLimit is more likely to take effect first,1625// if it is applicable.)1626make_not_entrant = true;1627}16281629// Here's more hysteresis: If there has been a recompile at1630// this trap point already, run the method in the interpreter1631// for a while to exercise it more thoroughly.1632if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {1633reprofile = true;1634}16351636}16371638// Take requested actions on the method:16391640// Recompile1641if (make_not_entrant) {1642if (!nm->make_not_entrant()) {1643return; // the call did not change nmethod's state1644}16451646if (pdata != NULL) {1647// Record the recompilation event, if any.1648int tstate0 = pdata->trap_state();1649int tstate1 = trap_state_set_recompiled(tstate0, true);1650if (tstate1 != tstate0)1651pdata->set_trap_state(tstate1);1652}16531654#if INCLUDE_RTM_OPT1655// Restart collecting RTM locking abort statistic if the method1656// is recompiled for a reason other than RTM state change.1657// Assume that in new recompiled code the statistic could be different,1658// for example, due to different inlining.1659if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) &&1660UseRTMDeopt && (nm->rtm_state() != ProfileRTM)) {1661trap_mdo->atomic_set_rtm_state(ProfileRTM);1662}1663#endif1664}16651666if (inc_recompile_count) {1667trap_mdo->inc_overflow_recompile_count();1668if ((uint)trap_mdo->overflow_recompile_count() >1669(uint)PerBytecodeRecompilationCutoff) {1670// Give up on the method containing the bad BCI.1671if (trap_method() == nm->method()) {1672make_not_compilable = true;1673} else {1674trap_method->set_not_compilable(CompLevel_full_optimization, true, "overflow_recompile_count > PerBytecodeRecompilationCutoff");1675// But give grace to the enclosing nm->method().1676}1677}1678}16791680// Reprofile1681if (reprofile) {1682CompilationPolicy::policy()->reprofile(trap_scope, nm->is_osr_method());1683}16841685// Give up compiling1686if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {1687assert(make_not_entrant, "consistent");1688nm->method()->set_not_compilable(CompLevel_full_optimization);1689}16901691} // Free marked resources16921693}1694JRT_END16951696MethodData*1697Deoptimization::get_method_data(JavaThread* thread, methodHandle m,1698bool create_if_missing) {1699Thread* THREAD = thread;1700MethodData* mdo = m()->method_data();1701if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) {1702// Build an MDO. Ignore errors like OutOfMemory;1703// that simply means we won't have an MDO to update.1704Method::build_interpreter_method_data(m, THREAD);1705if (HAS_PENDING_EXCEPTION) {1706assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");1707CLEAR_PENDING_EXCEPTION;1708}1709mdo = m()->method_data();1710}1711return mdo;1712}17131714ProfileData*1715Deoptimization::query_update_method_data(MethodData* trap_mdo,1716int trap_bci,1717Deoptimization::DeoptReason reason,1718Method* compiled_method,1719//outputs:1720uint& ret_this_trap_count,1721bool& ret_maybe_prior_trap,1722bool& ret_maybe_prior_recompile) {1723uint prior_trap_count = trap_mdo->trap_count(reason);1724uint this_trap_count = trap_mdo->inc_trap_count(reason);17251726// If the runtime cannot find a place to store trap history,1727// it is estimated based on the general condition of the method.1728// If the method has ever been recompiled, or has ever incurred1729// a trap with the present reason , then this BCI is assumed1730// (pessimistically) to be the culprit.1731bool maybe_prior_trap = (prior_trap_count != 0);1732bool maybe_prior_recompile = (trap_mdo->decompile_count() != 0);1733ProfileData* pdata = NULL;173417351736// For reasons which are recorded per bytecode, we check per-BCI data.1737DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);1738if (per_bc_reason != Reason_none) {1739// Find the profile data for this BCI. If there isn't one,1740// try to allocate one from the MDO's set of spares.1741// This will let us detect a repeated trap at this point.1742pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL);17431744if (pdata != NULL) {1745if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {1746if (LogCompilation && xtty != NULL) {1747ttyLocker ttyl;1748// no more room for speculative traps in this MDO1749xtty->elem("speculative_traps_oom");1750}1751}1752// Query the trap state of this profile datum.1753int tstate0 = pdata->trap_state();1754if (!trap_state_has_reason(tstate0, per_bc_reason))1755maybe_prior_trap = false;1756if (!trap_state_is_recompiled(tstate0))1757maybe_prior_recompile = false;17581759// Update the trap state of this profile datum.1760int tstate1 = tstate0;1761// Record the reason.1762tstate1 = trap_state_add_reason(tstate1, per_bc_reason);1763// Store the updated state on the MDO, for next time.1764if (tstate1 != tstate0)1765pdata->set_trap_state(tstate1);1766} else {1767if (LogCompilation && xtty != NULL) {1768ttyLocker ttyl;1769// Missing MDP? Leave a small complaint in the log.1770xtty->elem("missing_mdp bci='%d'", trap_bci);1771}1772}1773}17741775// Return results:1776ret_this_trap_count = this_trap_count;1777ret_maybe_prior_trap = maybe_prior_trap;1778ret_maybe_prior_recompile = maybe_prior_recompile;1779return pdata;1780}17811782void1783Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {1784ResourceMark rm;1785// Ignored outputs:1786uint ignore_this_trap_count;1787bool ignore_maybe_prior_trap;1788bool ignore_maybe_prior_recompile;1789assert(!reason_is_speculate(reason), "reason speculate only used by compiler");1790query_update_method_data(trap_mdo, trap_bci,1791(DeoptReason)reason,1792NULL,1793ignore_this_trap_count,1794ignore_maybe_prior_trap,1795ignore_maybe_prior_recompile);1796}17971798Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* thread, jint trap_request) {17991800// Still in Java no safepoints1801{1802// This enters VM and may safepoint1803uncommon_trap_inner(thread, trap_request);1804}1805return fetch_unroll_info_helper(thread);1806}18071808// Local derived constants.1809// Further breakdown of DataLayout::trap_state, as promised by DataLayout.1810const int DS_REASON_MASK = DataLayout::trap_mask >> 1;1811const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;18121813//---------------------------trap_state_reason---------------------------------1814Deoptimization::DeoptReason1815Deoptimization::trap_state_reason(int trap_state) {1816// This assert provides the link between the width of DataLayout::trap_bits1817// and the encoding of "recorded" reasons. It ensures there are enough1818// bits to store all needed reasons in the per-BCI MDO profile.1819assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");1820int recompile_bit = (trap_state & DS_RECOMPILE_BIT);1821trap_state -= recompile_bit;1822if (trap_state == DS_REASON_MASK) {1823return Reason_many;1824} else {1825assert((int)Reason_none == 0, "state=0 => Reason_none");1826return (DeoptReason)trap_state;1827}1828}1829//-------------------------trap_state_has_reason-------------------------------1830int Deoptimization::trap_state_has_reason(int trap_state, int reason) {1831assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");1832assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");1833int recompile_bit = (trap_state & DS_RECOMPILE_BIT);1834trap_state -= recompile_bit;1835if (trap_state == DS_REASON_MASK) {1836return -1; // true, unspecifically (bottom of state lattice)1837} else if (trap_state == reason) {1838return 1; // true, definitely1839} else if (trap_state == 0) {1840return 0; // false, definitely (top of state lattice)1841} else {1842return 0; // false, definitely1843}1844}1845//-------------------------trap_state_add_reason-------------------------------1846int Deoptimization::trap_state_add_reason(int trap_state, int reason) {1847assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");1848int recompile_bit = (trap_state & DS_RECOMPILE_BIT);1849trap_state -= recompile_bit;1850if (trap_state == DS_REASON_MASK) {1851return trap_state + recompile_bit; // already at state lattice bottom1852} else if (trap_state == reason) {1853return trap_state + recompile_bit; // the condition is already true1854} else if (trap_state == 0) {1855return reason + recompile_bit; // no condition has yet been true1856} else {1857return DS_REASON_MASK + recompile_bit; // fall to state lattice bottom1858}1859}1860//-----------------------trap_state_is_recompiled------------------------------1861bool Deoptimization::trap_state_is_recompiled(int trap_state) {1862return (trap_state & DS_RECOMPILE_BIT) != 0;1863}1864//-----------------------trap_state_set_recompiled-----------------------------1865int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {1866if (z) return trap_state | DS_RECOMPILE_BIT;1867else return trap_state & ~DS_RECOMPILE_BIT;1868}1869//---------------------------format_trap_state---------------------------------1870// This is used for debugging and diagnostics, including LogFile output.1871const char* Deoptimization::format_trap_state(char* buf, size_t buflen,1872int trap_state) {1873DeoptReason reason = trap_state_reason(trap_state);1874bool recomp_flag = trap_state_is_recompiled(trap_state);1875// Re-encode the state from its decoded components.1876int decoded_state = 0;1877if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)1878decoded_state = trap_state_add_reason(decoded_state, reason);1879if (recomp_flag)1880decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);1881// If the state re-encodes properly, format it symbolically.1882// Because this routine is used for debugging and diagnostics,1883// be robust even if the state is a strange value.1884size_t len;1885if (decoded_state != trap_state) {1886// Random buggy state that doesn't decode??1887len = jio_snprintf(buf, buflen, "#%d", trap_state);1888} else {1889len = jio_snprintf(buf, buflen, "%s%s",1890trap_reason_name(reason),1891recomp_flag ? " recompiled" : "");1892}1893return buf;1894}189518961897//--------------------------------statics--------------------------------------1898Deoptimization::DeoptAction Deoptimization::_unloaded_action1899= Deoptimization::Action_reinterpret;1900const char* Deoptimization::_trap_reason_name[Reason_LIMIT] = {1901// Note: Keep this in sync. with enum DeoptReason.1902"none",1903"null_check",1904"null_assert",1905"range_check",1906"class_check",1907"array_check",1908"intrinsic",1909"bimorphic",1910"unloaded",1911"uninitialized",1912"unreached",1913"unhandled",1914"constraint",1915"div0_check",1916"age",1917"predicate",1918"loop_limit_check",1919"speculate_class_check",1920"rtm_state_change",1921"unstable_if"1922};1923const char* Deoptimization::_trap_action_name[Action_LIMIT] = {1924// Note: Keep this in sync. with enum DeoptAction.1925"none",1926"maybe_recompile",1927"reinterpret",1928"make_not_entrant",1929"make_not_compilable"1930};19311932const char* Deoptimization::trap_reason_name(int reason) {1933if (reason == Reason_many) return "many";1934if ((uint)reason < Reason_LIMIT)1935return _trap_reason_name[reason];1936static char buf[20];1937sprintf(buf, "reason%d", reason);1938return buf;1939}1940const char* Deoptimization::trap_action_name(int action) {1941if ((uint)action < Action_LIMIT)1942return _trap_action_name[action];1943static char buf[20];1944sprintf(buf, "action%d", action);1945return buf;1946}19471948// This is used for debugging and diagnostics, including LogFile output.1949const char* Deoptimization::format_trap_request(char* buf, size_t buflen,1950int trap_request) {1951jint unloaded_class_index = trap_request_index(trap_request);1952const char* reason = trap_reason_name(trap_request_reason(trap_request));1953const char* action = trap_action_name(trap_request_action(trap_request));1954size_t len;1955if (unloaded_class_index < 0) {1956len = jio_snprintf(buf, buflen, "reason='%s' action='%s'",1957reason, action);1958} else {1959len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'",1960reason, action, unloaded_class_index);1961}1962return buf;1963}19641965juint Deoptimization::_deoptimization_hist1966[Deoptimization::Reason_LIMIT]1967[1 + Deoptimization::Action_LIMIT]1968[Deoptimization::BC_CASE_LIMIT]1969= {0};19701971enum {1972LSB_BITS = 8,1973LSB_MASK = right_n_bits(LSB_BITS)1974};19751976void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,1977Bytecodes::Code bc) {1978assert(reason >= 0 && reason < Reason_LIMIT, "oob");1979assert(action >= 0 && action < Action_LIMIT, "oob");1980_deoptimization_hist[Reason_none][0][0] += 1; // total1981_deoptimization_hist[reason][0][0] += 1; // per-reason total1982juint* cases = _deoptimization_hist[reason][1+action];1983juint* bc_counter_addr = NULL;1984juint bc_counter = 0;1985// Look for an unused counter, or an exact match to this BC.1986if (bc != Bytecodes::_illegal) {1987for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {1988juint* counter_addr = &cases[bc_case];1989juint counter = *counter_addr;1990if ((counter == 0 && bc_counter_addr == NULL)1991|| (Bytecodes::Code)(counter & LSB_MASK) == bc) {1992// this counter is either free or is already devoted to this BC1993bc_counter_addr = counter_addr;1994bc_counter = counter | bc;1995}1996}1997}1998if (bc_counter_addr == NULL) {1999// Overflow, or no given bytecode.2000bc_counter_addr = &cases[BC_CASE_LIMIT-1];2001bc_counter = (*bc_counter_addr & ~LSB_MASK); // clear LSB2002}2003*bc_counter_addr = bc_counter + (1 << LSB_BITS);2004}20052006jint Deoptimization::total_deoptimization_count() {2007return _deoptimization_hist[Reason_none][0][0];2008}20092010jint Deoptimization::deoptimization_count(DeoptReason reason) {2011assert(reason >= 0 && reason < Reason_LIMIT, "oob");2012return _deoptimization_hist[reason][0][0];2013}20142015void Deoptimization::print_statistics() {2016juint total = total_deoptimization_count();2017juint account = total;2018if (total != 0) {2019ttyLocker ttyl;2020if (xtty != NULL) xtty->head("statistics type='deoptimization'");2021tty->print_cr("Deoptimization traps recorded:");2022#define PRINT_STAT_LINE(name, r) \2023tty->print_cr(" %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);2024PRINT_STAT_LINE("total", total);2025// For each non-zero entry in the histogram, print the reason,2026// the action, and (if specifically known) the type of bytecode.2027for (int reason = 0; reason < Reason_LIMIT; reason++) {2028for (int action = 0; action < Action_LIMIT; action++) {2029juint* cases = _deoptimization_hist[reason][1+action];2030for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {2031juint counter = cases[bc_case];2032if (counter != 0) {2033char name[1*K];2034Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);2035if (bc_case == BC_CASE_LIMIT && (int)bc == 0)2036bc = Bytecodes::_illegal;2037sprintf(name, "%s/%s/%s",2038trap_reason_name(reason),2039trap_action_name(action),2040Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");2041juint r = counter >> LSB_BITS;2042tty->print_cr(" %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);2043account -= r;2044}2045}2046}2047}2048if (account != 0) {2049PRINT_STAT_LINE("unaccounted", account);2050}2051#undef PRINT_STAT_LINE2052if (xtty != NULL) xtty->tail("statistics");2053}2054}2055#else // COMPILER2 || SHARK205620572058// Stubs for C1 only system.2059bool Deoptimization::trap_state_is_recompiled(int trap_state) {2060return false;2061}20622063const char* Deoptimization::trap_reason_name(int reason) {2064return "unknown";2065}20662067void Deoptimization::print_statistics() {2068// no output2069}20702071void2072Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {2073// no udpate2074}20752076int Deoptimization::trap_state_has_reason(int trap_state, int reason) {2077return 0;2078}20792080void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,2081Bytecodes::Code bc) {2082// no update2083}20842085const char* Deoptimization::format_trap_state(char* buf, size_t buflen,2086int trap_state) {2087jio_snprintf(buf, buflen, "#%d", trap_state);2088return buf;2089}20902091#endif // COMPILER2 || SHARK209220932094