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