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