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