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