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