1 /* 2 * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 #include "jvm.h" 27 #include "classfile/javaClasses.inline.hpp" 28 #include "classfile/symbolTable.hpp" 29 #include "classfile/systemDictionary.hpp" 30 #include "classfile/vmClasses.hpp" 31 #include "code/codeCache.hpp" 32 #include "code/debugInfoRec.hpp" 33 #include "code/nmethod.hpp" 34 #include "code/pcDesc.hpp" 35 #include "code/scopeDesc.hpp" 36 #include "compiler/compilationPolicy.hpp" 37 #include "gc/shared/collectedHeap.hpp" 38 #include "interpreter/bytecode.hpp" 39 #include "interpreter/interpreter.hpp" 40 #include "interpreter/oopMapCache.hpp" 41 #include "memory/allocation.inline.hpp" 42 #include "memory/oopFactory.hpp" 43 #include "memory/resourceArea.hpp" 44 #include "memory/universe.hpp" 45 #include "oops/constantPool.hpp" 46 #include "oops/method.hpp" 47 #include "oops/objArrayKlass.hpp" 48 #include "oops/objArrayOop.inline.hpp" 49 #include "oops/oop.inline.hpp" 50 #include "oops/fieldStreams.inline.hpp" 51 #include "oops/typeArrayOop.inline.hpp" 52 #include "oops/verifyOopClosure.hpp" 53 #include "prims/jvmtiDeferredUpdates.hpp" 54 #include "prims/jvmtiExport.hpp" 55 #include "prims/jvmtiThreadState.hpp" 56 #include "prims/vectorSupport.hpp" 57 #include "prims/methodHandles.hpp" 58 #include "runtime/atomic.hpp" 59 #include "runtime/biasedLocking.hpp" 60 #include "runtime/deoptimization.hpp" 61 #include "runtime/escapeBarrier.hpp" 62 #include "runtime/fieldDescriptor.hpp" 63 #include "runtime/fieldDescriptor.inline.hpp" 64 #include "runtime/frame.inline.hpp" 65 #include "runtime/handles.inline.hpp" 66 #include "runtime/interfaceSupport.inline.hpp" 67 #include "runtime/jniHandles.inline.hpp" 68 #include "runtime/keepStackGCProcessed.hpp" 69 #include "runtime/objectMonitor.inline.hpp" 70 #include "runtime/osThread.hpp" 71 #include "runtime/safepointVerifiers.hpp" 72 #include "runtime/sharedRuntime.hpp" 73 #include "runtime/signature.hpp" 74 #include "runtime/stackFrameStream.inline.hpp" 75 #include "runtime/stackWatermarkSet.hpp" 76 #include "runtime/stubRoutines.hpp" 77 #include "runtime/thread.hpp" 78 #include "runtime/threadSMR.hpp" 79 #include "runtime/threadWXSetters.inline.hpp" 80 #include "runtime/vframe.hpp" 81 #include "runtime/vframeArray.hpp" 82 #include "runtime/vframe_hp.hpp" 83 #include "runtime/vmOperations.hpp" 84 #include "utilities/events.hpp" 85 #include "utilities/macros.hpp" 86 #include "utilities/preserveException.hpp" 87 #include "utilities/xmlstream.hpp" 88 #if INCLUDE_JFR 89 #include "jfr/jfrEvents.hpp" 90 #include "jfr/metadata/jfrSerializer.hpp" 91 #endif 92 93 bool DeoptimizationMarker::_is_active = false; 94 95 Deoptimization::UnrollBlock::UnrollBlock(int size_of_deoptimized_frame, 96 int caller_adjustment, 97 int caller_actual_parameters, 98 int number_of_frames, 99 intptr_t* frame_sizes, 100 address* frame_pcs, 101 BasicType return_type, 102 int exec_mode) { 103 _size_of_deoptimized_frame = size_of_deoptimized_frame; 104 _caller_adjustment = caller_adjustment; 105 _caller_actual_parameters = caller_actual_parameters; 106 _number_of_frames = number_of_frames; 107 _frame_sizes = frame_sizes; 108 _frame_pcs = frame_pcs; 109 _register_block = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler); 110 _return_type = return_type; 111 _initial_info = 0; 112 // PD (x86 only) 113 _counter_temp = 0; 114 _unpack_kind = exec_mode; 115 _sender_sp_temp = 0; 116 117 _total_frame_sizes = size_of_frames(); 118 assert(exec_mode >= 0 && exec_mode < Unpack_LIMIT, "Unexpected exec_mode"); 119 } 120 121 122 Deoptimization::UnrollBlock::~UnrollBlock() { 123 FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes); 124 FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs); 125 FREE_C_HEAP_ARRAY(intptr_t, _register_block); 126 } 127 128 129 intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const { 130 assert(register_number < RegisterMap::reg_count, "checking register number"); 131 return &_register_block[register_number * 2]; 132 } 133 134 135 136 int Deoptimization::UnrollBlock::size_of_frames() const { 137 // Acount first for the adjustment of the initial frame 138 int result = _caller_adjustment; 139 for (int index = 0; index < number_of_frames(); index++) { 140 result += frame_sizes()[index]; 141 } 142 return result; 143 } 144 145 146 void Deoptimization::UnrollBlock::print() { 147 ttyLocker ttyl; 148 tty->print_cr("UnrollBlock"); 149 tty->print_cr(" size_of_deoptimized_frame = %d", _size_of_deoptimized_frame); 150 tty->print( " frame_sizes: "); 151 for (int index = 0; index < number_of_frames(); index++) { 152 tty->print(INTX_FORMAT " ", frame_sizes()[index]); 153 } 154 tty->cr(); 155 } 156 157 158 // In order to make fetch_unroll_info work properly with escape 159 // analysis, the method was changed from JRT_LEAF to JRT_BLOCK_ENTRY. 160 // The actual reallocation of previously eliminated objects occurs in realloc_objects, 161 // which is called from the method fetch_unroll_info_helper below. 162 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* current, int exec_mode)) 163 // fetch_unroll_info() is called at the beginning of the deoptimization 164 // handler. Note this fact before we start generating temporary frames 165 // that can confuse an asynchronous stack walker. This counter is 166 // decremented at the end of unpack_frames(). 167 if (TraceDeoptimization) { 168 tty->print_cr("Deoptimizing thread " INTPTR_FORMAT, p2i(current)); 169 } 170 current->inc_in_deopt_handler(); 171 172 if (exec_mode == Unpack_exception) { 173 // When we get here, a callee has thrown an exception into a deoptimized 174 // frame. That throw might have deferred stack watermark checking until 175 // after unwinding. So we deal with such deferred requests here. 176 StackWatermarkSet::after_unwind(current); 177 } 178 179 return fetch_unroll_info_helper(current, exec_mode); 180 JRT_END 181 182 #if COMPILER2_OR_JVMCI 183 static bool rematerialize_objects(JavaThread* thread, int exec_mode, CompiledMethod* compiled_method, 184 frame& deoptee, RegisterMap& map, GrowableArray<compiledVFrame*>* chunk, 185 bool& deoptimized_objects) { 186 bool realloc_failures = false; 187 assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames"); 188 189 JavaThread* deoptee_thread = chunk->at(0)->thread(); 190 assert(exec_mode == Deoptimization::Unpack_none || (deoptee_thread == thread), 191 "a frame can only be deoptimized by the owner thread"); 192 193 GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects(); 194 195 // The flag return_oop() indicates call sites which return oop 196 // in compiled code. Such sites include java method calls, 197 // runtime calls (for example, used to allocate new objects/arrays 198 // on slow code path) and any other calls generated in compiled code. 199 // It is not guaranteed that we can get such information here only 200 // by analyzing bytecode in deoptimized frames. This is why this flag 201 // is set during method compilation (see Compile::Process_OopMap_Node()). 202 // If the previous frame was popped or if we are dispatching an exception, 203 // we don't have an oop result. 204 bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Deoptimization::Unpack_deopt); 205 Handle return_value; 206 if (save_oop_result) { 207 // Reallocation may trigger GC. If deoptimization happened on return from 208 // call which returns oop we need to save it since it is not in oopmap. 209 oop result = deoptee.saved_oop_result(&map); 210 assert(oopDesc::is_oop_or_null(result), "must be oop"); 211 return_value = Handle(thread, result); 212 assert(Universe::heap()->is_in_or_null(result), "must be heap pointer"); 213 if (TraceDeoptimization) { 214 ttyLocker ttyl; 215 tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread)); 216 } 217 } 218 if (objects != NULL) { 219 if (exec_mode == Deoptimization::Unpack_none) { 220 assert(thread->thread_state() == _thread_in_vm, "assumption"); 221 JavaThread* THREAD = thread; // For exception macros. 222 // Clear pending OOM if reallocation fails and return true indicating allocation failure 223 realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, CHECK_AND_CLEAR_(true)); 224 deoptimized_objects = true; 225 } else { 226 JavaThread* current = thread; // For JRT_BLOCK 227 JRT_BLOCK 228 realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, THREAD); 229 JRT_END 230 } 231 bool skip_internal = (compiled_method != NULL) && !compiled_method->is_compiled_by_jvmci(); 232 Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, skip_internal); 233 #ifndef PRODUCT 234 if (TraceDeoptimization) { 235 ttyLocker ttyl; 236 tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(deoptee_thread)); 237 Deoptimization::print_objects(objects, realloc_failures); 238 } 239 #endif 240 } 241 if (save_oop_result) { 242 // Restore result. 243 deoptee.set_saved_oop_result(&map, return_value()); 244 } 245 return realloc_failures; 246 } 247 248 static void restore_eliminated_locks(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures, 249 frame& deoptee, int exec_mode, bool& deoptimized_objects) { 250 JavaThread* deoptee_thread = chunk->at(0)->thread(); 251 assert(!EscapeBarrier::objs_are_deoptimized(deoptee_thread, deoptee.id()), "must relock just once"); 252 assert(thread == Thread::current(), "should be"); 253 HandleMark hm(thread); 254 #ifndef PRODUCT 255 bool first = true; 256 #endif 257 for (int i = 0; i < chunk->length(); i++) { 258 compiledVFrame* cvf = chunk->at(i); 259 assert (cvf->scope() != NULL,"expect only compiled java frames"); 260 GrowableArray<MonitorInfo*>* monitors = cvf->monitors(); 261 if (monitors->is_nonempty()) { 262 bool relocked = Deoptimization::relock_objects(thread, monitors, deoptee_thread, deoptee, 263 exec_mode, realloc_failures); 264 deoptimized_objects = deoptimized_objects || relocked; 265 #ifndef PRODUCT 266 if (PrintDeoptimizationDetails) { 267 ttyLocker ttyl; 268 for (int j = 0; j < monitors->length(); j++) { 269 MonitorInfo* mi = monitors->at(j); 270 if (mi->eliminated()) { 271 if (first) { 272 first = false; 273 tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, p2i(thread)); 274 } 275 if (exec_mode == Deoptimization::Unpack_none) { 276 ObjectMonitor* monitor = deoptee_thread->current_waiting_monitor(); 277 if (monitor != NULL && monitor->object() == mi->owner()) { 278 tty->print_cr(" object <" INTPTR_FORMAT "> DEFERRED relocking after wait", p2i(mi->owner())); 279 continue; 280 } 281 } 282 if (mi->owner_is_scalar_replaced()) { 283 Klass* k = java_lang_Class::as_Klass(mi->owner_klass()); 284 tty->print_cr(" failed reallocation for klass %s", k->external_name()); 285 } else { 286 tty->print_cr(" object <" INTPTR_FORMAT "> locked", p2i(mi->owner())); 287 } 288 } 289 } 290 } 291 #endif // !PRODUCT 292 } 293 } 294 } 295 296 // Deoptimize objects, that is reallocate and relock them, just before they escape through JVMTI. 297 // The given vframes cover one physical frame. 298 bool Deoptimization::deoptimize_objects_internal(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, 299 bool& realloc_failures) { 300 frame deoptee = chunk->at(0)->fr(); 301 JavaThread* deoptee_thread = chunk->at(0)->thread(); 302 CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null(); 303 RegisterMap map(chunk->at(0)->register_map()); 304 bool deoptimized_objects = false; 305 306 bool const jvmci_enabled = JVMCI_ONLY(UseJVMCICompiler) NOT_JVMCI(false); 307 308 // Reallocate the non-escaping objects and restore their fields. 309 if (jvmci_enabled COMPILER2_PRESENT(|| (DoEscapeAnalysis && EliminateAllocations) 310 || EliminateAutoBox || EnableVectorAggressiveReboxing)) { 311 realloc_failures = rematerialize_objects(thread, Unpack_none, cm, deoptee, map, chunk, deoptimized_objects); 312 } 313 314 // Revoke biases of objects with eliminated locks in the given frame. 315 Deoptimization::revoke_for_object_deoptimization(deoptee_thread, deoptee, &map, thread); 316 317 // MonitorInfo structures used in eliminate_locks are not GC safe. 318 NoSafepointVerifier no_safepoint; 319 320 // Now relock objects if synchronization on them was eliminated. 321 if (jvmci_enabled COMPILER2_PRESENT(|| ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks))) { 322 restore_eliminated_locks(thread, chunk, realloc_failures, deoptee, Unpack_none, deoptimized_objects); 323 } 324 return deoptimized_objects; 325 } 326 #endif // COMPILER2_OR_JVMCI 327 328 // This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap) 329 Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* current, int exec_mode) { 330 // When we get here we are about to unwind the deoptee frame. In order to 331 // catch not yet safe to use frames, the following stack watermark barrier 332 // poll will make such frames safe to use. 333 StackWatermarkSet::before_unwind(current); 334 335 // Note: there is a safepoint safety issue here. No matter whether we enter 336 // via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once 337 // the vframeArray is created. 338 // 339 340 // Allocate our special deoptimization ResourceMark 341 DeoptResourceMark* dmark = new DeoptResourceMark(current); 342 assert(current->deopt_mark() == NULL, "Pending deopt!"); 343 current->set_deopt_mark(dmark); 344 345 frame stub_frame = current->last_frame(); // Makes stack walkable as side effect 346 RegisterMap map(current, true); 347 RegisterMap dummy_map(current, false); 348 // Now get the deoptee with a valid map 349 frame deoptee = stub_frame.sender(&map); 350 // Set the deoptee nmethod 351 assert(current->deopt_compiled_method() == NULL, "Pending deopt!"); 352 CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null(); 353 current->set_deopt_compiled_method(cm); 354 355 if (VerifyStack) { 356 current->validate_frame_layout(); 357 } 358 359 // Create a growable array of VFrames where each VFrame represents an inlined 360 // Java frame. This storage is allocated with the usual system arena. 361 assert(deoptee.is_compiled_frame(), "Wrong frame type"); 362 GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10); 363 vframe* vf = vframe::new_vframe(&deoptee, &map, current); 364 while (!vf->is_top()) { 365 assert(vf->is_compiled_frame(), "Wrong frame type"); 366 chunk->push(compiledVFrame::cast(vf)); 367 vf = vf->sender(); 368 } 369 assert(vf->is_compiled_frame(), "Wrong frame type"); 370 chunk->push(compiledVFrame::cast(vf)); 371 372 bool realloc_failures = false; 373 374 #if COMPILER2_OR_JVMCI 375 bool const jvmci_enabled = JVMCI_ONLY(EnableJVMCI) NOT_JVMCI(false); 376 377 // Reallocate the non-escaping objects and restore their fields. Then 378 // relock objects if synchronization on them was eliminated. 379 if (jvmci_enabled COMPILER2_PRESENT( || (DoEscapeAnalysis && EliminateAllocations) 380 || EliminateAutoBox || EnableVectorAggressiveReboxing )) { 381 bool unused; 382 realloc_failures = rematerialize_objects(current, exec_mode, cm, deoptee, map, chunk, unused); 383 } 384 #endif // COMPILER2_OR_JVMCI 385 386 // Revoke biases, done with in java state. 387 // No safepoints allowed after this 388 revoke_from_deopt_handler(current, deoptee, &map); 389 390 // Ensure that no safepoint is taken after pointers have been stored 391 // in fields of rematerialized objects. If a safepoint occurs from here on 392 // out the java state residing in the vframeArray will be missed. 393 // Locks may be rebaised in a safepoint. 394 NoSafepointVerifier no_safepoint; 395 396 #if COMPILER2_OR_JVMCI 397 if ((jvmci_enabled COMPILER2_PRESENT( || ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks) )) 398 && !EscapeBarrier::objs_are_deoptimized(current, deoptee.id())) { 399 bool unused; 400 restore_eliminated_locks(current, chunk, realloc_failures, deoptee, exec_mode, unused); 401 } 402 #endif // COMPILER2_OR_JVMCI 403 404 ScopeDesc* trap_scope = chunk->at(0)->scope(); 405 Handle exceptionObject; 406 if (trap_scope->rethrow_exception()) { 407 if (PrintDeoptimizationDetails) { 408 tty->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()); 409 } 410 GrowableArray<ScopeValue*>* expressions = trap_scope->expressions(); 411 guarantee(expressions != NULL && expressions->length() > 0, "must have exception to throw"); 412 ScopeValue* topOfStack = expressions->top(); 413 exceptionObject = StackValue::create_stack_value(&deoptee, &map, topOfStack)->get_obj(); 414 guarantee(exceptionObject() != NULL, "exception oop can not be null"); 415 } 416 417 vframeArray* array = create_vframeArray(current, deoptee, &map, chunk, realloc_failures); 418 #if COMPILER2_OR_JVMCI 419 if (realloc_failures) { 420 pop_frames_failed_reallocs(current, array); 421 } 422 #endif 423 424 assert(current->vframe_array_head() == NULL, "Pending deopt!"); 425 current->set_vframe_array_head(array); 426 427 // Now that the vframeArray has been created if we have any deferred local writes 428 // added by jvmti then we can free up that structure as the data is now in the 429 // vframeArray 430 431 JvmtiDeferredUpdates::delete_updates_for_frame(current, array->original().id()); 432 433 // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info. 434 CodeBlob* cb = stub_frame.cb(); 435 // Verify we have the right vframeArray 436 assert(cb->frame_size() >= 0, "Unexpected frame size"); 437 intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size(); 438 439 // If the deopt call site is a MethodHandle invoke call site we have 440 // to adjust the unpack_sp. 441 nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null(); 442 if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc())) 443 unpack_sp = deoptee.unextended_sp(); 444 445 #ifdef ASSERT 446 assert(cb->is_deoptimization_stub() || 447 cb->is_uncommon_trap_stub() || 448 strcmp("Stub<DeoptimizationStub.deoptimizationHandler>", cb->name()) == 0 || 449 strcmp("Stub<UncommonTrapStub.uncommonTrapHandler>", cb->name()) == 0, 450 "unexpected code blob: %s", cb->name()); 451 #endif 452 453 // This is a guarantee instead of an assert because if vframe doesn't match 454 // we will unpack the wrong deoptimized frame and wind up in strange places 455 // where it will be very difficult to figure out what went wrong. Better 456 // to die an early death here than some very obscure death later when the 457 // trail is cold. 458 // Note: on ia64 this guarantee can be fooled by frames with no memory stack 459 // in that it will fail to detect a problem when there is one. This needs 460 // more work in tiger timeframe. 461 guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack"); 462 463 int number_of_frames = array->frames(); 464 465 // Compute the vframes' sizes. Note that frame_sizes[] entries are ordered from outermost to innermost 466 // virtual activation, which is the reverse of the elements in the vframes array. 467 intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler); 468 // +1 because we always have an interpreter return address for the final slot. 469 address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler); 470 int popframe_extra_args = 0; 471 // Create an interpreter return address for the stub to use as its return 472 // address so the skeletal frames are perfectly walkable 473 frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0); 474 475 // PopFrame requires that the preserved incoming arguments from the recently-popped topmost 476 // activation be put back on the expression stack of the caller for reexecution 477 if (JvmtiExport::can_pop_frame() && current->popframe_forcing_deopt_reexecution()) { 478 popframe_extra_args = in_words(current->popframe_preserved_args_size_in_words()); 479 } 480 481 // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized 482 // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather 483 // than simply use array->sender.pc(). This requires us to walk the current set of frames 484 // 485 frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame 486 deopt_sender = deopt_sender.sender(&dummy_map); // Now deoptee caller 487 488 // It's possible that the number of parameters at the call site is 489 // different than number of arguments in the callee when method 490 // handles are used. If the caller is interpreted get the real 491 // value so that the proper amount of space can be added to it's 492 // frame. 493 bool caller_was_method_handle = false; 494 if (deopt_sender.is_interpreted_frame()) { 495 methodHandle method(current, deopt_sender.interpreter_frame_method()); 496 Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci()); 497 if (cur.is_invokedynamic() || cur.is_invokehandle()) { 498 // Method handle invokes may involve fairly arbitrary chains of 499 // calls so it's impossible to know how much actual space the 500 // caller has for locals. 501 caller_was_method_handle = true; 502 } 503 } 504 505 // 506 // frame_sizes/frame_pcs[0] oldest frame (int or c2i) 507 // frame_sizes/frame_pcs[1] next oldest frame (int) 508 // frame_sizes/frame_pcs[n] youngest frame (int) 509 // 510 // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame 511 // owns the space for the return address to it's caller). Confusing ain't it. 512 // 513 // The vframe array can address vframes with indices running from 514 // 0.._frames-1. Index 0 is the youngest frame and _frame - 1 is the oldest (root) frame. 515 // When we create the skeletal frames we need the oldest frame to be in the zero slot 516 // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk. 517 // so things look a little strange in this loop. 518 // 519 int callee_parameters = 0; 520 int callee_locals = 0; 521 for (int index = 0; index < array->frames(); index++ ) { 522 // frame[number_of_frames - 1 ] = on_stack_size(youngest) 523 // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest)) 524 // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest))) 525 frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters, 526 callee_locals, 527 index == 0, 528 popframe_extra_args); 529 // This pc doesn't have to be perfect just good enough to identify the frame 530 // as interpreted so the skeleton frame will be walkable 531 // The correct pc will be set when the skeleton frame is completely filled out 532 // The final pc we store in the loop is wrong and will be overwritten below 533 frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset; 534 535 callee_parameters = array->element(index)->method()->size_of_parameters(); 536 callee_locals = array->element(index)->method()->max_locals(); 537 popframe_extra_args = 0; 538 } 539 540 // Compute whether the root vframe returns a float or double value. 541 BasicType return_type; 542 { 543 methodHandle method(current, array->element(0)->method()); 544 Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci()); 545 return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL; 546 } 547 548 // Compute information for handling adapters and adjusting the frame size of the caller. 549 int caller_adjustment = 0; 550 551 // Compute the amount the oldest interpreter frame will have to adjust 552 // its caller's stack by. If the caller is a compiled frame then 553 // we pretend that the callee has no parameters so that the 554 // extension counts for the full amount of locals and not just 555 // locals-parms. This is because without a c2i adapter the parm 556 // area as created by the compiled frame will not be usable by 557 // the interpreter. (Depending on the calling convention there 558 // may not even be enough space). 559 560 // QQQ I'd rather see this pushed down into last_frame_adjust 561 // and have it take the sender (aka caller). 562 563 if (deopt_sender.is_compiled_frame() || caller_was_method_handle) { 564 caller_adjustment = last_frame_adjust(0, callee_locals); 565 } else if (callee_locals > callee_parameters) { 566 // The caller frame may need extending to accommodate 567 // non-parameter locals of the first unpacked interpreted frame. 568 // Compute that adjustment. 569 caller_adjustment = last_frame_adjust(callee_parameters, callee_locals); 570 } 571 572 // If the sender is deoptimized the we must retrieve the address of the handler 573 // since the frame will "magically" show the original pc before the deopt 574 // and we'd undo the deopt. 575 576 frame_pcs[0] = deopt_sender.raw_pc(); 577 578 assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc"); 579 580 #if INCLUDE_JVMCI 581 if (exceptionObject() != NULL) { 582 current->set_exception_oop(exceptionObject()); 583 exec_mode = Unpack_exception; 584 } 585 #endif 586 587 if (current->frames_to_pop_failed_realloc() > 0 && exec_mode != Unpack_uncommon_trap) { 588 assert(current->has_pending_exception(), "should have thrown OOME"); 589 current->set_exception_oop(current->pending_exception()); 590 current->clear_pending_exception(); 591 exec_mode = Unpack_exception; 592 } 593 594 #if INCLUDE_JVMCI 595 if (current->frames_to_pop_failed_realloc() > 0) { 596 current->set_pending_monitorenter(false); 597 } 598 #endif 599 600 UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord, 601 caller_adjustment * BytesPerWord, 602 caller_was_method_handle ? 0 : callee_parameters, 603 number_of_frames, 604 frame_sizes, 605 frame_pcs, 606 return_type, 607 exec_mode); 608 // On some platforms, we need a way to pass some platform dependent 609 // information to the unpacking code so the skeletal frames come out 610 // correct (initial fp value, unextended sp, ...) 611 info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info()); 612 613 if (array->frames() > 1) { 614 if (VerifyStack && TraceDeoptimization) { 615 ttyLocker ttyl; 616 tty->print_cr("Deoptimizing method containing inlining"); 617 } 618 } 619 620 array->set_unroll_block(info); 621 return info; 622 } 623 624 // Called to cleanup deoptimization data structures in normal case 625 // after unpacking to stack and when stack overflow error occurs 626 void Deoptimization::cleanup_deopt_info(JavaThread *thread, 627 vframeArray *array) { 628 629 // Get array if coming from exception 630 if (array == NULL) { 631 array = thread->vframe_array_head(); 632 } 633 thread->set_vframe_array_head(NULL); 634 635 // Free the previous UnrollBlock 636 vframeArray* old_array = thread->vframe_array_last(); 637 thread->set_vframe_array_last(array); 638 639 if (old_array != NULL) { 640 UnrollBlock* old_info = old_array->unroll_block(); 641 old_array->set_unroll_block(NULL); 642 delete old_info; 643 delete old_array; 644 } 645 646 // Deallocate any resource creating in this routine and any ResourceObjs allocated 647 // inside the vframeArray (StackValueCollections) 648 649 delete thread->deopt_mark(); 650 thread->set_deopt_mark(NULL); 651 thread->set_deopt_compiled_method(NULL); 652 653 654 if (JvmtiExport::can_pop_frame()) { 655 // Regardless of whether we entered this routine with the pending 656 // popframe condition bit set, we should always clear it now 657 thread->clear_popframe_condition(); 658 } 659 660 // unpack_frames() is called at the end of the deoptimization handler 661 // and (in C2) at the end of the uncommon trap handler. Note this fact 662 // so that an asynchronous stack walker can work again. This counter is 663 // incremented at the beginning of fetch_unroll_info() and (in C2) at 664 // the beginning of uncommon_trap(). 665 thread->dec_in_deopt_handler(); 666 } 667 668 // Moved from cpu directories because none of the cpus has callee save values. 669 // If a cpu implements callee save values, move this to deoptimization_<cpu>.cpp. 670 void Deoptimization::unwind_callee_save_values(frame* f, vframeArray* vframe_array) { 671 672 // This code is sort of the equivalent of C2IAdapter::setup_stack_frame back in 673 // the days we had adapter frames. When we deoptimize a situation where a 674 // compiled caller calls a compiled caller will have registers it expects 675 // to survive the call to the callee. If we deoptimize the callee the only 676 // way we can restore these registers is to have the oldest interpreter 677 // frame that we create restore these values. That is what this routine 678 // will accomplish. 679 680 // At the moment we have modified c2 to not have any callee save registers 681 // so this problem does not exist and this routine is just a place holder. 682 683 assert(f->is_interpreted_frame(), "must be interpreted"); 684 } 685 686 #ifndef PRODUCT 687 static bool falls_through(Bytecodes::Code bc) { 688 switch (bc) { 689 // List may be incomplete. Here we really only care about bytecodes where compiled code 690 // can deoptimize. 691 case Bytecodes::_goto: 692 case Bytecodes::_goto_w: 693 case Bytecodes::_athrow: 694 return false; 695 default: 696 return true; 697 } 698 } 699 #endif 700 701 // Return BasicType of value being returned 702 JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)) 703 704 // We are already active in the special DeoptResourceMark any ResourceObj's we 705 // allocate will be freed at the end of the routine. 706 707 // JRT_LEAF methods don't normally allocate handles and there is a 708 // NoHandleMark to enforce that. It is actually safe to use Handles 709 // in a JRT_LEAF method, and sometimes desirable, but to do so we 710 // must use ResetNoHandleMark to bypass the NoHandleMark, and 711 // then use a HandleMark to ensure any Handles we do create are 712 // cleaned up in this scope. 713 ResetNoHandleMark rnhm; 714 HandleMark hm(thread); 715 716 frame stub_frame = thread->last_frame(); 717 718 // Since the frame to unpack is the top frame of this thread, the vframe_array_head 719 // must point to the vframeArray for the unpack frame. 720 vframeArray* array = thread->vframe_array_head(); 721 722 #ifndef PRODUCT 723 if (TraceDeoptimization) { 724 ttyLocker ttyl; 725 tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d", 726 p2i(thread), p2i(array), exec_mode); 727 } 728 #endif 729 Events::log_deopt_message(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d", 730 p2i(stub_frame.pc()), p2i(stub_frame.sp()), exec_mode); 731 732 UnrollBlock* info = array->unroll_block(); 733 734 // We set the last_Java frame. But the stack isn't really parsable here. So we 735 // clear it to make sure JFR understands not to try and walk stacks from events 736 // in here. 737 intptr_t* sp = thread->frame_anchor()->last_Java_sp(); 738 thread->frame_anchor()->set_last_Java_sp(NULL); 739 740 // Unpack the interpreter frames and any adapter frame (c2 only) we might create. 741 array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters()); 742 743 thread->frame_anchor()->set_last_Java_sp(sp); 744 745 BasicType bt = info->return_type(); 746 747 // If we have an exception pending, claim that the return type is an oop 748 // so the deopt_blob does not overwrite the exception_oop. 749 750 if (exec_mode == Unpack_exception) 751 bt = T_OBJECT; 752 753 // Cleanup thread deopt data 754 cleanup_deopt_info(thread, array); 755 756 #ifndef PRODUCT 757 if (VerifyStack) { 758 ResourceMark res_mark; 759 // Clear pending exception to not break verification code (restored afterwards) 760 PreserveExceptionMark pm(thread); 761 762 thread->validate_frame_layout(); 763 764 // Verify that the just-unpacked frames match the interpreter's 765 // notions of expression stack and locals 766 vframeArray* cur_array = thread->vframe_array_last(); 767 RegisterMap rm(thread, false); 768 rm.set_include_argument_oops(false); 769 bool is_top_frame = true; 770 int callee_size_of_parameters = 0; 771 int callee_max_locals = 0; 772 for (int i = 0; i < cur_array->frames(); i++) { 773 vframeArrayElement* el = cur_array->element(i); 774 frame* iframe = el->iframe(); 775 guarantee(iframe->is_interpreted_frame(), "Wrong frame type"); 776 777 // Get the oop map for this bci 778 InterpreterOopMap mask; 779 int cur_invoke_parameter_size = 0; 780 bool try_next_mask = false; 781 int next_mask_expression_stack_size = -1; 782 int top_frame_expression_stack_adjustment = 0; 783 methodHandle mh(thread, iframe->interpreter_frame_method()); 784 OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask); 785 BytecodeStream str(mh, iframe->interpreter_frame_bci()); 786 int max_bci = mh->code_size(); 787 // Get to the next bytecode if possible 788 assert(str.bci() < max_bci, "bci in interpreter frame out of bounds"); 789 // Check to see if we can grab the number of outgoing arguments 790 // at an uncommon trap for an invoke (where the compiler 791 // generates debug info before the invoke has executed) 792 Bytecodes::Code cur_code = str.next(); 793 Bytecodes::Code next_code = Bytecodes::_shouldnotreachhere; 794 if (Bytecodes::is_invoke(cur_code)) { 795 Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci()); 796 cur_invoke_parameter_size = invoke.size_of_parameters(); 797 if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) { 798 callee_size_of_parameters++; 799 } 800 } 801 if (str.bci() < max_bci) { 802 next_code = str.next(); 803 if (next_code >= 0) { 804 // The interpreter oop map generator reports results before 805 // the current bytecode has executed except in the case of 806 // calls. It seems to be hard to tell whether the compiler 807 // has emitted debug information matching the "state before" 808 // a given bytecode or the state after, so we try both 809 if (!Bytecodes::is_invoke(cur_code) && falls_through(cur_code)) { 810 // Get expression stack size for the next bytecode 811 InterpreterOopMap next_mask; 812 OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask); 813 next_mask_expression_stack_size = next_mask.expression_stack_size(); 814 if (Bytecodes::is_invoke(next_code)) { 815 Bytecode_invoke invoke(mh, str.bci()); 816 next_mask_expression_stack_size += invoke.size_of_parameters(); 817 } 818 // Need to subtract off the size of the result type of 819 // the bytecode because this is not described in the 820 // debug info but returned to the interpreter in the TOS 821 // caching register 822 BasicType bytecode_result_type = Bytecodes::result_type(cur_code); 823 if (bytecode_result_type != T_ILLEGAL) { 824 top_frame_expression_stack_adjustment = type2size[bytecode_result_type]; 825 } 826 assert(top_frame_expression_stack_adjustment >= 0, "stack adjustment must be positive"); 827 try_next_mask = true; 828 } 829 } 830 } 831 832 // Verify stack depth and oops in frame 833 // This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc) 834 if (!( 835 /* SPARC */ 836 (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) || 837 /* x86 */ 838 (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) || 839 (try_next_mask && 840 (iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size - 841 top_frame_expression_stack_adjustment))) || 842 (is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) || 843 (is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute || el->should_reexecute()) && 844 (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size)) 845 )) { 846 { 847 ttyLocker ttyl; 848 849 // Print out some information that will help us debug the problem 850 tty->print_cr("Wrong number of expression stack elements during deoptimization"); 851 tty->print_cr(" Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1); 852 tty->print_cr(" Current code %s", Bytecodes::name(cur_code)); 853 if (try_next_mask) { 854 tty->print_cr(" Next code %s", Bytecodes::name(next_code)); 855 } 856 tty->print_cr(" Fabricated interpreter frame had %d expression stack elements", 857 iframe->interpreter_frame_expression_stack_size()); 858 tty->print_cr(" Interpreter oop map had %d expression stack elements", mask.expression_stack_size()); 859 tty->print_cr(" try_next_mask = %d", try_next_mask); 860 tty->print_cr(" next_mask_expression_stack_size = %d", next_mask_expression_stack_size); 861 tty->print_cr(" callee_size_of_parameters = %d", callee_size_of_parameters); 862 tty->print_cr(" callee_max_locals = %d", callee_max_locals); 863 tty->print_cr(" top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment); 864 tty->print_cr(" exec_mode = %d", exec_mode); 865 tty->print_cr(" cur_invoke_parameter_size = %d", cur_invoke_parameter_size); 866 tty->print_cr(" Thread = " INTPTR_FORMAT ", thread ID = %d", p2i(thread), thread->osthread()->thread_id()); 867 tty->print_cr(" Interpreted frames:"); 868 for (int k = 0; k < cur_array->frames(); k++) { 869 vframeArrayElement* el = cur_array->element(k); 870 tty->print_cr(" %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci()); 871 } 872 cur_array->print_on_2(tty); 873 } // release tty lock before calling guarantee 874 guarantee(false, "wrong number of expression stack elements during deopt"); 875 } 876 VerifyOopClosure verify; 877 iframe->oops_interpreted_do(&verify, &rm, false); 878 callee_size_of_parameters = mh->size_of_parameters(); 879 callee_max_locals = mh->max_locals(); 880 is_top_frame = false; 881 } 882 } 883 #endif /* !PRODUCT */ 884 885 return bt; 886 JRT_END 887 888 class DeoptimizeMarkedClosure : public HandshakeClosure { 889 public: 890 DeoptimizeMarkedClosure() : HandshakeClosure("Deoptimize") {} 891 void do_thread(Thread* thread) { 892 JavaThread* jt = thread->as_Java_thread(); 893 jt->deoptimize_marked_methods(); 894 } 895 }; 896 897 void Deoptimization::deoptimize_all_marked(nmethod* nmethod_only) { 898 ResourceMark rm; 899 DeoptimizationMarker dm; 900 901 // Make the dependent methods not entrant 902 if (nmethod_only != NULL) { 903 nmethod_only->mark_for_deoptimization(); 904 nmethod_only->make_not_entrant(); 905 } else { 906 MutexLocker mu(SafepointSynchronize::is_at_safepoint() ? NULL : CodeCache_lock, Mutex::_no_safepoint_check_flag); 907 CodeCache::make_marked_nmethods_not_entrant(); 908 } 909 910 DeoptimizeMarkedClosure deopt; 911 if (SafepointSynchronize::is_at_safepoint()) { 912 Threads::java_threads_do(&deopt); 913 } else { 914 Handshake::execute(&deopt); 915 } 916 } 917 918 Deoptimization::DeoptAction Deoptimization::_unloaded_action 919 = Deoptimization::Action_reinterpret; 920 921 #if COMPILER2_OR_JVMCI 922 template<typename CacheType> 923 class BoxCacheBase : public CHeapObj<mtCompiler> { 924 protected: 925 static InstanceKlass* find_cache_klass(Symbol* klass_name) { 926 ResourceMark rm; 927 char* klass_name_str = klass_name->as_C_string(); 928 InstanceKlass* ik = SystemDictionary::find_instance_klass(klass_name, Handle(), Handle()); 929 guarantee(ik != NULL, "%s must be loaded", klass_name_str); 930 guarantee(ik->is_initialized(), "%s must be initialized", klass_name_str); 931 CacheType::compute_offsets(ik); 932 return ik; 933 } 934 }; 935 936 template<typename PrimitiveType, typename CacheType, typename BoxType> class BoxCache : public BoxCacheBase<CacheType> { 937 PrimitiveType _low; 938 PrimitiveType _high; 939 jobject _cache; 940 protected: 941 static BoxCache<PrimitiveType, CacheType, BoxType> *_singleton; 942 BoxCache(Thread* thread) { 943 InstanceKlass* ik = BoxCacheBase<CacheType>::find_cache_klass(CacheType::symbol()); 944 objArrayOop cache = CacheType::cache(ik); 945 assert(cache->length() > 0, "Empty cache"); 946 _low = BoxType::value(cache->obj_at(0)); 947 _high = _low + cache->length() - 1; 948 _cache = JNIHandles::make_global(Handle(thread, cache)); 949 } 950 ~BoxCache() { 951 JNIHandles::destroy_global(_cache); 952 } 953 public: 954 static BoxCache<PrimitiveType, CacheType, BoxType>* singleton(Thread* thread) { 955 if (_singleton == NULL) { 956 BoxCache<PrimitiveType, CacheType, BoxType>* s = new BoxCache<PrimitiveType, CacheType, BoxType>(thread); 957 if (!Atomic::replace_if_null(&_singleton, s)) { 958 delete s; 959 } 960 } 961 return _singleton; 962 } 963 oop lookup(PrimitiveType value) { 964 if (_low <= value && value <= _high) { 965 int offset = value - _low; 966 return objArrayOop(JNIHandles::resolve_non_null(_cache))->obj_at(offset); 967 } 968 return NULL; 969 } 970 oop lookup_raw(intptr_t raw_value) { 971 // Have to cast to avoid little/big-endian problems. 972 if (sizeof(PrimitiveType) > sizeof(jint)) { 973 jlong value = (jlong)raw_value; 974 return lookup(value); 975 } 976 PrimitiveType value = (PrimitiveType)*((jint*)&raw_value); 977 return lookup(value); 978 } 979 }; 980 981 typedef BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer> IntegerBoxCache; 982 typedef BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long> LongBoxCache; 983 typedef BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character> CharacterBoxCache; 984 typedef BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short> ShortBoxCache; 985 typedef BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte> ByteBoxCache; 986 987 template<> BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>* BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>::_singleton = NULL; 988 template<> BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>* BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>::_singleton = NULL; 989 template<> BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>* BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>::_singleton = NULL; 990 template<> BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>* BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>::_singleton = NULL; 991 template<> BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>* BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>::_singleton = NULL; 992 993 class BooleanBoxCache : public BoxCacheBase<java_lang_Boolean> { 994 jobject _true_cache; 995 jobject _false_cache; 996 protected: 997 static BooleanBoxCache *_singleton; 998 BooleanBoxCache(Thread *thread) { 999 InstanceKlass* ik = find_cache_klass(java_lang_Boolean::symbol()); 1000 _true_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_TRUE(ik))); 1001 _false_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_FALSE(ik))); 1002 } 1003 ~BooleanBoxCache() { 1004 JNIHandles::destroy_global(_true_cache); 1005 JNIHandles::destroy_global(_false_cache); 1006 } 1007 public: 1008 static BooleanBoxCache* singleton(Thread* thread) { 1009 if (_singleton == NULL) { 1010 BooleanBoxCache* s = new BooleanBoxCache(thread); 1011 if (!Atomic::replace_if_null(&_singleton, s)) { 1012 delete s; 1013 } 1014 } 1015 return _singleton; 1016 } 1017 oop lookup_raw(intptr_t raw_value) { 1018 // Have to cast to avoid little/big-endian problems. 1019 jboolean value = (jboolean)*((jint*)&raw_value); 1020 return lookup(value); 1021 } 1022 oop lookup(jboolean value) { 1023 if (value != 0) { 1024 return JNIHandles::resolve_non_null(_true_cache); 1025 } 1026 return JNIHandles::resolve_non_null(_false_cache); 1027 } 1028 }; 1029 1030 BooleanBoxCache* BooleanBoxCache::_singleton = NULL; 1031 1032 oop Deoptimization::get_cached_box(AutoBoxObjectValue* bv, frame* fr, RegisterMap* reg_map, TRAPS) { 1033 Klass* k = java_lang_Class::as_Klass(bv->klass()->as_ConstantOopReadValue()->value()()); 1034 BasicType box_type = vmClasses::box_klass_type(k); 1035 if (box_type != T_OBJECT) { 1036 StackValue* value = StackValue::create_stack_value(fr, reg_map, bv->field_at(box_type == T_LONG ? 1 : 0)); 1037 switch(box_type) { 1038 case T_INT: return IntegerBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 1039 case T_CHAR: return CharacterBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 1040 case T_SHORT: return ShortBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 1041 case T_BYTE: return ByteBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 1042 case T_BOOLEAN: return BooleanBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 1043 case T_LONG: return LongBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 1044 default:; 1045 } 1046 } 1047 return NULL; 1048 } 1049 1050 bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) { 1051 Handle pending_exception(THREAD, thread->pending_exception()); 1052 const char* exception_file = thread->exception_file(); 1053 int exception_line = thread->exception_line(); 1054 thread->clear_pending_exception(); 1055 1056 bool failures = false; 1057 1058 for (int i = 0; i < objects->length(); i++) { 1059 assert(objects->at(i)->is_object(), "invalid debug information"); 1060 ObjectValue* sv = (ObjectValue*) objects->at(i); 1061 1062 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()); 1063 oop obj = NULL; 1064 1065 if (k->is_instance_klass()) { 1066 if (sv->is_auto_box()) { 1067 AutoBoxObjectValue* abv = (AutoBoxObjectValue*) sv; 1068 obj = get_cached_box(abv, fr, reg_map, THREAD); 1069 if (obj != NULL) { 1070 // Set the flag to indicate the box came from a cache, so that we can skip the field reassignment for it. 1071 abv->set_cached(true); 1072 } 1073 } 1074 1075 InstanceKlass* ik = InstanceKlass::cast(k); 1076 if (obj == NULL) { 1077 #ifdef COMPILER2 1078 if (EnableVectorSupport && VectorSupport::is_vector(ik)) { 1079 obj = VectorSupport::allocate_vector(ik, fr, reg_map, sv, THREAD); 1080 } else { 1081 obj = ik->allocate_instance(THREAD); 1082 } 1083 #else 1084 obj = ik->allocate_instance(THREAD); 1085 #endif // COMPILER2 1086 } 1087 } else if (k->is_typeArray_klass()) { 1088 TypeArrayKlass* ak = TypeArrayKlass::cast(k); 1089 assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length"); 1090 int len = sv->field_size() / type2size[ak->element_type()]; 1091 obj = ak->allocate(len, THREAD); 1092 } else if (k->is_objArray_klass()) { 1093 ObjArrayKlass* ak = ObjArrayKlass::cast(k); 1094 obj = ak->allocate(sv->field_size(), THREAD); 1095 } 1096 1097 if (obj == NULL) { 1098 failures = true; 1099 } 1100 1101 assert(sv->value().is_null(), "redundant reallocation"); 1102 assert(obj != NULL || HAS_PENDING_EXCEPTION, "allocation should succeed or we should get an exception"); 1103 CLEAR_PENDING_EXCEPTION; 1104 sv->set_value(obj); 1105 } 1106 1107 if (failures) { 1108 THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures); 1109 } else if (pending_exception.not_null()) { 1110 thread->set_pending_exception(pending_exception(), exception_file, exception_line); 1111 } 1112 1113 return failures; 1114 } 1115 1116 #if INCLUDE_JVMCI 1117 /** 1118 * For primitive types whose kind gets "erased" at runtime (shorts become stack ints), 1119 * we need to somehow be able to recover the actual kind to be able to write the correct 1120 * amount of bytes. 1121 * For that purpose, this method assumes that, for an entry spanning n bytes at index i, 1122 * the entries at index n + 1 to n + i are 'markers'. 1123 * For example, if we were writing a short at index 4 of a byte array of size 8, the 1124 * expected form of the array would be: 1125 * 1126 * {b0, b1, b2, b3, INT, marker, b6, b7} 1127 * 1128 * Thus, in order to get back the size of the entry, we simply need to count the number 1129 * of marked entries 1130 * 1131 * @param virtualArray the virtualized byte array 1132 * @param i index of the virtual entry we are recovering 1133 * @return The number of bytes the entry spans 1134 */ 1135 static int count_number_of_bytes_for_entry(ObjectValue *virtualArray, int i) { 1136 int index = i; 1137 while (++index < virtualArray->field_size() && 1138 virtualArray->field_at(index)->is_marker()) {} 1139 return index - i; 1140 } 1141 1142 /** 1143 * If there was a guarantee for byte array to always start aligned to a long, we could 1144 * do a simple check on the parity of the index. Unfortunately, that is not always the 1145 * case. Thus, we check alignment of the actual address we are writing to. 1146 * In the unlikely case index 0 is 5-aligned for example, it would then be possible to 1147 * write a long to index 3. 1148 */ 1149 static jbyte* check_alignment_get_addr(typeArrayOop obj, int index, int expected_alignment) { 1150 jbyte* res = obj->byte_at_addr(index); 1151 assert((((intptr_t) res) % expected_alignment) == 0, "Non-aligned write"); 1152 return res; 1153 } 1154 1155 static void byte_array_put(typeArrayOop obj, intptr_t val, int index, int byte_count) { 1156 switch (byte_count) { 1157 case 1: 1158 obj->byte_at_put(index, (jbyte) *((jint *) &val)); 1159 break; 1160 case 2: 1161 *((jshort *) check_alignment_get_addr(obj, index, 2)) = (jshort) *((jint *) &val); 1162 break; 1163 case 4: 1164 *((jint *) check_alignment_get_addr(obj, index, 4)) = (jint) *((jint *) &val); 1165 break; 1166 case 8: 1167 *((jlong *) check_alignment_get_addr(obj, index, 8)) = (jlong) *((jlong *) &val); 1168 break; 1169 default: 1170 ShouldNotReachHere(); 1171 } 1172 } 1173 #endif // INCLUDE_JVMCI 1174 1175 1176 // restore elements of an eliminated type array 1177 void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) { 1178 int index = 0; 1179 intptr_t val; 1180 1181 for (int i = 0; i < sv->field_size(); i++) { 1182 StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i)); 1183 switch(type) { 1184 case T_LONG: case T_DOUBLE: { 1185 assert(value->type() == T_INT, "Agreement."); 1186 StackValue* low = 1187 StackValue::create_stack_value(fr, reg_map, sv->field_at(++i)); 1188 #ifdef _LP64 1189 jlong res = (jlong)low->get_int(); 1190 #else 1191 jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int()); 1192 #endif 1193 obj->long_at_put(index, res); 1194 break; 1195 } 1196 1197 // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem. 1198 case T_INT: case T_FLOAT: { // 4 bytes. 1199 assert(value->type() == T_INT, "Agreement."); 1200 bool big_value = false; 1201 if (i + 1 < sv->field_size() && type == T_INT) { 1202 if (sv->field_at(i)->is_location()) { 1203 Location::Type type = ((LocationValue*) sv->field_at(i))->location().type(); 1204 if (type == Location::dbl || type == Location::lng) { 1205 big_value = true; 1206 } 1207 } else if (sv->field_at(i)->is_constant_int()) { 1208 ScopeValue* next_scope_field = sv->field_at(i + 1); 1209 if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) { 1210 big_value = true; 1211 } 1212 } 1213 } 1214 1215 if (big_value) { 1216 StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++i)); 1217 #ifdef _LP64 1218 jlong res = (jlong)low->get_int(); 1219 #else 1220 jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int()); 1221 #endif 1222 obj->int_at_put(index, (jint)*((jint*)&res)); 1223 obj->int_at_put(++index, (jint)*(((jint*)&res) + 1)); 1224 } else { 1225 val = value->get_int(); 1226 obj->int_at_put(index, (jint)*((jint*)&val)); 1227 } 1228 break; 1229 } 1230 1231 case T_SHORT: 1232 assert(value->type() == T_INT, "Agreement."); 1233 val = value->get_int(); 1234 obj->short_at_put(index, (jshort)*((jint*)&val)); 1235 break; 1236 1237 case T_CHAR: 1238 assert(value->type() == T_INT, "Agreement."); 1239 val = value->get_int(); 1240 obj->char_at_put(index, (jchar)*((jint*)&val)); 1241 break; 1242 1243 case T_BYTE: { 1244 assert(value->type() == T_INT, "Agreement."); 1245 // The value we get is erased as a regular int. We will need to find its actual byte count 'by hand'. 1246 val = value->get_int(); 1247 #if INCLUDE_JVMCI 1248 int byte_count = count_number_of_bytes_for_entry(sv, i); 1249 byte_array_put(obj, val, index, byte_count); 1250 // According to byte_count contract, the values from i + 1 to i + byte_count are illegal values. Skip. 1251 i += byte_count - 1; // Balance the loop counter. 1252 index += byte_count; 1253 // index has been updated so continue at top of loop 1254 continue; 1255 #else 1256 obj->byte_at_put(index, (jbyte)*((jint*)&val)); 1257 break; 1258 #endif // INCLUDE_JVMCI 1259 } 1260 1261 case T_BOOLEAN: { 1262 assert(value->type() == T_INT, "Agreement."); 1263 val = value->get_int(); 1264 obj->bool_at_put(index, (jboolean)*((jint*)&val)); 1265 break; 1266 } 1267 1268 default: 1269 ShouldNotReachHere(); 1270 } 1271 index++; 1272 } 1273 } 1274 1275 // restore fields of an eliminated object array 1276 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) { 1277 for (int i = 0; i < sv->field_size(); i++) { 1278 StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i)); 1279 assert(value->type() == T_OBJECT, "object element expected"); 1280 obj->obj_at_put(i, value->get_obj()()); 1281 } 1282 } 1283 1284 class ReassignedField { 1285 public: 1286 int _offset; 1287 BasicType _type; 1288 public: 1289 ReassignedField() { 1290 _offset = 0; 1291 _type = T_ILLEGAL; 1292 } 1293 }; 1294 1295 int compare(ReassignedField* left, ReassignedField* right) { 1296 return left->_offset - right->_offset; 1297 } 1298 1299 // Restore fields of an eliminated instance object using the same field order 1300 // returned by HotSpotResolvedObjectTypeImpl.getInstanceFields(true) 1301 static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool skip_internal) { 1302 GrowableArray<ReassignedField>* fields = new GrowableArray<ReassignedField>(); 1303 InstanceKlass* ik = klass; 1304 while (ik != NULL) { 1305 for (AllFieldStream fs(ik); !fs.done(); fs.next()) { 1306 if (!fs.access_flags().is_static() && (!skip_internal || !fs.access_flags().is_internal())) { 1307 ReassignedField field; 1308 field._offset = fs.offset(); 1309 field._type = Signature::basic_type(fs.signature()); 1310 fields->append(field); 1311 } 1312 } 1313 ik = ik->superklass(); 1314 } 1315 fields->sort(compare); 1316 for (int i = 0; i < fields->length(); i++) { 1317 intptr_t val; 1318 ScopeValue* scope_field = sv->field_at(svIndex); 1319 StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field); 1320 int offset = fields->at(i)._offset; 1321 BasicType type = fields->at(i)._type; 1322 switch (type) { 1323 case T_OBJECT: case T_ARRAY: 1324 assert(value->type() == T_OBJECT, "Agreement."); 1325 obj->obj_field_put(offset, value->get_obj()()); 1326 break; 1327 1328 // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem. 1329 case T_INT: case T_FLOAT: { // 4 bytes. 1330 assert(value->type() == T_INT, "Agreement."); 1331 bool big_value = false; 1332 if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) { 1333 if (scope_field->is_location()) { 1334 Location::Type type = ((LocationValue*) scope_field)->location().type(); 1335 if (type == Location::dbl || type == Location::lng) { 1336 big_value = true; 1337 } 1338 } 1339 if (scope_field->is_constant_int()) { 1340 ScopeValue* next_scope_field = sv->field_at(svIndex + 1); 1341 if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) { 1342 big_value = true; 1343 } 1344 } 1345 } 1346 1347 if (big_value) { 1348 i++; 1349 assert(i < fields->length(), "second T_INT field needed"); 1350 assert(fields->at(i)._type == T_INT, "T_INT field needed"); 1351 } else { 1352 val = value->get_int(); 1353 obj->int_field_put(offset, (jint)*((jint*)&val)); 1354 break; 1355 } 1356 } 1357 /* no break */ 1358 1359 case T_LONG: case T_DOUBLE: { 1360 assert(value->type() == T_INT, "Agreement."); 1361 StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++svIndex)); 1362 #ifdef _LP64 1363 jlong res = (jlong)low->get_int(); 1364 #else 1365 jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int()); 1366 #endif 1367 obj->long_field_put(offset, res); 1368 break; 1369 } 1370 1371 case T_SHORT: 1372 assert(value->type() == T_INT, "Agreement."); 1373 val = value->get_int(); 1374 obj->short_field_put(offset, (jshort)*((jint*)&val)); 1375 break; 1376 1377 case T_CHAR: 1378 assert(value->type() == T_INT, "Agreement."); 1379 val = value->get_int(); 1380 obj->char_field_put(offset, (jchar)*((jint*)&val)); 1381 break; 1382 1383 case T_BYTE: 1384 assert(value->type() == T_INT, "Agreement."); 1385 val = value->get_int(); 1386 obj->byte_field_put(offset, (jbyte)*((jint*)&val)); 1387 break; 1388 1389 case T_BOOLEAN: 1390 assert(value->type() == T_INT, "Agreement."); 1391 val = value->get_int(); 1392 obj->bool_field_put(offset, (jboolean)*((jint*)&val)); 1393 break; 1394 1395 default: 1396 ShouldNotReachHere(); 1397 } 1398 svIndex++; 1399 } 1400 return svIndex; 1401 } 1402 1403 // restore fields of all eliminated objects and arrays 1404 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool skip_internal) { 1405 for (int i = 0; i < objects->length(); i++) { 1406 ObjectValue* sv = (ObjectValue*) objects->at(i); 1407 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()); 1408 Handle obj = sv->value(); 1409 assert(obj.not_null() || realloc_failures, "reallocation was missed"); 1410 if (PrintDeoptimizationDetails) { 1411 tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string()); 1412 } 1413 if (obj.is_null()) { 1414 continue; 1415 } 1416 1417 // Don't reassign fields of boxes that came from a cache. Caches may be in CDS. 1418 if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) { 1419 continue; 1420 } 1421 #ifdef COMPILER2 1422 if (EnableVectorSupport && VectorSupport::is_vector(k)) { 1423 assert(sv->field_size() == 1, "%s not a vector", k->name()->as_C_string()); 1424 ScopeValue* payload = sv->field_at(0); 1425 if (payload->is_location() && 1426 payload->as_LocationValue()->location().type() == Location::vector) { 1427 if (PrintDeoptimizationDetails) { 1428 tty->print_cr("skip field reassignment for this vector - it should be assigned already"); 1429 if (Verbose) { 1430 Handle obj = sv->value(); 1431 k->oop_print_on(obj(), tty); 1432 } 1433 } 1434 continue; // Such vector's value was already restored in VectorSupport::allocate_vector(). 1435 } 1436 // Else fall-through to do assignment for scalar-replaced boxed vector representation 1437 // which could be restored after vector object allocation. 1438 } 1439 #endif 1440 if (k->is_instance_klass()) { 1441 InstanceKlass* ik = InstanceKlass::cast(k); 1442 reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), skip_internal); 1443 } else if (k->is_typeArray_klass()) { 1444 TypeArrayKlass* ak = TypeArrayKlass::cast(k); 1445 reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type()); 1446 } else if (k->is_objArray_klass()) { 1447 reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj()); 1448 } 1449 } 1450 } 1451 1452 1453 // relock objects for which synchronization was eliminated 1454 bool Deoptimization::relock_objects(JavaThread* thread, GrowableArray<MonitorInfo*>* monitors, 1455 JavaThread* deoptee_thread, frame& fr, int exec_mode, bool realloc_failures) { 1456 bool relocked_objects = false; 1457 for (int i = 0; i < monitors->length(); i++) { 1458 MonitorInfo* mon_info = monitors->at(i); 1459 if (mon_info->eliminated()) { 1460 assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed"); 1461 relocked_objects = true; 1462 if (!mon_info->owner_is_scalar_replaced()) { 1463 Handle obj(thread, mon_info->owner()); 1464 markWord mark = obj->mark(); 1465 if (UseBiasedLocking && mark.has_bias_pattern()) { 1466 // New allocated objects may have the mark set to anonymously biased. 1467 // Also the deoptimized method may called methods with synchronization 1468 // where the thread-local object is bias locked to the current thread. 1469 assert(mark.is_biased_anonymously() || 1470 mark.biased_locker() == deoptee_thread, "should be locked to current thread"); 1471 // Reset mark word to unbiased prototype. 1472 markWord unbiased_prototype = markWord::prototype().set_age(mark.age()); 1473 obj->set_mark(unbiased_prototype); 1474 } else if (exec_mode == Unpack_none) { 1475 if (mark.has_locker() && fr.sp() > (intptr_t*)mark.locker()) { 1476 // With exec_mode == Unpack_none obj may be thread local and locked in 1477 // a callee frame. In this case the bias was revoked before in revoke_for_object_deoptimization(). 1478 // Make the lock in the callee a recursive lock and restore the displaced header. 1479 markWord dmw = mark.displaced_mark_helper(); 1480 mark.locker()->set_displaced_header(markWord::encode((BasicLock*) NULL)); 1481 obj->set_mark(dmw); 1482 } 1483 if (mark.has_monitor()) { 1484 // defer relocking if the deoptee thread is currently waiting for obj 1485 ObjectMonitor* waiting_monitor = deoptee_thread->current_waiting_monitor(); 1486 if (waiting_monitor != NULL && waiting_monitor->object() == obj()) { 1487 assert(fr.is_deoptimized_frame(), "frame must be scheduled for deoptimization"); 1488 mon_info->lock()->set_displaced_header(markWord::unused_mark()); 1489 JvmtiDeferredUpdates::inc_relock_count_after_wait(deoptee_thread); 1490 continue; 1491 } 1492 } 1493 } 1494 BasicLock* lock = mon_info->lock(); 1495 ObjectSynchronizer::enter(obj, lock, deoptee_thread); 1496 assert(mon_info->owner()->is_locked(), "object must be locked now"); 1497 } 1498 } 1499 } 1500 return relocked_objects; 1501 } 1502 1503 1504 #ifndef PRODUCT 1505 // print information about reallocated objects 1506 void Deoptimization::print_objects(GrowableArray<ScopeValue*>* objects, bool realloc_failures) { 1507 fieldDescriptor fd; 1508 1509 for (int i = 0; i < objects->length(); i++) { 1510 ObjectValue* sv = (ObjectValue*) objects->at(i); 1511 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()); 1512 Handle obj = sv->value(); 1513 1514 tty->print(" object <" INTPTR_FORMAT "> of type ", p2i(sv->value()())); 1515 k->print_value(); 1516 assert(obj.not_null() || realloc_failures, "reallocation was missed"); 1517 if (obj.is_null()) { 1518 tty->print(" allocation failed"); 1519 } else { 1520 tty->print(" allocated (%d bytes)", obj->size() * HeapWordSize); 1521 } 1522 tty->cr(); 1523 1524 if (Verbose && !obj.is_null()) { 1525 k->oop_print_on(obj(), tty); 1526 } 1527 } 1528 } 1529 #endif 1530 #endif // COMPILER2_OR_JVMCI 1531 1532 vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) { 1533 Events::log_deopt_message(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, p2i(fr.pc()), p2i(fr.sp())); 1534 1535 #ifndef PRODUCT 1536 if (PrintDeoptimizationDetails) { 1537 ttyLocker ttyl; 1538 tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", p2i(thread)); 1539 fr.print_on(tty); 1540 tty->print_cr(" Virtual frames (innermost first):"); 1541 for (int index = 0; index < chunk->length(); index++) { 1542 compiledVFrame* vf = chunk->at(index); 1543 tty->print(" %2d - ", index); 1544 vf->print_value(); 1545 int bci = chunk->at(index)->raw_bci(); 1546 const char* code_name; 1547 if (bci == SynchronizationEntryBCI) { 1548 code_name = "sync entry"; 1549 } else { 1550 Bytecodes::Code code = vf->method()->code_at(bci); 1551 code_name = Bytecodes::name(code); 1552 } 1553 tty->print(" - %s", code_name); 1554 tty->print_cr(" @ bci %d ", bci); 1555 if (Verbose) { 1556 vf->print(); 1557 tty->cr(); 1558 } 1559 } 1560 } 1561 #endif 1562 1563 // Register map for next frame (used for stack crawl). We capture 1564 // the state of the deopt'ing frame's caller. Thus if we need to 1565 // stuff a C2I adapter we can properly fill in the callee-save 1566 // register locations. 1567 frame caller = fr.sender(reg_map); 1568 int frame_size = caller.sp() - fr.sp(); 1569 1570 frame sender = caller; 1571 1572 // Since the Java thread being deoptimized will eventually adjust it's own stack, 1573 // the vframeArray containing the unpacking information is allocated in the C heap. 1574 // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames(). 1575 vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures); 1576 1577 // Compare the vframeArray to the collected vframes 1578 assert(array->structural_compare(thread, chunk), "just checking"); 1579 1580 #ifndef PRODUCT 1581 if (PrintDeoptimizationDetails) { 1582 ttyLocker ttyl; 1583 tty->print_cr(" Created vframeArray " INTPTR_FORMAT, p2i(array)); 1584 } 1585 #endif // PRODUCT 1586 1587 return array; 1588 } 1589 1590 #if COMPILER2_OR_JVMCI 1591 void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) { 1592 // Reallocation of some scalar replaced objects failed. Record 1593 // that we need to pop all the interpreter frames for the 1594 // deoptimized compiled frame. 1595 assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?"); 1596 thread->set_frames_to_pop_failed_realloc(array->frames()); 1597 // Unlock all monitors here otherwise the interpreter will see a 1598 // mix of locked and unlocked monitors (because of failed 1599 // reallocations of synchronized objects) and be confused. 1600 for (int i = 0; i < array->frames(); i++) { 1601 MonitorChunk* monitors = array->element(i)->monitors(); 1602 if (monitors != NULL) { 1603 for (int j = 0; j < monitors->number_of_monitors(); j++) { 1604 BasicObjectLock* src = monitors->at(j); 1605 if (src->obj() != NULL) { 1606 ObjectSynchronizer::exit(src->obj(), src->lock(), thread); 1607 } 1608 } 1609 array->element(i)->free_monitors(thread); 1610 #ifdef ASSERT 1611 array->element(i)->set_removed_monitors(); 1612 #endif 1613 } 1614 } 1615 } 1616 #endif 1617 1618 static void collect_monitors(compiledVFrame* cvf, GrowableArray<Handle>* objects_to_revoke, 1619 bool only_eliminated) { 1620 GrowableArray<MonitorInfo*>* monitors = cvf->monitors(); 1621 Thread* thread = Thread::current(); 1622 for (int i = 0; i < monitors->length(); i++) { 1623 MonitorInfo* mon_info = monitors->at(i); 1624 if (mon_info->eliminated() == only_eliminated && 1625 !mon_info->owner_is_scalar_replaced() && 1626 mon_info->owner() != NULL) { 1627 objects_to_revoke->append(Handle(thread, mon_info->owner())); 1628 } 1629 } 1630 } 1631 1632 static void get_monitors_from_stack(GrowableArray<Handle>* objects_to_revoke, JavaThread* thread, 1633 frame fr, RegisterMap* map, bool only_eliminated) { 1634 // Unfortunately we don't have a RegisterMap available in most of 1635 // the places we want to call this routine so we need to walk the 1636 // stack again to update the register map. 1637 if (map == NULL || !map->update_map()) { 1638 StackFrameStream sfs(thread, true /* update */, true /* process_frames */); 1639 bool found = false; 1640 while (!found && !sfs.is_done()) { 1641 frame* cur = sfs.current(); 1642 sfs.next(); 1643 found = cur->id() == fr.id(); 1644 } 1645 assert(found, "frame to be deoptimized not found on target thread's stack"); 1646 map = sfs.register_map(); 1647 } 1648 1649 vframe* vf = vframe::new_vframe(&fr, map, thread); 1650 compiledVFrame* cvf = compiledVFrame::cast(vf); 1651 // Revoke monitors' biases in all scopes 1652 while (!cvf->is_top()) { 1653 collect_monitors(cvf, objects_to_revoke, only_eliminated); 1654 cvf = compiledVFrame::cast(cvf->sender()); 1655 } 1656 collect_monitors(cvf, objects_to_revoke, only_eliminated); 1657 } 1658 1659 void Deoptimization::revoke_from_deopt_handler(JavaThread* thread, frame fr, RegisterMap* map) { 1660 if (!UseBiasedLocking) { 1661 return; 1662 } 1663 assert(thread == Thread::current(), "should be"); 1664 ResourceMark rm(thread); 1665 HandleMark hm(thread); 1666 GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>(); 1667 get_monitors_from_stack(objects_to_revoke, thread, fr, map, false); 1668 1669 int len = objects_to_revoke->length(); 1670 for (int i = 0; i < len; i++) { 1671 oop obj = (objects_to_revoke->at(i))(); 1672 BiasedLocking::revoke_own_lock(thread, objects_to_revoke->at(i)); 1673 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 1674 } 1675 } 1676 1677 // Revoke the bias of objects with eliminated locking to prepare subsequent relocking. 1678 void Deoptimization::revoke_for_object_deoptimization(JavaThread* deoptee_thread, frame fr, 1679 RegisterMap* map, JavaThread* thread) { 1680 if (!UseBiasedLocking) { 1681 return; 1682 } 1683 GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>(); 1684 assert(KeepStackGCProcessedMark::stack_is_kept_gc_processed(deoptee_thread), "must be"); 1685 // Collect monitors but only those with eliminated locking. 1686 get_monitors_from_stack(objects_to_revoke, deoptee_thread, fr, map, true); 1687 1688 int len = objects_to_revoke->length(); 1689 for (int i = 0; i < len; i++) { 1690 oop obj = (objects_to_revoke->at(i))(); 1691 markWord mark = obj->mark(); 1692 if (!mark.has_bias_pattern() || 1693 mark.is_biased_anonymously() || // eliminated locking does not bias an object if it wasn't before 1694 !obj->klass()->prototype_header().has_bias_pattern() || // bulk revoke ignores eliminated monitors 1695 (obj->klass()->prototype_header().bias_epoch() != mark.bias_epoch())) { // bulk rebias ignores eliminated monitors 1696 // We reach here regularly if there's just eliminated locking on obj. 1697 // We must not call BiasedLocking::revoke_own_lock() in this case, as we 1698 // would hit assertions because it is a prerequisite that there has to be 1699 // non-eliminated locking on obj by deoptee_thread. 1700 // Luckily we don't have to revoke here because obj has to be a 1701 // non-escaping obj and can be relocked without revoking the bias. See 1702 // Deoptimization::relock_objects(). 1703 continue; 1704 } 1705 BiasedLocking::revoke(thread, objects_to_revoke->at(i)); 1706 assert(!objects_to_revoke->at(i)->mark().has_bias_pattern(), "biases should be revoked by now"); 1707 } 1708 } 1709 1710 void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) { 1711 assert(fr.can_be_deoptimized(), "checking frame type"); 1712 1713 gather_statistics(reason, Action_none, Bytecodes::_illegal); 1714 1715 if (LogCompilation && xtty != NULL) { 1716 CompiledMethod* cm = fr.cb()->as_compiled_method_or_null(); 1717 assert(cm != NULL, "only compiled methods can deopt"); 1718 1719 ttyLocker ttyl; 1720 xtty->begin_head("deoptimized thread='" UINTX_FORMAT "' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc())); 1721 cm->log_identity(xtty); 1722 xtty->end_head(); 1723 for (ScopeDesc* sd = cm->scope_desc_at(fr.pc()); ; sd = sd->sender()) { 1724 xtty->begin_elem("jvms bci='%d'", sd->bci()); 1725 xtty->method(sd->method()); 1726 xtty->end_elem(); 1727 if (sd->is_top()) break; 1728 } 1729 xtty->tail("deoptimized"); 1730 } 1731 1732 // Patch the compiled method so that when execution returns to it we will 1733 // deopt the execution state and return to the interpreter. 1734 fr.deoptimize(thread); 1735 } 1736 1737 void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) { 1738 // Deoptimize only if the frame comes from compile code. 1739 // Do not deoptimize the frame which is already patched 1740 // during the execution of the loops below. 1741 if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) { 1742 return; 1743 } 1744 ResourceMark rm; 1745 DeoptimizationMarker dm; 1746 deoptimize_single_frame(thread, fr, reason); 1747 } 1748 1749 #if INCLUDE_JVMCI 1750 address Deoptimization::deoptimize_for_missing_exception_handler(CompiledMethod* cm) { 1751 // there is no exception handler for this pc => deoptimize 1752 cm->make_not_entrant(); 1753 1754 // Use Deoptimization::deoptimize for all of its side-effects: 1755 // gathering traps statistics, logging... 1756 // it also patches the return pc but we do not care about that 1757 // since we return a continuation to the deopt_blob below. 1758 JavaThread* thread = JavaThread::current(); 1759 RegisterMap reg_map(thread, false); 1760 frame runtime_frame = thread->last_frame(); 1761 frame caller_frame = runtime_frame.sender(®_map); 1762 assert(caller_frame.cb()->as_compiled_method_or_null() == cm, "expect top frame compiled method"); 1763 vframe* vf = vframe::new_vframe(&caller_frame, ®_map, thread); 1764 compiledVFrame* cvf = compiledVFrame::cast(vf); 1765 ScopeDesc* imm_scope = cvf->scope(); 1766 MethodData* imm_mdo = get_method_data(thread, methodHandle(thread, imm_scope->method()), true); 1767 if (imm_mdo != NULL) { 1768 ProfileData* pdata = imm_mdo->allocate_bci_to_data(imm_scope->bci(), NULL); 1769 if (pdata != NULL && pdata->is_BitData()) { 1770 BitData* bit_data = (BitData*) pdata; 1771 bit_data->set_exception_seen(); 1772 } 1773 } 1774 1775 Deoptimization::deoptimize(thread, caller_frame, Deoptimization::Reason_not_compiled_exception_handler); 1776 1777 MethodData* trap_mdo = get_method_data(thread, methodHandle(thread, cm->method()), true); 1778 if (trap_mdo != NULL) { 1779 trap_mdo->inc_trap_count(Deoptimization::Reason_not_compiled_exception_handler); 1780 } 1781 1782 return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls(); 1783 } 1784 #endif 1785 1786 void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id, DeoptReason reason) { 1787 assert(thread == Thread::current() || 1788 thread->is_handshake_safe_for(Thread::current()) || 1789 SafepointSynchronize::is_at_safepoint(), 1790 "can only deoptimize other thread at a safepoint/handshake"); 1791 // Compute frame and register map based on thread and sp. 1792 RegisterMap reg_map(thread, false); 1793 frame fr = thread->last_frame(); 1794 while (fr.id() != id) { 1795 fr = fr.sender(®_map); 1796 } 1797 deoptimize(thread, fr, reason); 1798 } 1799 1800 1801 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id, DeoptReason reason) { 1802 Thread* current = Thread::current(); 1803 if (thread == current || thread->is_handshake_safe_for(current)) { 1804 Deoptimization::deoptimize_frame_internal(thread, id, reason); 1805 } else { 1806 VM_DeoptimizeFrame deopt(thread, id, reason); 1807 VMThread::execute(&deopt); 1808 } 1809 } 1810 1811 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) { 1812 deoptimize_frame(thread, id, Reason_constraint); 1813 } 1814 1815 // JVMTI PopFrame support 1816 JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address)) 1817 { 1818 thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address); 1819 } 1820 JRT_END 1821 1822 MethodData* 1823 Deoptimization::get_method_data(JavaThread* thread, const methodHandle& m, 1824 bool create_if_missing) { 1825 JavaThread* THREAD = thread; // For exception macros. 1826 MethodData* mdo = m()->method_data(); 1827 if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) { 1828 // Build an MDO. Ignore errors like OutOfMemory; 1829 // that simply means we won't have an MDO to update. 1830 Method::build_interpreter_method_data(m, THREAD); 1831 if (HAS_PENDING_EXCEPTION) { 1832 // Only metaspace OOM is expected. No Java code executed. 1833 assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())), "we expect only an OOM error here"); 1834 CLEAR_PENDING_EXCEPTION; 1835 } 1836 mdo = m()->method_data(); 1837 } 1838 return mdo; 1839 } 1840 1841 #if COMPILER2_OR_JVMCI 1842 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index, TRAPS) { 1843 // In case of an unresolved klass entry, load the class. 1844 // This path is exercised from case _ldc in Parse::do_one_bytecode, 1845 // and probably nowhere else. 1846 // Even that case would benefit from simply re-interpreting the 1847 // bytecode, without paying special attention to the class index. 1848 // So this whole "class index" feature should probably be removed. 1849 1850 if (constant_pool->tag_at(index).is_unresolved_klass()) { 1851 Klass* tk = constant_pool->klass_at(index, THREAD); 1852 if (HAS_PENDING_EXCEPTION) { 1853 // Exception happened during classloading. We ignore the exception here, since it 1854 // is going to be rethrown since the current activation is going to be deoptimized and 1855 // the interpreter will re-execute the bytecode. 1856 // Do not clear probable Async Exceptions. 1857 CLEAR_PENDING_NONASYNC_EXCEPTION; 1858 // Class loading called java code which may have caused a stack 1859 // overflow. If the exception was thrown right before the return 1860 // to the runtime the stack is no longer guarded. Reguard the 1861 // stack otherwise if we return to the uncommon trap blob and the 1862 // stack bang causes a stack overflow we crash. 1863 JavaThread* jt = THREAD; 1864 bool guard_pages_enabled = jt->stack_overflow_state()->reguard_stack_if_needed(); 1865 assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash"); 1866 } 1867 return; 1868 } 1869 1870 assert(!constant_pool->tag_at(index).is_symbol(), 1871 "no symbolic names here, please"); 1872 } 1873 1874 #if INCLUDE_JFR 1875 1876 class DeoptReasonSerializer : public JfrSerializer { 1877 public: 1878 void serialize(JfrCheckpointWriter& writer) { 1879 writer.write_count((u4)(Deoptimization::Reason_LIMIT + 1)); // + Reason::many (-1) 1880 for (int i = -1; i < Deoptimization::Reason_LIMIT; ++i) { 1881 writer.write_key((u8)i); 1882 writer.write(Deoptimization::trap_reason_name(i)); 1883 } 1884 } 1885 }; 1886 1887 class DeoptActionSerializer : public JfrSerializer { 1888 public: 1889 void serialize(JfrCheckpointWriter& writer) { 1890 static const u4 nof_actions = Deoptimization::Action_LIMIT; 1891 writer.write_count(nof_actions); 1892 for (u4 i = 0; i < Deoptimization::Action_LIMIT; ++i) { 1893 writer.write_key(i); 1894 writer.write(Deoptimization::trap_action_name((int)i)); 1895 } 1896 } 1897 }; 1898 1899 static void register_serializers() { 1900 static int critical_section = 0; 1901 if (1 == critical_section || Atomic::cmpxchg(&critical_section, 0, 1) == 1) { 1902 return; 1903 } 1904 JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONREASON, true, new DeoptReasonSerializer()); 1905 JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONACTION, true, new DeoptActionSerializer()); 1906 } 1907 1908 static void post_deoptimization_event(CompiledMethod* nm, 1909 const Method* method, 1910 int trap_bci, 1911 int instruction, 1912 Deoptimization::DeoptReason reason, 1913 Deoptimization::DeoptAction action) { 1914 assert(nm != NULL, "invariant"); 1915 assert(method != NULL, "invariant"); 1916 if (EventDeoptimization::is_enabled()) { 1917 static bool serializers_registered = false; 1918 if (!serializers_registered) { 1919 register_serializers(); 1920 serializers_registered = true; 1921 } 1922 EventDeoptimization event; 1923 event.set_compileId(nm->compile_id()); 1924 event.set_compiler(nm->compiler_type()); 1925 event.set_method(method); 1926 event.set_lineNumber(method->line_number_from_bci(trap_bci)); 1927 event.set_bci(trap_bci); 1928 event.set_instruction(instruction); 1929 event.set_reason(reason); 1930 event.set_action(action); 1931 event.commit(); 1932 } 1933 } 1934 1935 #endif // INCLUDE_JFR 1936 1937 JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* current, jint trap_request)) { 1938 HandleMark hm(current); 1939 1940 // uncommon_trap() is called at the beginning of the uncommon trap 1941 // handler. Note this fact before we start generating temporary frames 1942 // that can confuse an asynchronous stack walker. This counter is 1943 // decremented at the end of unpack_frames(). 1944 current->inc_in_deopt_handler(); 1945 1946 // We need to update the map if we have biased locking. 1947 #if INCLUDE_JVMCI 1948 // JVMCI might need to get an exception from the stack, which in turn requires the register map to be valid 1949 RegisterMap reg_map(current, true); 1950 #else 1951 RegisterMap reg_map(current, UseBiasedLocking); 1952 #endif 1953 frame stub_frame = current->last_frame(); 1954 frame fr = stub_frame.sender(®_map); 1955 // Make sure the calling nmethod is not getting deoptimized and removed 1956 // before we are done with it. 1957 nmethodLocker nl(fr.pc()); 1958 1959 // Log a message 1960 Events::log_deopt_message(current, "Uncommon trap: trap_request=" PTR32_FORMAT " fr.pc=" INTPTR_FORMAT " relative=" INTPTR_FORMAT, 1961 trap_request, p2i(fr.pc()), fr.pc() - fr.cb()->code_begin()); 1962 1963 { 1964 ResourceMark rm; 1965 1966 DeoptReason reason = trap_request_reason(trap_request); 1967 DeoptAction action = trap_request_action(trap_request); 1968 #if INCLUDE_JVMCI 1969 int debug_id = trap_request_debug_id(trap_request); 1970 #endif 1971 jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1 1972 1973 vframe* vf = vframe::new_vframe(&fr, ®_map, current); 1974 compiledVFrame* cvf = compiledVFrame::cast(vf); 1975 1976 CompiledMethod* nm = cvf->code(); 1977 1978 ScopeDesc* trap_scope = cvf->scope(); 1979 1980 bool is_receiver_constraint_failure = COMPILER2_PRESENT(VerifyReceiverTypes &&) (reason == Deoptimization::Reason_receiver_constraint); 1981 1982 if (TraceDeoptimization || is_receiver_constraint_failure) { 1983 ttyLocker ttyl; 1984 tty->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() 1985 #if INCLUDE_JVMCI 1986 , debug_id 1987 #endif 1988 ); 1989 } 1990 1991 methodHandle trap_method(current, trap_scope->method()); 1992 int trap_bci = trap_scope->bci(); 1993 #if INCLUDE_JVMCI 1994 jlong speculation = current->pending_failed_speculation(); 1995 if (nm->is_compiled_by_jvmci()) { 1996 nm->as_nmethod()->update_speculation(current); 1997 } else { 1998 assert(speculation == 0, "There should not be a speculation for methods compiled by non-JVMCI compilers"); 1999 } 2000 2001 if (trap_bci == SynchronizationEntryBCI) { 2002 trap_bci = 0; 2003 current->set_pending_monitorenter(true); 2004 } 2005 2006 if (reason == Deoptimization::Reason_transfer_to_interpreter) { 2007 current->set_pending_transfer_to_interpreter(true); 2008 } 2009 #endif 2010 2011 Bytecodes::Code trap_bc = trap_method->java_code_at(trap_bci); 2012 // Record this event in the histogram. 2013 gather_statistics(reason, action, trap_bc); 2014 2015 // Ensure that we can record deopt. history: 2016 // Need MDO to record RTM code generation state. 2017 bool create_if_missing = ProfileTraps || UseCodeAging RTM_OPT_ONLY( || UseRTMLocking ); 2018 2019 methodHandle profiled_method; 2020 #if INCLUDE_JVMCI 2021 if (nm->is_compiled_by_jvmci()) { 2022 profiled_method = methodHandle(current, nm->method()); 2023 } else { 2024 profiled_method = trap_method; 2025 } 2026 #else 2027 profiled_method = trap_method; 2028 #endif 2029 2030 MethodData* trap_mdo = 2031 get_method_data(current, profiled_method, create_if_missing); 2032 2033 JFR_ONLY(post_deoptimization_event(nm, trap_method(), trap_bci, trap_bc, reason, action);) 2034 2035 // Log a message 2036 Events::log_deopt_message(current, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d %s", 2037 trap_reason_name(reason), trap_action_name(action), p2i(fr.pc()), 2038 trap_method->name_and_sig_as_C_string(), trap_bci, nm->compiler_name()); 2039 2040 // Print a bunch of diagnostics, if requested. 2041 if (TraceDeoptimization || LogCompilation || is_receiver_constraint_failure) { 2042 ResourceMark rm; 2043 ttyLocker ttyl; 2044 char buf[100]; 2045 if (xtty != NULL) { 2046 xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT "' %s", 2047 os::current_thread_id(), 2048 format_trap_request(buf, sizeof(buf), trap_request)); 2049 #if INCLUDE_JVMCI 2050 if (speculation != 0) { 2051 xtty->print(" speculation='" JLONG_FORMAT "'", speculation); 2052 } 2053 #endif 2054 nm->log_identity(xtty); 2055 } 2056 Symbol* class_name = NULL; 2057 bool unresolved = false; 2058 if (unloaded_class_index >= 0) { 2059 constantPoolHandle constants (current, trap_method->constants()); 2060 if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) { 2061 class_name = constants->klass_name_at(unloaded_class_index); 2062 unresolved = true; 2063 if (xtty != NULL) 2064 xtty->print(" unresolved='1'"); 2065 } else if (constants->tag_at(unloaded_class_index).is_symbol()) { 2066 class_name = constants->symbol_at(unloaded_class_index); 2067 } 2068 if (xtty != NULL) 2069 xtty->name(class_name); 2070 } 2071 if (xtty != NULL && trap_mdo != NULL && (int)reason < (int)MethodData::_trap_hist_limit) { 2072 // Dump the relevant MDO state. 2073 // This is the deopt count for the current reason, any previous 2074 // reasons or recompiles seen at this point. 2075 int dcnt = trap_mdo->trap_count(reason); 2076 if (dcnt != 0) 2077 xtty->print(" count='%d'", dcnt); 2078 ProfileData* pdata = trap_mdo->bci_to_data(trap_bci); 2079 int dos = (pdata == NULL)? 0: pdata->trap_state(); 2080 if (dos != 0) { 2081 xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos)); 2082 if (trap_state_is_recompiled(dos)) { 2083 int recnt2 = trap_mdo->overflow_recompile_count(); 2084 if (recnt2 != 0) 2085 xtty->print(" recompiles2='%d'", recnt2); 2086 } 2087 } 2088 } 2089 if (xtty != NULL) { 2090 xtty->stamp(); 2091 xtty->end_head(); 2092 } 2093 if (TraceDeoptimization) { // make noise on the tty 2094 tty->print("Uncommon trap occurred in"); 2095 nm->method()->print_short_name(tty); 2096 tty->print(" compiler=%s compile_id=%d", nm->compiler_name(), nm->compile_id()); 2097 #if INCLUDE_JVMCI 2098 if (nm->is_nmethod()) { 2099 const char* installed_code_name = nm->as_nmethod()->jvmci_name(); 2100 if (installed_code_name != NULL) { 2101 tty->print(" (JVMCI: installed code name=%s) ", installed_code_name); 2102 } 2103 } 2104 #endif 2105 tty->print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d" JVMCI_ONLY(" debug_id=%d"), 2106 p2i(fr.pc()), 2107 os::current_thread_id(), 2108 trap_reason_name(reason), 2109 trap_action_name(action), 2110 unloaded_class_index 2111 #if INCLUDE_JVMCI 2112 , debug_id 2113 #endif 2114 ); 2115 if (class_name != NULL) { 2116 tty->print(unresolved ? " unresolved class: " : " symbol: "); 2117 class_name->print_symbol_on(tty); 2118 } 2119 tty->cr(); 2120 } 2121 if (xtty != NULL) { 2122 // Log the precise location of the trap. 2123 for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) { 2124 xtty->begin_elem("jvms bci='%d'", sd->bci()); 2125 xtty->method(sd->method()); 2126 xtty->end_elem(); 2127 if (sd->is_top()) break; 2128 } 2129 xtty->tail("uncommon_trap"); 2130 } 2131 } 2132 // (End diagnostic printout.) 2133 2134 if (is_receiver_constraint_failure) { 2135 fatal("missing receiver type check"); 2136 } 2137 2138 // Load class if necessary 2139 if (unloaded_class_index >= 0) { 2140 constantPoolHandle constants(current, trap_method->constants()); 2141 load_class_by_index(constants, unloaded_class_index, THREAD); 2142 } 2143 2144 // Flush the nmethod if necessary and desirable. 2145 // 2146 // We need to avoid situations where we are re-flushing the nmethod 2147 // because of a hot deoptimization site. Repeated flushes at the same 2148 // point need to be detected by the compiler and avoided. If the compiler 2149 // cannot avoid them (or has a bug and "refuses" to avoid them), this 2150 // module must take measures to avoid an infinite cycle of recompilation 2151 // and deoptimization. There are several such measures: 2152 // 2153 // 1. If a recompilation is ordered a second time at some site X 2154 // and for the same reason R, the action is adjusted to 'reinterpret', 2155 // to give the interpreter time to exercise the method more thoroughly. 2156 // If this happens, the method's overflow_recompile_count is incremented. 2157 // 2158 // 2. If the compiler fails to reduce the deoptimization rate, then 2159 // the method's overflow_recompile_count will begin to exceed the set 2160 // limit PerBytecodeRecompilationCutoff. If this happens, the action 2161 // is adjusted to 'make_not_compilable', and the method is abandoned 2162 // to the interpreter. This is a performance hit for hot methods, 2163 // but is better than a disastrous infinite cycle of recompilations. 2164 // (Actually, only the method containing the site X is abandoned.) 2165 // 2166 // 3. In parallel with the previous measures, if the total number of 2167 // recompilations of a method exceeds the much larger set limit 2168 // PerMethodRecompilationCutoff, the method is abandoned. 2169 // This should only happen if the method is very large and has 2170 // many "lukewarm" deoptimizations. The code which enforces this 2171 // limit is elsewhere (class nmethod, class Method). 2172 // 2173 // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance 2174 // to recompile at each bytecode independently of the per-BCI cutoff. 2175 // 2176 // The decision to update code is up to the compiler, and is encoded 2177 // in the Action_xxx code. If the compiler requests Action_none 2178 // no trap state is changed, no compiled code is changed, and the 2179 // computation suffers along in the interpreter. 2180 // 2181 // The other action codes specify various tactics for decompilation 2182 // and recompilation. Action_maybe_recompile is the loosest, and 2183 // allows the compiled code to stay around until enough traps are seen, 2184 // and until the compiler gets around to recompiling the trapping method. 2185 // 2186 // The other actions cause immediate removal of the present code. 2187 2188 // Traps caused by injected profile shouldn't pollute trap counts. 2189 bool injected_profile_trap = trap_method->has_injected_profile() && 2190 (reason == Reason_intrinsic || reason == Reason_unreached); 2191 2192 bool update_trap_state = (reason != Reason_tenured) && !injected_profile_trap; 2193 bool make_not_entrant = false; 2194 bool make_not_compilable = false; 2195 bool reprofile = false; 2196 switch (action) { 2197 case Action_none: 2198 // Keep the old code. 2199 update_trap_state = false; 2200 break; 2201 case Action_maybe_recompile: 2202 // Do not need to invalidate the present code, but we can 2203 // initiate another 2204 // Start compiler without (necessarily) invalidating the nmethod. 2205 // The system will tolerate the old code, but new code should be 2206 // generated when possible. 2207 break; 2208 case Action_reinterpret: 2209 // Go back into the interpreter for a while, and then consider 2210 // recompiling form scratch. 2211 make_not_entrant = true; 2212 // Reset invocation counter for outer most method. 2213 // This will allow the interpreter to exercise the bytecodes 2214 // for a while before recompiling. 2215 // By contrast, Action_make_not_entrant is immediate. 2216 // 2217 // Note that the compiler will track null_check, null_assert, 2218 // range_check, and class_check events and log them as if they 2219 // had been traps taken from compiled code. This will update 2220 // the MDO trap history so that the next compilation will 2221 // properly detect hot trap sites. 2222 reprofile = true; 2223 break; 2224 case Action_make_not_entrant: 2225 // Request immediate recompilation, and get rid of the old code. 2226 // Make them not entrant, so next time they are called they get 2227 // recompiled. Unloaded classes are loaded now so recompile before next 2228 // time they are called. Same for uninitialized. The interpreter will 2229 // link the missing class, if any. 2230 make_not_entrant = true; 2231 break; 2232 case Action_make_not_compilable: 2233 // Give up on compiling this method at all. 2234 make_not_entrant = true; 2235 make_not_compilable = true; 2236 break; 2237 default: 2238 ShouldNotReachHere(); 2239 } 2240 2241 // Setting +ProfileTraps fixes the following, on all platforms: 2242 // 4852688: ProfileInterpreter is off by default for ia64. The result is 2243 // infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the 2244 // recompile relies on a MethodData* to record heroic opt failures. 2245 2246 // Whether the interpreter is producing MDO data or not, we also need 2247 // to use the MDO to detect hot deoptimization points and control 2248 // aggressive optimization. 2249 bool inc_recompile_count = false; 2250 ProfileData* pdata = NULL; 2251 if (ProfileTraps && CompilerConfig::is_c2_or_jvmci_compiler_enabled() && update_trap_state && trap_mdo != NULL) { 2252 assert(trap_mdo == get_method_data(current, profiled_method, false), "sanity"); 2253 uint this_trap_count = 0; 2254 bool maybe_prior_trap = false; 2255 bool maybe_prior_recompile = false; 2256 pdata = query_update_method_data(trap_mdo, trap_bci, reason, true, 2257 #if INCLUDE_JVMCI 2258 nm->is_compiled_by_jvmci() && nm->is_osr_method(), 2259 #endif 2260 nm->method(), 2261 //outputs: 2262 this_trap_count, 2263 maybe_prior_trap, 2264 maybe_prior_recompile); 2265 // Because the interpreter also counts null, div0, range, and class 2266 // checks, these traps from compiled code are double-counted. 2267 // This is harmless; it just means that the PerXTrapLimit values 2268 // are in effect a little smaller than they look. 2269 2270 DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason); 2271 if (per_bc_reason != Reason_none) { 2272 // Now take action based on the partially known per-BCI history. 2273 if (maybe_prior_trap 2274 && this_trap_count >= (uint)PerBytecodeTrapLimit) { 2275 // If there are too many traps at this BCI, force a recompile. 2276 // This will allow the compiler to see the limit overflow, and 2277 // take corrective action, if possible. The compiler generally 2278 // does not use the exact PerBytecodeTrapLimit value, but instead 2279 // changes its tactics if it sees any traps at all. This provides 2280 // a little hysteresis, delaying a recompile until a trap happens 2281 // several times. 2282 // 2283 // Actually, since there is only one bit of counter per BCI, 2284 // the possible per-BCI counts are {0,1,(per-method count)}. 2285 // This produces accurate results if in fact there is only 2286 // one hot trap site, but begins to get fuzzy if there are 2287 // many sites. For example, if there are ten sites each 2288 // trapping two or more times, they each get the blame for 2289 // all of their traps. 2290 make_not_entrant = true; 2291 } 2292 2293 // Detect repeated recompilation at the same BCI, and enforce a limit. 2294 if (make_not_entrant && maybe_prior_recompile) { 2295 // More than one recompile at this point. 2296 inc_recompile_count = maybe_prior_trap; 2297 } 2298 } else { 2299 // For reasons which are not recorded per-bytecode, we simply 2300 // force recompiles unconditionally. 2301 // (Note that PerMethodRecompilationCutoff is enforced elsewhere.) 2302 make_not_entrant = true; 2303 } 2304 2305 // Go back to the compiler if there are too many traps in this method. 2306 if (this_trap_count >= per_method_trap_limit(reason)) { 2307 // If there are too many traps in this method, force a recompile. 2308 // This will allow the compiler to see the limit overflow, and 2309 // take corrective action, if possible. 2310 // (This condition is an unlikely backstop only, because the 2311 // PerBytecodeTrapLimit is more likely to take effect first, 2312 // if it is applicable.) 2313 make_not_entrant = true; 2314 } 2315 2316 // Here's more hysteresis: If there has been a recompile at 2317 // this trap point already, run the method in the interpreter 2318 // for a while to exercise it more thoroughly. 2319 if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) { 2320 reprofile = true; 2321 } 2322 } 2323 2324 // Take requested actions on the method: 2325 2326 // Recompile 2327 if (make_not_entrant) { 2328 if (!nm->make_not_entrant()) { 2329 return; // the call did not change nmethod's state 2330 } 2331 2332 if (pdata != NULL) { 2333 // Record the recompilation event, if any. 2334 int tstate0 = pdata->trap_state(); 2335 int tstate1 = trap_state_set_recompiled(tstate0, true); 2336 if (tstate1 != tstate0) 2337 pdata->set_trap_state(tstate1); 2338 } 2339 2340 #if INCLUDE_RTM_OPT 2341 // Restart collecting RTM locking abort statistic if the method 2342 // is recompiled for a reason other than RTM state change. 2343 // Assume that in new recompiled code the statistic could be different, 2344 // for example, due to different inlining. 2345 if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) && 2346 UseRTMDeopt && (nm->as_nmethod()->rtm_state() != ProfileRTM)) { 2347 trap_mdo->atomic_set_rtm_state(ProfileRTM); 2348 } 2349 #endif 2350 // For code aging we count traps separately here, using make_not_entrant() 2351 // as a guard against simultaneous deopts in multiple threads. 2352 if (reason == Reason_tenured && trap_mdo != NULL) { 2353 trap_mdo->inc_tenure_traps(); 2354 } 2355 } 2356 2357 if (inc_recompile_count) { 2358 trap_mdo->inc_overflow_recompile_count(); 2359 if ((uint)trap_mdo->overflow_recompile_count() > 2360 (uint)PerBytecodeRecompilationCutoff) { 2361 // Give up on the method containing the bad BCI. 2362 if (trap_method() == nm->method()) { 2363 make_not_compilable = true; 2364 } else { 2365 trap_method->set_not_compilable("overflow_recompile_count > PerBytecodeRecompilationCutoff", CompLevel_full_optimization); 2366 // But give grace to the enclosing nm->method(). 2367 } 2368 } 2369 } 2370 2371 // Reprofile 2372 if (reprofile) { 2373 CompilationPolicy::reprofile(trap_scope, nm->is_osr_method()); 2374 } 2375 2376 // Give up compiling 2377 if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) { 2378 assert(make_not_entrant, "consistent"); 2379 nm->method()->set_not_compilable("give up compiling", CompLevel_full_optimization); 2380 } 2381 2382 } // Free marked resources 2383 2384 } 2385 JRT_END 2386 2387 ProfileData* 2388 Deoptimization::query_update_method_data(MethodData* trap_mdo, 2389 int trap_bci, 2390 Deoptimization::DeoptReason reason, 2391 bool update_total_trap_count, 2392 #if INCLUDE_JVMCI 2393 bool is_osr, 2394 #endif 2395 Method* compiled_method, 2396 //outputs: 2397 uint& ret_this_trap_count, 2398 bool& ret_maybe_prior_trap, 2399 bool& ret_maybe_prior_recompile) { 2400 bool maybe_prior_trap = false; 2401 bool maybe_prior_recompile = false; 2402 uint this_trap_count = 0; 2403 if (update_total_trap_count) { 2404 uint idx = reason; 2405 #if INCLUDE_JVMCI 2406 if (is_osr) { 2407 // Upper half of history array used for traps in OSR compilations 2408 idx += Reason_TRAP_HISTORY_LENGTH; 2409 } 2410 #endif 2411 uint prior_trap_count = trap_mdo->trap_count(idx); 2412 this_trap_count = trap_mdo->inc_trap_count(idx); 2413 2414 // If the runtime cannot find a place to store trap history, 2415 // it is estimated based on the general condition of the method. 2416 // If the method has ever been recompiled, or has ever incurred 2417 // a trap with the present reason , then this BCI is assumed 2418 // (pessimistically) to be the culprit. 2419 maybe_prior_trap = (prior_trap_count != 0); 2420 maybe_prior_recompile = (trap_mdo->decompile_count() != 0); 2421 } 2422 ProfileData* pdata = NULL; 2423 2424 2425 // For reasons which are recorded per bytecode, we check per-BCI data. 2426 DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason); 2427 assert(per_bc_reason != Reason_none || update_total_trap_count, "must be"); 2428 if (per_bc_reason != Reason_none) { 2429 // Find the profile data for this BCI. If there isn't one, 2430 // try to allocate one from the MDO's set of spares. 2431 // This will let us detect a repeated trap at this point. 2432 pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL); 2433 2434 if (pdata != NULL) { 2435 if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) { 2436 if (LogCompilation && xtty != NULL) { 2437 ttyLocker ttyl; 2438 // no more room for speculative traps in this MDO 2439 xtty->elem("speculative_traps_oom"); 2440 } 2441 } 2442 // Query the trap state of this profile datum. 2443 int tstate0 = pdata->trap_state(); 2444 if (!trap_state_has_reason(tstate0, per_bc_reason)) 2445 maybe_prior_trap = false; 2446 if (!trap_state_is_recompiled(tstate0)) 2447 maybe_prior_recompile = false; 2448 2449 // Update the trap state of this profile datum. 2450 int tstate1 = tstate0; 2451 // Record the reason. 2452 tstate1 = trap_state_add_reason(tstate1, per_bc_reason); 2453 // Store the updated state on the MDO, for next time. 2454 if (tstate1 != tstate0) 2455 pdata->set_trap_state(tstate1); 2456 } else { 2457 if (LogCompilation && xtty != NULL) { 2458 ttyLocker ttyl; 2459 // Missing MDP? Leave a small complaint in the log. 2460 xtty->elem("missing_mdp bci='%d'", trap_bci); 2461 } 2462 } 2463 } 2464 2465 // Return results: 2466 ret_this_trap_count = this_trap_count; 2467 ret_maybe_prior_trap = maybe_prior_trap; 2468 ret_maybe_prior_recompile = maybe_prior_recompile; 2469 return pdata; 2470 } 2471 2472 void 2473 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) { 2474 ResourceMark rm; 2475 // Ignored outputs: 2476 uint ignore_this_trap_count; 2477 bool ignore_maybe_prior_trap; 2478 bool ignore_maybe_prior_recompile; 2479 assert(!reason_is_speculate(reason), "reason speculate only used by compiler"); 2480 // JVMCI uses the total counts to determine if deoptimizations are happening too frequently -> do not adjust total counts 2481 bool update_total_counts = true JVMCI_ONLY( && !UseJVMCICompiler); 2482 query_update_method_data(trap_mdo, trap_bci, 2483 (DeoptReason)reason, 2484 update_total_counts, 2485 #if INCLUDE_JVMCI 2486 false, 2487 #endif 2488 NULL, 2489 ignore_this_trap_count, 2490 ignore_maybe_prior_trap, 2491 ignore_maybe_prior_recompile); 2492 } 2493 2494 Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* current, jint trap_request, jint exec_mode) { 2495 // Enable WXWrite: current function is called from methods compiled by C2 directly 2496 MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current)); 2497 2498 if (TraceDeoptimization) { 2499 tty->print("Uncommon trap "); 2500 } 2501 // Still in Java no safepoints 2502 { 2503 // This enters VM and may safepoint 2504 uncommon_trap_inner(current, trap_request); 2505 } 2506 HandleMark hm(current); 2507 return fetch_unroll_info_helper(current, exec_mode); 2508 } 2509 2510 // Local derived constants. 2511 // Further breakdown of DataLayout::trap_state, as promised by DataLayout. 2512 const int DS_REASON_MASK = ((uint)DataLayout::trap_mask) >> 1; 2513 const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK; 2514 2515 //---------------------------trap_state_reason--------------------------------- 2516 Deoptimization::DeoptReason 2517 Deoptimization::trap_state_reason(int trap_state) { 2518 // This assert provides the link between the width of DataLayout::trap_bits 2519 // and the encoding of "recorded" reasons. It ensures there are enough 2520 // bits to store all needed reasons in the per-BCI MDO profile. 2521 assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits"); 2522 int recompile_bit = (trap_state & DS_RECOMPILE_BIT); 2523 trap_state -= recompile_bit; 2524 if (trap_state == DS_REASON_MASK) { 2525 return Reason_many; 2526 } else { 2527 assert((int)Reason_none == 0, "state=0 => Reason_none"); 2528 return (DeoptReason)trap_state; 2529 } 2530 } 2531 //-------------------------trap_state_has_reason------------------------------- 2532 int Deoptimization::trap_state_has_reason(int trap_state, int reason) { 2533 assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason"); 2534 assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits"); 2535 int recompile_bit = (trap_state & DS_RECOMPILE_BIT); 2536 trap_state -= recompile_bit; 2537 if (trap_state == DS_REASON_MASK) { 2538 return -1; // true, unspecifically (bottom of state lattice) 2539 } else if (trap_state == reason) { 2540 return 1; // true, definitely 2541 } else if (trap_state == 0) { 2542 return 0; // false, definitely (top of state lattice) 2543 } else { 2544 return 0; // false, definitely 2545 } 2546 } 2547 //-------------------------trap_state_add_reason------------------------------- 2548 int Deoptimization::trap_state_add_reason(int trap_state, int reason) { 2549 assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason"); 2550 int recompile_bit = (trap_state & DS_RECOMPILE_BIT); 2551 trap_state -= recompile_bit; 2552 if (trap_state == DS_REASON_MASK) { 2553 return trap_state + recompile_bit; // already at state lattice bottom 2554 } else if (trap_state == reason) { 2555 return trap_state + recompile_bit; // the condition is already true 2556 } else if (trap_state == 0) { 2557 return reason + recompile_bit; // no condition has yet been true 2558 } else { 2559 return DS_REASON_MASK + recompile_bit; // fall to state lattice bottom 2560 } 2561 } 2562 //-----------------------trap_state_is_recompiled------------------------------ 2563 bool Deoptimization::trap_state_is_recompiled(int trap_state) { 2564 return (trap_state & DS_RECOMPILE_BIT) != 0; 2565 } 2566 //-----------------------trap_state_set_recompiled----------------------------- 2567 int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) { 2568 if (z) return trap_state | DS_RECOMPILE_BIT; 2569 else return trap_state & ~DS_RECOMPILE_BIT; 2570 } 2571 //---------------------------format_trap_state--------------------------------- 2572 // This is used for debugging and diagnostics, including LogFile output. 2573 const char* Deoptimization::format_trap_state(char* buf, size_t buflen, 2574 int trap_state) { 2575 assert(buflen > 0, "sanity"); 2576 DeoptReason reason = trap_state_reason(trap_state); 2577 bool recomp_flag = trap_state_is_recompiled(trap_state); 2578 // Re-encode the state from its decoded components. 2579 int decoded_state = 0; 2580 if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many) 2581 decoded_state = trap_state_add_reason(decoded_state, reason); 2582 if (recomp_flag) 2583 decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag); 2584 // If the state re-encodes properly, format it symbolically. 2585 // Because this routine is used for debugging and diagnostics, 2586 // be robust even if the state is a strange value. 2587 size_t len; 2588 if (decoded_state != trap_state) { 2589 // Random buggy state that doesn't decode?? 2590 len = jio_snprintf(buf, buflen, "#%d", trap_state); 2591 } else { 2592 len = jio_snprintf(buf, buflen, "%s%s", 2593 trap_reason_name(reason), 2594 recomp_flag ? " recompiled" : ""); 2595 } 2596 return buf; 2597 } 2598 2599 2600 //--------------------------------statics-------------------------------------- 2601 const char* Deoptimization::_trap_reason_name[] = { 2602 // Note: Keep this in sync. with enum DeoptReason. 2603 "none", 2604 "null_check", 2605 "null_assert" JVMCI_ONLY("_or_unreached0"), 2606 "range_check", 2607 "class_check", 2608 "array_check", 2609 "intrinsic" JVMCI_ONLY("_or_type_checked_inlining"), 2610 "bimorphic" JVMCI_ONLY("_or_optimized_type_check"), 2611 "profile_predicate", 2612 "unloaded", 2613 "uninitialized", 2614 "initialized", 2615 "unreached", 2616 "unhandled", 2617 "constraint", 2618 "div0_check", 2619 "age", 2620 "predicate", 2621 "loop_limit_check", 2622 "speculate_class_check", 2623 "speculate_null_check", 2624 "speculate_null_assert", 2625 "rtm_state_change", 2626 "unstable_if", 2627 "unstable_fused_if", 2628 "receiver_constraint", 2629 #if INCLUDE_JVMCI 2630 "aliasing", 2631 "transfer_to_interpreter", 2632 "not_compiled_exception_handler", 2633 "unresolved", 2634 "jsr_mismatch", 2635 #endif 2636 "tenured" 2637 }; 2638 const char* Deoptimization::_trap_action_name[] = { 2639 // Note: Keep this in sync. with enum DeoptAction. 2640 "none", 2641 "maybe_recompile", 2642 "reinterpret", 2643 "make_not_entrant", 2644 "make_not_compilable" 2645 }; 2646 2647 const char* Deoptimization::trap_reason_name(int reason) { 2648 // Check that every reason has a name 2649 STATIC_ASSERT(sizeof(_trap_reason_name)/sizeof(const char*) == Reason_LIMIT); 2650 2651 if (reason == Reason_many) return "many"; 2652 if ((uint)reason < Reason_LIMIT) 2653 return _trap_reason_name[reason]; 2654 static char buf[20]; 2655 sprintf(buf, "reason%d", reason); 2656 return buf; 2657 } 2658 const char* Deoptimization::trap_action_name(int action) { 2659 // Check that every action has a name 2660 STATIC_ASSERT(sizeof(_trap_action_name)/sizeof(const char*) == Action_LIMIT); 2661 2662 if ((uint)action < Action_LIMIT) 2663 return _trap_action_name[action]; 2664 static char buf[20]; 2665 sprintf(buf, "action%d", action); 2666 return buf; 2667 } 2668 2669 // This is used for debugging and diagnostics, including LogFile output. 2670 const char* Deoptimization::format_trap_request(char* buf, size_t buflen, 2671 int trap_request) { 2672 jint unloaded_class_index = trap_request_index(trap_request); 2673 const char* reason = trap_reason_name(trap_request_reason(trap_request)); 2674 const char* action = trap_action_name(trap_request_action(trap_request)); 2675 #if INCLUDE_JVMCI 2676 int debug_id = trap_request_debug_id(trap_request); 2677 #endif 2678 size_t len; 2679 if (unloaded_class_index < 0) { 2680 len = jio_snprintf(buf, buflen, "reason='%s' action='%s'" JVMCI_ONLY(" debug_id='%d'"), 2681 reason, action 2682 #if INCLUDE_JVMCI 2683 ,debug_id 2684 #endif 2685 ); 2686 } else { 2687 len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'" JVMCI_ONLY(" debug_id='%d'"), 2688 reason, action, unloaded_class_index 2689 #if INCLUDE_JVMCI 2690 ,debug_id 2691 #endif 2692 ); 2693 } 2694 return buf; 2695 } 2696 2697 juint Deoptimization::_deoptimization_hist 2698 [Deoptimization::Reason_LIMIT] 2699 [1 + Deoptimization::Action_LIMIT] 2700 [Deoptimization::BC_CASE_LIMIT] 2701 = {0}; 2702 2703 enum { 2704 LSB_BITS = 8, 2705 LSB_MASK = right_n_bits(LSB_BITS) 2706 }; 2707 2708 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action, 2709 Bytecodes::Code bc) { 2710 assert(reason >= 0 && reason < Reason_LIMIT, "oob"); 2711 assert(action >= 0 && action < Action_LIMIT, "oob"); 2712 _deoptimization_hist[Reason_none][0][0] += 1; // total 2713 _deoptimization_hist[reason][0][0] += 1; // per-reason total 2714 juint* cases = _deoptimization_hist[reason][1+action]; 2715 juint* bc_counter_addr = NULL; 2716 juint bc_counter = 0; 2717 // Look for an unused counter, or an exact match to this BC. 2718 if (bc != Bytecodes::_illegal) { 2719 for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) { 2720 juint* counter_addr = &cases[bc_case]; 2721 juint counter = *counter_addr; 2722 if ((counter == 0 && bc_counter_addr == NULL) 2723 || (Bytecodes::Code)(counter & LSB_MASK) == bc) { 2724 // this counter is either free or is already devoted to this BC 2725 bc_counter_addr = counter_addr; 2726 bc_counter = counter | bc; 2727 } 2728 } 2729 } 2730 if (bc_counter_addr == NULL) { 2731 // Overflow, or no given bytecode. 2732 bc_counter_addr = &cases[BC_CASE_LIMIT-1]; 2733 bc_counter = (*bc_counter_addr & ~LSB_MASK); // clear LSB 2734 } 2735 *bc_counter_addr = bc_counter + (1 << LSB_BITS); 2736 } 2737 2738 jint Deoptimization::total_deoptimization_count() { 2739 return _deoptimization_hist[Reason_none][0][0]; 2740 } 2741 2742 void Deoptimization::print_statistics() { 2743 juint total = total_deoptimization_count(); 2744 juint account = total; 2745 if (total != 0) { 2746 ttyLocker ttyl; 2747 if (xtty != NULL) xtty->head("statistics type='deoptimization'"); 2748 tty->print_cr("Deoptimization traps recorded:"); 2749 #define PRINT_STAT_LINE(name, r) \ 2750 tty->print_cr(" %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name); 2751 PRINT_STAT_LINE("total", total); 2752 // For each non-zero entry in the histogram, print the reason, 2753 // the action, and (if specifically known) the type of bytecode. 2754 for (int reason = 0; reason < Reason_LIMIT; reason++) { 2755 for (int action = 0; action < Action_LIMIT; action++) { 2756 juint* cases = _deoptimization_hist[reason][1+action]; 2757 for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) { 2758 juint counter = cases[bc_case]; 2759 if (counter != 0) { 2760 char name[1*K]; 2761 Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK); 2762 if (bc_case == BC_CASE_LIMIT && (int)bc == 0) 2763 bc = Bytecodes::_illegal; 2764 sprintf(name, "%s/%s/%s", 2765 trap_reason_name(reason), 2766 trap_action_name(action), 2767 Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other"); 2768 juint r = counter >> LSB_BITS; 2769 tty->print_cr(" %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total); 2770 account -= r; 2771 } 2772 } 2773 } 2774 } 2775 if (account != 0) { 2776 PRINT_STAT_LINE("unaccounted", account); 2777 } 2778 #undef PRINT_STAT_LINE 2779 if (xtty != NULL) xtty->tail("statistics"); 2780 } 2781 } 2782 2783 #else // COMPILER2_OR_JVMCI 2784 2785 2786 // Stubs for C1 only system. 2787 bool Deoptimization::trap_state_is_recompiled(int trap_state) { 2788 return false; 2789 } 2790 2791 const char* Deoptimization::trap_reason_name(int reason) { 2792 return "unknown"; 2793 } 2794 2795 void Deoptimization::print_statistics() { 2796 // no output 2797 } 2798 2799 void 2800 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) { 2801 // no udpate 2802 } 2803 2804 int Deoptimization::trap_state_has_reason(int trap_state, int reason) { 2805 return 0; 2806 } 2807 2808 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action, 2809 Bytecodes::Code bc) { 2810 // no update 2811 } 2812 2813 const char* Deoptimization::format_trap_state(char* buf, size_t buflen, 2814 int trap_state) { 2815 jio_snprintf(buf, buflen, "#%d", trap_state); 2816 return buf; 2817 } 2818 2819 #endif // COMPILER2_OR_JVMCI