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