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