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