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