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