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