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