Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-aarch32-jdk8u
Path: blob/jdk8u272-b10-aarch32-20201026/hotspot/src/share/vm/runtime/deoptimization.cpp
48785 views
1
/*
2
* Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*
23
*/
24
25
#include "precompiled.hpp"
26
#include "classfile/systemDictionary.hpp"
27
#include "code/debugInfoRec.hpp"
28
#include "code/nmethod.hpp"
29
#include "code/pcDesc.hpp"
30
#include "code/scopeDesc.hpp"
31
#include "interpreter/bytecode.hpp"
32
#include "interpreter/interpreter.hpp"
33
#include "interpreter/oopMapCache.hpp"
34
#include "memory/allocation.inline.hpp"
35
#include "memory/oopFactory.hpp"
36
#include "memory/resourceArea.hpp"
37
#include "oops/method.hpp"
38
#include "oops/oop.inline.hpp"
39
#include "prims/jvmtiThreadState.hpp"
40
#include "runtime/biasedLocking.hpp"
41
#include "runtime/compilationPolicy.hpp"
42
#include "runtime/deoptimization.hpp"
43
#include "runtime/interfaceSupport.hpp"
44
#include "runtime/sharedRuntime.hpp"
45
#include "runtime/signature.hpp"
46
#include "runtime/stubRoutines.hpp"
47
#include "runtime/thread.hpp"
48
#include "runtime/vframe.hpp"
49
#include "runtime/vframeArray.hpp"
50
#include "runtime/vframe_hp.hpp"
51
#include "utilities/events.hpp"
52
#include "utilities/xmlstream.hpp"
53
#ifdef TARGET_ARCH_x86
54
# include "vmreg_x86.inline.hpp"
55
#endif
56
#ifdef TARGET_ARCH_aarch64
57
# include "vmreg_aarch64.inline.hpp"
58
#endif
59
#ifdef TARGET_ARCH_sparc
60
# include "vmreg_sparc.inline.hpp"
61
#endif
62
#ifdef TARGET_ARCH_zero
63
# include "vmreg_zero.inline.hpp"
64
#endif
65
#ifdef TARGET_ARCH_arm
66
# include "vmreg_arm.inline.hpp"
67
#endif
68
#ifdef TARGET_ARCH_ppc
69
# include "vmreg_ppc.inline.hpp"
70
#endif
71
#ifdef TARGET_ARCH_aarch32
72
# include "vmreg_aarch32.inline.hpp"
73
#endif
74
#ifdef COMPILER2
75
#if defined AD_MD_HPP
76
# include AD_MD_HPP
77
#elif defined TARGET_ARCH_MODEL_x86_32
78
# include "adfiles/ad_x86_32.hpp"
79
#elif defined TARGET_ARCH_MODEL_x86_64
80
# include "adfiles/ad_x86_64.hpp"
81
#elif defined TARGET_ARCH_MODEL_aarch64
82
# include "adfiles/ad_aarch64.hpp"
83
#elif defined TARGET_ARCH_MODEL_sparc
84
# include "adfiles/ad_sparc.hpp"
85
#elif defined TARGET_ARCH_MODEL_zero
86
# include "adfiles/ad_zero.hpp"
87
#elif defined TARGET_ARCH_MODEL_ppc_64
88
# include "adfiles/ad_ppc_64.hpp"
89
#elif defined TARGET_ARCH_MODEL_aarch32
90
# include "adfiles/ad_aarch32.hpp"
91
#endif
92
#endif // COMPILER2
93
94
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
95
96
bool DeoptimizationMarker::_is_active = false;
97
98
Deoptimization::UnrollBlock::UnrollBlock(int size_of_deoptimized_frame,
99
int caller_adjustment,
100
int caller_actual_parameters,
101
int number_of_frames,
102
intptr_t* frame_sizes,
103
address* frame_pcs,
104
BasicType return_type) {
105
_size_of_deoptimized_frame = size_of_deoptimized_frame;
106
_caller_adjustment = caller_adjustment;
107
_caller_actual_parameters = caller_actual_parameters;
108
_number_of_frames = number_of_frames;
109
_frame_sizes = frame_sizes;
110
_frame_pcs = frame_pcs;
111
_register_block = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);
112
_return_type = return_type;
113
_initial_info = 0;
114
// PD (x86 only)
115
_counter_temp = 0;
116
_unpack_kind = 0;
117
_sender_sp_temp = 0;
118
119
_total_frame_sizes = size_of_frames();
120
}
121
122
123
Deoptimization::UnrollBlock::~UnrollBlock() {
124
FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes, mtCompiler);
125
FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs, mtCompiler);
126
FREE_C_HEAP_ARRAY(intptr_t, _register_block, mtCompiler);
127
}
128
129
130
intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const {
131
assert(register_number < RegisterMap::reg_count, "checking register number");
132
return &_register_block[register_number * 2];
133
}
134
135
136
137
int Deoptimization::UnrollBlock::size_of_frames() const {
138
// Acount first for the adjustment of the initial frame
139
int result = _caller_adjustment;
140
for (int index = 0; index < number_of_frames(); index++) {
141
result += frame_sizes()[index];
142
}
143
return result;
144
}
145
146
147
void Deoptimization::UnrollBlock::print() {
148
ttyLocker ttyl;
149
tty->print_cr("UnrollBlock");
150
tty->print_cr(" size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
151
tty->print( " frame_sizes: ");
152
for (int index = 0; index < number_of_frames(); index++) {
153
tty->print("%d ", frame_sizes()[index]);
154
}
155
tty->cr();
156
}
157
158
159
// In order to make fetch_unroll_info work properly with escape
160
// analysis, The method was changed from JRT_LEAF to JRT_BLOCK_ENTRY and
161
// ResetNoHandleMark and HandleMark were removed from it. The actual reallocation
162
// of previously eliminated objects occurs in realloc_objects, which is
163
// called from the method fetch_unroll_info_helper below.
164
JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* thread))
165
// It is actually ok to allocate handles in a leaf method. It causes no safepoints,
166
// but makes the entry a little slower. There is however a little dance we have to
167
// do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
168
169
// fetch_unroll_info() is called at the beginning of the deoptimization
170
// handler. Note this fact before we start generating temporary frames
171
// that can confuse an asynchronous stack walker. This counter is
172
// decremented at the end of unpack_frames().
173
thread->inc_in_deopt_handler();
174
175
return fetch_unroll_info_helper(thread);
176
JRT_END
177
178
179
// This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)
180
Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* thread) {
181
182
// Note: there is a safepoint safety issue here. No matter whether we enter
183
// via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once
184
// the vframeArray is created.
185
//
186
187
// Allocate our special deoptimization ResourceMark
188
DeoptResourceMark* dmark = new DeoptResourceMark(thread);
189
assert(thread->deopt_mark() == NULL, "Pending deopt!");
190
thread->set_deopt_mark(dmark);
191
192
frame stub_frame = thread->last_frame(); // Makes stack walkable as side effect
193
RegisterMap map(thread, true);
194
RegisterMap dummy_map(thread, false);
195
// Now get the deoptee with a valid map
196
frame deoptee = stub_frame.sender(&map);
197
// Set the deoptee nmethod
198
assert(thread->deopt_nmethod() == NULL, "Pending deopt!");
199
thread->set_deopt_nmethod(deoptee.cb()->as_nmethod_or_null());
200
201
if (VerifyStack) {
202
thread->validate_frame_layout();
203
}
204
205
// Create a growable array of VFrames where each VFrame represents an inlined
206
// Java frame. This storage is allocated with the usual system arena.
207
assert(deoptee.is_compiled_frame(), "Wrong frame type");
208
GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);
209
vframe* vf = vframe::new_vframe(&deoptee, &map, thread);
210
while (!vf->is_top()) {
211
assert(vf->is_compiled_frame(), "Wrong frame type");
212
chunk->push(compiledVFrame::cast(vf));
213
vf = vf->sender();
214
}
215
assert(vf->is_compiled_frame(), "Wrong frame type");
216
chunk->push(compiledVFrame::cast(vf));
217
218
bool realloc_failures = false;
219
220
#ifdef COMPILER2
221
// Reallocate the non-escaping objects and restore their fields. Then
222
// relock objects if synchronization on them was eliminated.
223
if (DoEscapeAnalysis || EliminateNestedLocks) {
224
if (EliminateAllocations) {
225
assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames");
226
GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects();
227
228
// The flag return_oop() indicates call sites which return oop
229
// in compiled code. Such sites include java method calls,
230
// runtime calls (for example, used to allocate new objects/arrays
231
// on slow code path) and any other calls generated in compiled code.
232
// It is not guaranteed that we can get such information here only
233
// by analyzing bytecode in deoptimized frames. This is why this flag
234
// is set during method compilation (see Compile::Process_OopMap_Node()).
235
// If the previous frame was popped, we don't have a result.
236
bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution();
237
Handle return_value;
238
if (save_oop_result) {
239
// Reallocation may trigger GC. If deoptimization happened on return from
240
// call which returns oop we need to save it since it is not in oopmap.
241
oop result = deoptee.saved_oop_result(&map);
242
assert(result == NULL || result->is_oop(), "must be oop");
243
return_value = Handle(thread, result);
244
assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
245
if (TraceDeoptimization) {
246
ttyLocker ttyl;
247
tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, (void *)result, thread);
248
}
249
}
250
if (objects != NULL) {
251
JRT_BLOCK
252
realloc_failures = realloc_objects(thread, &deoptee, objects, THREAD);
253
JRT_END
254
reassign_fields(&deoptee, &map, objects, realloc_failures);
255
#ifndef PRODUCT
256
if (TraceDeoptimization) {
257
ttyLocker ttyl;
258
tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, thread);
259
print_objects(objects, realloc_failures);
260
}
261
#endif
262
}
263
if (save_oop_result) {
264
// Restore result.
265
deoptee.set_saved_oop_result(&map, return_value());
266
}
267
}
268
if (EliminateLocks) {
269
#ifndef PRODUCT
270
bool first = true;
271
#endif
272
for (int i = 0; i < chunk->length(); i++) {
273
compiledVFrame* cvf = chunk->at(i);
274
assert (cvf->scope() != NULL,"expect only compiled java frames");
275
GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
276
if (monitors->is_nonempty()) {
277
relock_objects(monitors, thread, realloc_failures);
278
#ifndef PRODUCT
279
if (TraceDeoptimization) {
280
ttyLocker ttyl;
281
for (int j = 0; j < monitors->length(); j++) {
282
MonitorInfo* mi = monitors->at(j);
283
if (mi->eliminated()) {
284
if (first) {
285
first = false;
286
tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, thread);
287
}
288
if (mi->owner_is_scalar_replaced()) {
289
Klass* k = java_lang_Class::as_Klass(mi->owner_klass());
290
tty->print_cr(" failed reallocation for klass %s", k->external_name());
291
} else {
292
tty->print_cr(" object <" INTPTR_FORMAT "> locked", (void *)mi->owner());
293
}
294
}
295
}
296
}
297
#endif
298
}
299
}
300
}
301
}
302
#endif // COMPILER2
303
// Ensure that no safepoint is taken after pointers have been stored
304
// in fields of rematerialized objects. If a safepoint occurs from here on
305
// out the java state residing in the vframeArray will be missed.
306
No_Safepoint_Verifier no_safepoint;
307
308
vframeArray* array = create_vframeArray(thread, deoptee, &map, chunk, realloc_failures);
309
#ifdef COMPILER2
310
if (realloc_failures) {
311
pop_frames_failed_reallocs(thread, array);
312
}
313
#endif
314
315
assert(thread->vframe_array_head() == NULL, "Pending deopt!");
316
thread->set_vframe_array_head(array);
317
318
// Now that the vframeArray has been created if we have any deferred local writes
319
// added by jvmti then we can free up that structure as the data is now in the
320
// vframeArray
321
322
if (thread->deferred_locals() != NULL) {
323
GrowableArray<jvmtiDeferredLocalVariableSet*>* list = thread->deferred_locals();
324
int i = 0;
325
do {
326
// Because of inlining we could have multiple vframes for a single frame
327
// and several of the vframes could have deferred writes. Find them all.
328
if (list->at(i)->id() == array->original().id()) {
329
jvmtiDeferredLocalVariableSet* dlv = list->at(i);
330
list->remove_at(i);
331
// individual jvmtiDeferredLocalVariableSet are CHeapObj's
332
delete dlv;
333
} else {
334
i++;
335
}
336
} while ( i < list->length() );
337
if (list->length() == 0) {
338
thread->set_deferred_locals(NULL);
339
// free the list and elements back to C heap.
340
delete list;
341
}
342
343
}
344
345
#ifndef SHARK
346
// Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.
347
CodeBlob* cb = stub_frame.cb();
348
// Verify we have the right vframeArray
349
assert(cb->frame_size() >= 0, "Unexpected frame size");
350
intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();
351
352
// If the deopt call site is a MethodHandle invoke call site we have
353
// to adjust the unpack_sp.
354
nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null();
355
if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc()))
356
unpack_sp = deoptee.unextended_sp();
357
358
#ifdef ASSERT
359
assert(cb->is_deoptimization_stub() || cb->is_uncommon_trap_stub(), "just checking");
360
#endif
361
#else
362
intptr_t* unpack_sp = stub_frame.sender(&dummy_map).unextended_sp();
363
#endif // !SHARK
364
365
// This is a guarantee instead of an assert because if vframe doesn't match
366
// we will unpack the wrong deoptimized frame and wind up in strange places
367
// where it will be very difficult to figure out what went wrong. Better
368
// to die an early death here than some very obscure death later when the
369
// trail is cold.
370
// Note: on ia64 this guarantee can be fooled by frames with no memory stack
371
// in that it will fail to detect a problem when there is one. This needs
372
// more work in tiger timeframe.
373
guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");
374
375
int number_of_frames = array->frames();
376
377
// Compute the vframes' sizes. Note that frame_sizes[] entries are ordered from outermost to innermost
378
// virtual activation, which is the reverse of the elements in the vframes array.
379
intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);
380
// +1 because we always have an interpreter return address for the final slot.
381
address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);
382
int popframe_extra_args = 0;
383
// Create an interpreter return address for the stub to use as its return
384
// address so the skeletal frames are perfectly walkable
385
frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);
386
387
// PopFrame requires that the preserved incoming arguments from the recently-popped topmost
388
// activation be put back on the expression stack of the caller for reexecution
389
if (JvmtiExport::can_pop_frame() && thread->popframe_forcing_deopt_reexecution()) {
390
popframe_extra_args = in_words(thread->popframe_preserved_args_size_in_words());
391
}
392
393
// Find the current pc for sender of the deoptee. Since the sender may have been deoptimized
394
// itself since the deoptee vframeArray was created we must get a fresh value of the pc rather
395
// than simply use array->sender.pc(). This requires us to walk the current set of frames
396
//
397
frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame
398
deopt_sender = deopt_sender.sender(&dummy_map); // Now deoptee caller
399
400
// It's possible that the number of paramters at the call site is
401
// different than number of arguments in the callee when method
402
// handles are used. If the caller is interpreted get the real
403
// value so that the proper amount of space can be added to it's
404
// frame.
405
bool caller_was_method_handle = false;
406
if (deopt_sender.is_interpreted_frame()) {
407
methodHandle method = deopt_sender.interpreter_frame_method();
408
Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci());
409
if (cur.is_invokedynamic() || cur.is_invokehandle()) {
410
// Method handle invokes may involve fairly arbitrary chains of
411
// calls so it's impossible to know how much actual space the
412
// caller has for locals.
413
caller_was_method_handle = true;
414
}
415
}
416
417
//
418
// frame_sizes/frame_pcs[0] oldest frame (int or c2i)
419
// frame_sizes/frame_pcs[1] next oldest frame (int)
420
// frame_sizes/frame_pcs[n] youngest frame (int)
421
//
422
// Now a pc in frame_pcs is actually the return address to the frame's caller (a frame
423
// owns the space for the return address to it's caller). Confusing ain't it.
424
//
425
// The vframe array can address vframes with indices running from
426
// 0.._frames-1. Index 0 is the youngest frame and _frame - 1 is the oldest (root) frame.
427
// When we create the skeletal frames we need the oldest frame to be in the zero slot
428
// in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.
429
// so things look a little strange in this loop.
430
//
431
int callee_parameters = 0;
432
int callee_locals = 0;
433
for (int index = 0; index < array->frames(); index++ ) {
434
// frame[number_of_frames - 1 ] = on_stack_size(youngest)
435
// frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))
436
// frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))
437
frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,
438
callee_locals,
439
index == 0,
440
popframe_extra_args);
441
// This pc doesn't have to be perfect just good enough to identify the frame
442
// as interpreted so the skeleton frame will be walkable
443
// The correct pc will be set when the skeleton frame is completely filled out
444
// The final pc we store in the loop is wrong and will be overwritten below
445
frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;
446
447
callee_parameters = array->element(index)->method()->size_of_parameters();
448
callee_locals = array->element(index)->method()->max_locals();
449
popframe_extra_args = 0;
450
}
451
452
// Compute whether the root vframe returns a float or double value.
453
BasicType return_type;
454
{
455
HandleMark hm;
456
methodHandle method(thread, array->element(0)->method());
457
Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());
458
return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;
459
}
460
461
// Compute information for handling adapters and adjusting the frame size of the caller.
462
int caller_adjustment = 0;
463
464
// Compute the amount the oldest interpreter frame will have to adjust
465
// its caller's stack by. If the caller is a compiled frame then
466
// we pretend that the callee has no parameters so that the
467
// extension counts for the full amount of locals and not just
468
// locals-parms. This is because without a c2i adapter the parm
469
// area as created by the compiled frame will not be usable by
470
// the interpreter. (Depending on the calling convention there
471
// may not even be enough space).
472
473
// QQQ I'd rather see this pushed down into last_frame_adjust
474
// and have it take the sender (aka caller).
475
476
if (deopt_sender.is_compiled_frame() || caller_was_method_handle) {
477
caller_adjustment = last_frame_adjust(0, callee_locals);
478
} else if (callee_locals > callee_parameters) {
479
// The caller frame may need extending to accommodate
480
// non-parameter locals of the first unpacked interpreted frame.
481
// Compute that adjustment.
482
caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
483
}
484
485
// If the sender is deoptimized the we must retrieve the address of the handler
486
// since the frame will "magically" show the original pc before the deopt
487
// and we'd undo the deopt.
488
489
frame_pcs[0] = deopt_sender.raw_pc();
490
491
#ifndef SHARK
492
assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc");
493
#endif // SHARK
494
495
UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,
496
caller_adjustment * BytesPerWord,
497
caller_was_method_handle ? 0 : callee_parameters,
498
number_of_frames,
499
frame_sizes,
500
frame_pcs,
501
return_type);
502
// On some platforms, we need a way to pass some platform dependent
503
// information to the unpacking code so the skeletal frames come out
504
// correct (initial fp value, unextended sp, ...)
505
info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());
506
507
if (array->frames() > 1) {
508
if (VerifyStack && TraceDeoptimization) {
509
ttyLocker ttyl;
510
tty->print_cr("Deoptimizing method containing inlining");
511
}
512
}
513
514
array->set_unroll_block(info);
515
return info;
516
}
517
518
// Called to cleanup deoptimization data structures in normal case
519
// after unpacking to stack and when stack overflow error occurs
520
void Deoptimization::cleanup_deopt_info(JavaThread *thread,
521
vframeArray *array) {
522
523
// Get array if coming from exception
524
if (array == NULL) {
525
array = thread->vframe_array_head();
526
}
527
thread->set_vframe_array_head(NULL);
528
529
// Free the previous UnrollBlock
530
vframeArray* old_array = thread->vframe_array_last();
531
thread->set_vframe_array_last(array);
532
533
if (old_array != NULL) {
534
UnrollBlock* old_info = old_array->unroll_block();
535
old_array->set_unroll_block(NULL);
536
delete old_info;
537
delete old_array;
538
}
539
540
// Deallocate any resource creating in this routine and any ResourceObjs allocated
541
// inside the vframeArray (StackValueCollections)
542
543
delete thread->deopt_mark();
544
thread->set_deopt_mark(NULL);
545
thread->set_deopt_nmethod(NULL);
546
547
548
if (JvmtiExport::can_pop_frame()) {
549
#ifndef CC_INTERP
550
// Regardless of whether we entered this routine with the pending
551
// popframe condition bit set, we should always clear it now
552
thread->clear_popframe_condition();
553
#else
554
// C++ interpeter will clear has_pending_popframe when it enters
555
// with method_resume. For deopt_resume2 we clear it now.
556
if (thread->popframe_forcing_deopt_reexecution())
557
thread->clear_popframe_condition();
558
#endif /* CC_INTERP */
559
}
560
561
// unpack_frames() is called at the end of the deoptimization handler
562
// and (in C2) at the end of the uncommon trap handler. Note this fact
563
// so that an asynchronous stack walker can work again. This counter is
564
// incremented at the beginning of fetch_unroll_info() and (in C2) at
565
// the beginning of uncommon_trap().
566
thread->dec_in_deopt_handler();
567
}
568
569
570
// Return BasicType of value being returned
571
JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
572
573
// We are already active int he special DeoptResourceMark any ResourceObj's we
574
// allocate will be freed at the end of the routine.
575
576
// It is actually ok to allocate handles in a leaf method. It causes no safepoints,
577
// but makes the entry a little slower. There is however a little dance we have to
578
// do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
579
ResetNoHandleMark rnhm; // No-op in release/product versions
580
HandleMark hm;
581
582
frame stub_frame = thread->last_frame();
583
584
// Since the frame to unpack is the top frame of this thread, the vframe_array_head
585
// must point to the vframeArray for the unpack frame.
586
vframeArray* array = thread->vframe_array_head();
587
588
#ifndef PRODUCT
589
if (TraceDeoptimization) {
590
ttyLocker ttyl;
591
tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d", thread, array, exec_mode);
592
}
593
#endif
594
Events::log(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d",
595
stub_frame.pc(), stub_frame.sp(), exec_mode);
596
597
UnrollBlock* info = array->unroll_block();
598
599
// Unpack the interpreter frames and any adapter frame (c2 only) we might create.
600
array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());
601
602
BasicType bt = info->return_type();
603
604
// If we have an exception pending, claim that the return type is an oop
605
// so the deopt_blob does not overwrite the exception_oop.
606
607
if (exec_mode == Unpack_exception)
608
bt = T_OBJECT;
609
610
// Cleanup thread deopt data
611
cleanup_deopt_info(thread, array);
612
613
#ifndef PRODUCT
614
if (VerifyStack) {
615
ResourceMark res_mark;
616
617
thread->validate_frame_layout();
618
619
// Verify that the just-unpacked frames match the interpreter's
620
// notions of expression stack and locals
621
vframeArray* cur_array = thread->vframe_array_last();
622
RegisterMap rm(thread, false);
623
rm.set_include_argument_oops(false);
624
bool is_top_frame = true;
625
int callee_size_of_parameters = 0;
626
int callee_max_locals = 0;
627
for (int i = 0; i < cur_array->frames(); i++) {
628
vframeArrayElement* el = cur_array->element(i);
629
frame* iframe = el->iframe();
630
guarantee(iframe->is_interpreted_frame(), "Wrong frame type");
631
632
// Get the oop map for this bci
633
InterpreterOopMap mask;
634
int cur_invoke_parameter_size = 0;
635
bool try_next_mask = false;
636
int next_mask_expression_stack_size = -1;
637
int top_frame_expression_stack_adjustment = 0;
638
methodHandle mh(thread, iframe->interpreter_frame_method());
639
OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask);
640
BytecodeStream str(mh);
641
str.set_start(iframe->interpreter_frame_bci());
642
int max_bci = mh->code_size();
643
// Get to the next bytecode if possible
644
assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
645
// Check to see if we can grab the number of outgoing arguments
646
// at an uncommon trap for an invoke (where the compiler
647
// generates debug info before the invoke has executed)
648
Bytecodes::Code cur_code = str.next();
649
if (cur_code == Bytecodes::_invokevirtual ||
650
cur_code == Bytecodes::_invokespecial ||
651
cur_code == Bytecodes::_invokestatic ||
652
cur_code == Bytecodes::_invokeinterface ||
653
cur_code == Bytecodes::_invokedynamic) {
654
Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci());
655
Symbol* signature = invoke.signature();
656
ArgumentSizeComputer asc(signature);
657
cur_invoke_parameter_size = asc.size();
658
if (invoke.has_receiver()) {
659
// Add in receiver
660
++cur_invoke_parameter_size;
661
}
662
if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) {
663
callee_size_of_parameters++;
664
}
665
}
666
if (str.bci() < max_bci) {
667
Bytecodes::Code bc = str.next();
668
if (bc >= 0) {
669
// The interpreter oop map generator reports results before
670
// the current bytecode has executed except in the case of
671
// calls. It seems to be hard to tell whether the compiler
672
// has emitted debug information matching the "state before"
673
// a given bytecode or the state after, so we try both
674
switch (cur_code) {
675
case Bytecodes::_invokevirtual:
676
case Bytecodes::_invokespecial:
677
case Bytecodes::_invokestatic:
678
case Bytecodes::_invokeinterface:
679
case Bytecodes::_invokedynamic:
680
case Bytecodes::_athrow:
681
break;
682
default: {
683
InterpreterOopMap next_mask;
684
OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask);
685
next_mask_expression_stack_size = next_mask.expression_stack_size();
686
// Need to subtract off the size of the result type of
687
// the bytecode because this is not described in the
688
// debug info but returned to the interpreter in the TOS
689
// caching register
690
BasicType bytecode_result_type = Bytecodes::result_type(cur_code);
691
if (bytecode_result_type != T_ILLEGAL) {
692
top_frame_expression_stack_adjustment = type2size[bytecode_result_type];
693
}
694
assert(top_frame_expression_stack_adjustment >= 0, "");
695
try_next_mask = true;
696
break;
697
}
698
}
699
}
700
}
701
702
// Verify stack depth and oops in frame
703
// This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc)
704
if (!(
705
/* SPARC */
706
(iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) ||
707
/* x86 */
708
(iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) ||
709
(try_next_mask &&
710
(iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size -
711
top_frame_expression_stack_adjustment))) ||
712
(is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) ||
713
(is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute || el->should_reexecute()) &&
714
(iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size))
715
)) {
716
ttyLocker ttyl;
717
718
// Print out some information that will help us debug the problem
719
tty->print_cr("Wrong number of expression stack elements during deoptimization");
720
tty->print_cr(" Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1);
721
tty->print_cr(" Fabricated interpreter frame had %d expression stack elements",
722
iframe->interpreter_frame_expression_stack_size());
723
tty->print_cr(" Interpreter oop map had %d expression stack elements", mask.expression_stack_size());
724
tty->print_cr(" try_next_mask = %d", try_next_mask);
725
tty->print_cr(" next_mask_expression_stack_size = %d", next_mask_expression_stack_size);
726
tty->print_cr(" callee_size_of_parameters = %d", callee_size_of_parameters);
727
tty->print_cr(" callee_max_locals = %d", callee_max_locals);
728
tty->print_cr(" top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);
729
tty->print_cr(" exec_mode = %d", exec_mode);
730
tty->print_cr(" cur_invoke_parameter_size = %d", cur_invoke_parameter_size);
731
tty->print_cr(" Thread = " INTPTR_FORMAT ", thread ID = " UINTX_FORMAT, thread, thread->osthread()->thread_id());
732
tty->print_cr(" Interpreted frames:");
733
for (int k = 0; k < cur_array->frames(); k++) {
734
vframeArrayElement* el = cur_array->element(k);
735
tty->print_cr(" %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());
736
}
737
cur_array->print_on_2(tty);
738
guarantee(false, "wrong number of expression stack elements during deopt");
739
}
740
VerifyOopClosure verify;
741
iframe->oops_interpreted_do(&verify, NULL, &rm, false);
742
callee_size_of_parameters = mh->size_of_parameters();
743
callee_max_locals = mh->max_locals();
744
is_top_frame = false;
745
}
746
}
747
#endif /* !PRODUCT */
748
749
750
return bt;
751
JRT_END
752
753
754
int Deoptimization::deoptimize_dependents() {
755
Threads::deoptimized_wrt_marked_nmethods();
756
return 0;
757
}
758
759
760
#ifdef COMPILER2
761
bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, GrowableArray<ScopeValue*>* objects, TRAPS) {
762
Handle pending_exception(thread->pending_exception());
763
const char* exception_file = thread->exception_file();
764
int exception_line = thread->exception_line();
765
thread->clear_pending_exception();
766
767
bool failures = false;
768
769
for (int i = 0; i < objects->length(); i++) {
770
assert(objects->at(i)->is_object(), "invalid debug information");
771
ObjectValue* sv = (ObjectValue*) objects->at(i);
772
773
KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
774
oop obj = NULL;
775
776
if (k->oop_is_instance()) {
777
InstanceKlass* ik = InstanceKlass::cast(k());
778
obj = ik->allocate_instance(THREAD);
779
} else if (k->oop_is_typeArray()) {
780
TypeArrayKlass* ak = TypeArrayKlass::cast(k());
781
assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
782
int len = sv->field_size() / type2size[ak->element_type()];
783
obj = ak->allocate(len, THREAD);
784
} else if (k->oop_is_objArray()) {
785
ObjArrayKlass* ak = ObjArrayKlass::cast(k());
786
obj = ak->allocate(sv->field_size(), THREAD);
787
}
788
789
if (obj == NULL) {
790
failures = true;
791
}
792
793
assert(sv->value().is_null(), "redundant reallocation");
794
assert(obj != NULL || HAS_PENDING_EXCEPTION, "allocation should succeed or we should get an exception");
795
CLEAR_PENDING_EXCEPTION;
796
sv->set_value(obj);
797
}
798
799
if (failures) {
800
THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
801
} else if (pending_exception.not_null()) {
802
thread->set_pending_exception(pending_exception(), exception_file, exception_line);
803
}
804
805
return failures;
806
}
807
808
// This assumes that the fields are stored in ObjectValue in the same order
809
// they are yielded by do_nonstatic_fields.
810
class FieldReassigner: public FieldClosure {
811
frame* _fr;
812
RegisterMap* _reg_map;
813
ObjectValue* _sv;
814
InstanceKlass* _ik;
815
oop _obj;
816
817
int _i;
818
public:
819
FieldReassigner(frame* fr, RegisterMap* reg_map, ObjectValue* sv, oop obj) :
820
_fr(fr), _reg_map(reg_map), _sv(sv), _obj(obj), _i(0) {}
821
822
int i() const { return _i; }
823
824
825
void do_field(fieldDescriptor* fd) {
826
intptr_t val;
827
StackValue* value =
828
StackValue::create_stack_value(_fr, _reg_map, _sv->field_at(i()));
829
int offset = fd->offset();
830
switch (fd->field_type()) {
831
case T_OBJECT: case T_ARRAY:
832
assert(value->type() == T_OBJECT, "Agreement.");
833
_obj->obj_field_put(offset, value->get_obj()());
834
break;
835
836
case T_LONG: case T_DOUBLE: {
837
assert(value->type() == T_INT, "Agreement.");
838
StackValue* low =
839
StackValue::create_stack_value(_fr, _reg_map, _sv->field_at(++_i));
840
#ifdef _LP64
841
jlong res = (jlong)low->get_int();
842
#else
843
#ifdef SPARC
844
// For SPARC we have to swap high and low words.
845
jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
846
#else
847
jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
848
#endif //SPARC
849
#endif
850
_obj->long_field_put(offset, res);
851
break;
852
}
853
// Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
854
case T_INT: case T_FLOAT: // 4 bytes.
855
assert(value->type() == T_INT, "Agreement.");
856
val = value->get_int();
857
_obj->int_field_put(offset, (jint)*((jint*)&val));
858
break;
859
860
case T_SHORT:
861
assert(value->type() == T_INT, "Agreement.");
862
val = value->get_int();
863
_obj->short_field_put(offset, (jshort)*((jint*)&val));
864
break;
865
866
case T_CHAR:
867
assert(value->type() == T_INT, "Agreement.");
868
val = value->get_int();
869
_obj->char_field_put(offset, (jchar)*((jint*)&val));
870
break;
871
872
case T_BYTE:
873
assert(value->type() == T_INT, "Agreement.");
874
val = value->get_int();
875
_obj->byte_field_put(offset, (jbyte)*((jint*)&val));
876
break;
877
878
case T_BOOLEAN:
879
assert(value->type() == T_INT, "Agreement.");
880
val = value->get_int();
881
_obj->bool_field_put(offset, (jboolean)*((jint*)&val));
882
break;
883
884
default:
885
ShouldNotReachHere();
886
}
887
_i++;
888
}
889
};
890
891
// restore elements of an eliminated type array
892
void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {
893
int index = 0;
894
intptr_t val;
895
896
for (int i = 0; i < sv->field_size(); i++) {
897
StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
898
switch(type) {
899
case T_LONG: case T_DOUBLE: {
900
assert(value->type() == T_INT, "Agreement.");
901
StackValue* low =
902
StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
903
#ifdef _LP64
904
jlong res = (jlong)low->get_int();
905
#else
906
#ifdef SPARC
907
// For SPARC we have to swap high and low words.
908
jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
909
#else
910
jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
911
#endif //SPARC
912
#endif
913
obj->long_at_put(index, res);
914
break;
915
}
916
917
// Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
918
case T_INT: case T_FLOAT: // 4 bytes.
919
assert(value->type() == T_INT, "Agreement.");
920
val = value->get_int();
921
obj->int_at_put(index, (jint)*((jint*)&val));
922
break;
923
924
case T_SHORT:
925
assert(value->type() == T_INT, "Agreement.");
926
val = value->get_int();
927
obj->short_at_put(index, (jshort)*((jint*)&val));
928
break;
929
930
case T_CHAR:
931
assert(value->type() == T_INT, "Agreement.");
932
val = value->get_int();
933
obj->char_at_put(index, (jchar)*((jint*)&val));
934
break;
935
936
case T_BYTE:
937
assert(value->type() == T_INT, "Agreement.");
938
val = value->get_int();
939
obj->byte_at_put(index, (jbyte)*((jint*)&val));
940
break;
941
942
case T_BOOLEAN:
943
assert(value->type() == T_INT, "Agreement.");
944
val = value->get_int();
945
obj->bool_at_put(index, (jboolean)*((jint*)&val));
946
break;
947
948
default:
949
ShouldNotReachHere();
950
}
951
index++;
952
}
953
}
954
955
956
// restore fields of an eliminated object array
957
void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
958
for (int i = 0; i < sv->field_size(); i++) {
959
StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
960
assert(value->type() == T_OBJECT, "object element expected");
961
obj->obj_at_put(i, value->get_obj()());
962
}
963
}
964
965
966
// restore fields of all eliminated objects and arrays
967
void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
968
for (int i = 0; i < objects->length(); i++) {
969
ObjectValue* sv = (ObjectValue*) objects->at(i);
970
KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
971
Handle obj = sv->value();
972
assert(obj.not_null() || realloc_failures, "reallocation was missed");
973
if (obj.is_null()) {
974
continue;
975
}
976
977
if (k->oop_is_instance()) {
978
InstanceKlass* ik = InstanceKlass::cast(k());
979
FieldReassigner reassign(fr, reg_map, sv, obj());
980
ik->do_nonstatic_fields(&reassign);
981
} else if (k->oop_is_typeArray()) {
982
TypeArrayKlass* ak = TypeArrayKlass::cast(k());
983
reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
984
} else if (k->oop_is_objArray()) {
985
reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
986
}
987
}
988
}
989
990
991
// relock objects for which synchronization was eliminated
992
void Deoptimization::relock_objects(GrowableArray<MonitorInfo*>* monitors, JavaThread* thread, bool realloc_failures) {
993
for (int i = 0; i < monitors->length(); i++) {
994
MonitorInfo* mon_info = monitors->at(i);
995
if (mon_info->eliminated()) {
996
assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
997
if (!mon_info->owner_is_scalar_replaced()) {
998
Handle obj = Handle(mon_info->owner());
999
markOop mark = obj->mark();
1000
if (UseBiasedLocking && mark->has_bias_pattern()) {
1001
// New allocated objects may have the mark set to anonymously biased.
1002
// Also the deoptimized method may called methods with synchronization
1003
// where the thread-local object is bias locked to the current thread.
1004
assert(mark->is_biased_anonymously() ||
1005
mark->biased_locker() == thread, "should be locked to current thread");
1006
// Reset mark word to unbiased prototype.
1007
markOop unbiased_prototype = markOopDesc::prototype()->set_age(mark->age());
1008
obj->set_mark(unbiased_prototype);
1009
}
1010
BasicLock* lock = mon_info->lock();
1011
ObjectSynchronizer::slow_enter(obj, lock, thread);
1012
assert(mon_info->owner()->is_locked(), "object must be locked now");
1013
}
1014
}
1015
}
1016
}
1017
1018
1019
#ifndef PRODUCT
1020
// print information about reallocated objects
1021
void Deoptimization::print_objects(GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
1022
fieldDescriptor fd;
1023
1024
for (int i = 0; i < objects->length(); i++) {
1025
ObjectValue* sv = (ObjectValue*) objects->at(i);
1026
KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
1027
Handle obj = sv->value();
1028
1029
tty->print(" object <" INTPTR_FORMAT "> of type ", (void *)sv->value()());
1030
k->print_value();
1031
assert(obj.not_null() || realloc_failures, "reallocation was missed");
1032
if (obj.is_null()) {
1033
tty->print(" allocation failed");
1034
} else {
1035
tty->print(" allocated (%d bytes)", obj->size() * HeapWordSize);
1036
}
1037
tty->cr();
1038
1039
if (Verbose && !obj.is_null()) {
1040
k->oop_print_on(obj(), tty);
1041
}
1042
}
1043
}
1044
#endif
1045
#endif // COMPILER2
1046
1047
vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {
1048
Events::log(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, fr.pc(), fr.sp());
1049
1050
#ifndef PRODUCT
1051
if (TraceDeoptimization) {
1052
ttyLocker ttyl;
1053
tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", thread);
1054
fr.print_on(tty);
1055
tty->print_cr(" Virtual frames (innermost first):");
1056
for (int index = 0; index < chunk->length(); index++) {
1057
compiledVFrame* vf = chunk->at(index);
1058
tty->print(" %2d - ", index);
1059
vf->print_value();
1060
int bci = chunk->at(index)->raw_bci();
1061
const char* code_name;
1062
if (bci == SynchronizationEntryBCI) {
1063
code_name = "sync entry";
1064
} else {
1065
Bytecodes::Code code = vf->method()->code_at(bci);
1066
code_name = Bytecodes::name(code);
1067
}
1068
tty->print(" - %s", code_name);
1069
tty->print_cr(" @ bci %d ", bci);
1070
if (Verbose) {
1071
vf->print();
1072
tty->cr();
1073
}
1074
}
1075
}
1076
#endif
1077
1078
// Register map for next frame (used for stack crawl). We capture
1079
// the state of the deopt'ing frame's caller. Thus if we need to
1080
// stuff a C2I adapter we can properly fill in the callee-save
1081
// register locations.
1082
frame caller = fr.sender(reg_map);
1083
int frame_size = caller.sp() - fr.sp();
1084
1085
frame sender = caller;
1086
1087
// Since the Java thread being deoptimized will eventually adjust it's own stack,
1088
// the vframeArray containing the unpacking information is allocated in the C heap.
1089
// For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().
1090
vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures);
1091
1092
// Compare the vframeArray to the collected vframes
1093
assert(array->structural_compare(thread, chunk), "just checking");
1094
1095
#ifndef PRODUCT
1096
if (TraceDeoptimization) {
1097
ttyLocker ttyl;
1098
tty->print_cr(" Created vframeArray " INTPTR_FORMAT, array);
1099
}
1100
#endif // PRODUCT
1101
1102
return array;
1103
}
1104
1105
#ifdef COMPILER2
1106
void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) {
1107
// Reallocation of some scalar replaced objects failed. Record
1108
// that we need to pop all the interpreter frames for the
1109
// deoptimized compiled frame.
1110
assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?");
1111
thread->set_frames_to_pop_failed_realloc(array->frames());
1112
// Unlock all monitors here otherwise the interpreter will see a
1113
// mix of locked and unlocked monitors (because of failed
1114
// reallocations of synchronized objects) and be confused.
1115
for (int i = 0; i < array->frames(); i++) {
1116
MonitorChunk* monitors = array->element(i)->monitors();
1117
if (monitors != NULL) {
1118
for (int j = 0; j < monitors->number_of_monitors(); j++) {
1119
BasicObjectLock* src = monitors->at(j);
1120
if (src->obj() != NULL) {
1121
ObjectSynchronizer::fast_exit(src->obj(), src->lock(), thread);
1122
}
1123
}
1124
array->element(i)->free_monitors(thread);
1125
#ifdef ASSERT
1126
array->element(i)->set_removed_monitors();
1127
#endif
1128
}
1129
}
1130
}
1131
#endif
1132
1133
static void collect_monitors(compiledVFrame* cvf, GrowableArray<Handle>* objects_to_revoke) {
1134
GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
1135
for (int i = 0; i < monitors->length(); i++) {
1136
MonitorInfo* mon_info = monitors->at(i);
1137
if (!mon_info->eliminated() && mon_info->owner() != NULL) {
1138
objects_to_revoke->append(Handle(mon_info->owner()));
1139
}
1140
}
1141
}
1142
1143
1144
void Deoptimization::revoke_biases_of_monitors(JavaThread* thread, frame fr, RegisterMap* map) {
1145
if (!UseBiasedLocking) {
1146
return;
1147
}
1148
1149
GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
1150
1151
// Unfortunately we don't have a RegisterMap available in most of
1152
// the places we want to call this routine so we need to walk the
1153
// stack again to update the register map.
1154
if (map == NULL || !map->update_map()) {
1155
StackFrameStream sfs(thread, true);
1156
bool found = false;
1157
while (!found && !sfs.is_done()) {
1158
frame* cur = sfs.current();
1159
sfs.next();
1160
found = cur->id() == fr.id();
1161
}
1162
assert(found, "frame to be deoptimized not found on target thread's stack");
1163
map = sfs.register_map();
1164
}
1165
1166
vframe* vf = vframe::new_vframe(&fr, map, thread);
1167
compiledVFrame* cvf = compiledVFrame::cast(vf);
1168
// Revoke monitors' biases in all scopes
1169
while (!cvf->is_top()) {
1170
collect_monitors(cvf, objects_to_revoke);
1171
cvf = compiledVFrame::cast(cvf->sender());
1172
}
1173
collect_monitors(cvf, objects_to_revoke);
1174
1175
if (SafepointSynchronize::is_at_safepoint()) {
1176
BiasedLocking::revoke_at_safepoint(objects_to_revoke);
1177
} else {
1178
BiasedLocking::revoke(objects_to_revoke);
1179
}
1180
}
1181
1182
1183
void Deoptimization::revoke_biases_of_monitors(CodeBlob* cb) {
1184
if (!UseBiasedLocking) {
1185
return;
1186
}
1187
1188
assert(SafepointSynchronize::is_at_safepoint(), "must only be called from safepoint");
1189
GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
1190
for (JavaThread* jt = Threads::first(); jt != NULL ; jt = jt->next()) {
1191
if (jt->has_last_Java_frame()) {
1192
StackFrameStream sfs(jt, true);
1193
while (!sfs.is_done()) {
1194
frame* cur = sfs.current();
1195
if (cb->contains(cur->pc())) {
1196
vframe* vf = vframe::new_vframe(cur, sfs.register_map(), jt);
1197
compiledVFrame* cvf = compiledVFrame::cast(vf);
1198
// Revoke monitors' biases in all scopes
1199
while (!cvf->is_top()) {
1200
collect_monitors(cvf, objects_to_revoke);
1201
cvf = compiledVFrame::cast(cvf->sender());
1202
}
1203
collect_monitors(cvf, objects_to_revoke);
1204
}
1205
sfs.next();
1206
}
1207
}
1208
}
1209
BiasedLocking::revoke_at_safepoint(objects_to_revoke);
1210
}
1211
1212
1213
void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr) {
1214
assert(fr.can_be_deoptimized(), "checking frame type");
1215
1216
gather_statistics(Reason_constraint, Action_none, Bytecodes::_illegal);
1217
1218
// Patch the nmethod so that when execution returns to it we will
1219
// deopt the execution state and return to the interpreter.
1220
fr.deoptimize(thread);
1221
}
1222
1223
void Deoptimization::deoptimize(JavaThread* thread, frame fr, RegisterMap *map) {
1224
// Deoptimize only if the frame comes from compile code.
1225
// Do not deoptimize the frame which is already patched
1226
// during the execution of the loops below.
1227
if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
1228
return;
1229
}
1230
ResourceMark rm;
1231
DeoptimizationMarker dm;
1232
if (UseBiasedLocking) {
1233
revoke_biases_of_monitors(thread, fr, map);
1234
}
1235
deoptimize_single_frame(thread, fr);
1236
1237
}
1238
1239
1240
void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id) {
1241
assert(thread == Thread::current() || SafepointSynchronize::is_at_safepoint(),
1242
"can only deoptimize other thread at a safepoint");
1243
// Compute frame and register map based on thread and sp.
1244
RegisterMap reg_map(thread, UseBiasedLocking);
1245
frame fr = thread->last_frame();
1246
while (fr.id() != id) {
1247
fr = fr.sender(&reg_map);
1248
}
1249
deoptimize(thread, fr, &reg_map);
1250
}
1251
1252
1253
void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {
1254
if (thread == Thread::current()) {
1255
Deoptimization::deoptimize_frame_internal(thread, id);
1256
} else {
1257
VM_DeoptimizeFrame deopt(thread, id);
1258
VMThread::execute(&deopt);
1259
}
1260
}
1261
1262
1263
// JVMTI PopFrame support
1264
JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))
1265
{
1266
thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);
1267
}
1268
JRT_END
1269
1270
1271
#if defined(COMPILER2) || defined(SHARK)
1272
void Deoptimization::load_class_by_index(constantPoolHandle constant_pool, int index, TRAPS) {
1273
// in case of an unresolved klass entry, load the class.
1274
if (constant_pool->tag_at(index).is_unresolved_klass()) {
1275
Klass* tk = constant_pool->klass_at(index, CHECK);
1276
return;
1277
}
1278
1279
if (!constant_pool->tag_at(index).is_symbol()) return;
1280
1281
Handle class_loader (THREAD, constant_pool->pool_holder()->class_loader());
1282
Symbol* symbol = constant_pool->symbol_at(index);
1283
1284
// class name?
1285
if (symbol->byte_at(0) != '(') {
1286
Handle protection_domain (THREAD, constant_pool->pool_holder()->protection_domain());
1287
SystemDictionary::resolve_or_null(symbol, class_loader, protection_domain, CHECK);
1288
return;
1289
}
1290
1291
// then it must be a signature!
1292
ResourceMark rm(THREAD);
1293
for (SignatureStream ss(symbol); !ss.is_done(); ss.next()) {
1294
if (ss.is_object()) {
1295
Symbol* class_name = ss.as_symbol(CHECK);
1296
Handle protection_domain (THREAD, constant_pool->pool_holder()->protection_domain());
1297
SystemDictionary::resolve_or_null(class_name, class_loader, protection_domain, CHECK);
1298
}
1299
}
1300
}
1301
1302
1303
void Deoptimization::load_class_by_index(constantPoolHandle constant_pool, int index) {
1304
EXCEPTION_MARK;
1305
load_class_by_index(constant_pool, index, THREAD);
1306
if (HAS_PENDING_EXCEPTION) {
1307
// Exception happened during classloading. We ignore the exception here, since it
1308
// is going to be rethrown since the current activation is going to be deoptimized and
1309
// the interpreter will re-execute the bytecode.
1310
CLEAR_PENDING_EXCEPTION;
1311
// Class loading called java code which may have caused a stack
1312
// overflow. If the exception was thrown right before the return
1313
// to the runtime the stack is no longer guarded. Reguard the
1314
// stack otherwise if we return to the uncommon trap blob and the
1315
// stack bang causes a stack overflow we crash.
1316
assert(THREAD->is_Java_thread(), "only a java thread can be here");
1317
JavaThread* thread = (JavaThread*)THREAD;
1318
bool guard_pages_enabled = thread->stack_yellow_zone_enabled();
1319
if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
1320
assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");
1321
}
1322
}
1323
1324
JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* thread, jint trap_request)) {
1325
HandleMark hm;
1326
1327
// uncommon_trap() is called at the beginning of the uncommon trap
1328
// handler. Note this fact before we start generating temporary frames
1329
// that can confuse an asynchronous stack walker. This counter is
1330
// decremented at the end of unpack_frames().
1331
thread->inc_in_deopt_handler();
1332
1333
// We need to update the map if we have biased locking.
1334
RegisterMap reg_map(thread, UseBiasedLocking);
1335
frame stub_frame = thread->last_frame();
1336
frame fr = stub_frame.sender(&reg_map);
1337
// Make sure the calling nmethod is not getting deoptimized and removed
1338
// before we are done with it.
1339
nmethodLocker nl(fr.pc());
1340
1341
// Log a message
1342
Events::log(thread, "Uncommon trap: trap_request=" PTR32_FORMAT " fr.pc=" INTPTR_FORMAT,
1343
trap_request, fr.pc());
1344
1345
{
1346
ResourceMark rm;
1347
1348
// Revoke biases of any monitors in the frame to ensure we can migrate them
1349
revoke_biases_of_monitors(thread, fr, &reg_map);
1350
1351
DeoptReason reason = trap_request_reason(trap_request);
1352
DeoptAction action = trap_request_action(trap_request);
1353
jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1
1354
1355
vframe* vf = vframe::new_vframe(&fr, &reg_map, thread);
1356
compiledVFrame* cvf = compiledVFrame::cast(vf);
1357
1358
nmethod* nm = cvf->code();
1359
1360
ScopeDesc* trap_scope = cvf->scope();
1361
methodHandle trap_method = trap_scope->method();
1362
int trap_bci = trap_scope->bci();
1363
Bytecodes::Code trap_bc = trap_method->java_code_at(trap_bci);
1364
1365
// Record this event in the histogram.
1366
gather_statistics(reason, action, trap_bc);
1367
1368
// Ensure that we can record deopt. history:
1369
// Need MDO to record RTM code generation state.
1370
bool create_if_missing = ProfileTraps RTM_OPT_ONLY( || UseRTMLocking );
1371
1372
MethodData* trap_mdo =
1373
get_method_data(thread, trap_method, create_if_missing);
1374
1375
// Log a message
1376
Events::log_deopt_message(thread, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d",
1377
trap_reason_name(reason), trap_action_name(action), fr.pc(),
1378
trap_method->name_and_sig_as_C_string(), trap_bci);
1379
1380
// Print a bunch of diagnostics, if requested.
1381
if (TraceDeoptimization || LogCompilation) {
1382
ResourceMark rm;
1383
ttyLocker ttyl;
1384
char buf[100];
1385
if (xtty != NULL) {
1386
xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT "' %s",
1387
os::current_thread_id(),
1388
format_trap_request(buf, sizeof(buf), trap_request));
1389
nm->log_identity(xtty);
1390
}
1391
Symbol* class_name = NULL;
1392
bool unresolved = false;
1393
if (unloaded_class_index >= 0) {
1394
constantPoolHandle constants (THREAD, trap_method->constants());
1395
if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {
1396
class_name = constants->klass_name_at(unloaded_class_index);
1397
unresolved = true;
1398
if (xtty != NULL)
1399
xtty->print(" unresolved='1'");
1400
} else if (constants->tag_at(unloaded_class_index).is_symbol()) {
1401
class_name = constants->symbol_at(unloaded_class_index);
1402
}
1403
if (xtty != NULL)
1404
xtty->name(class_name);
1405
}
1406
if (xtty != NULL && trap_mdo != NULL) {
1407
// Dump the relevant MDO state.
1408
// This is the deopt count for the current reason, any previous
1409
// reasons or recompiles seen at this point.
1410
int dcnt = trap_mdo->trap_count(reason);
1411
if (dcnt != 0)
1412
xtty->print(" count='%d'", dcnt);
1413
ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);
1414
int dos = (pdata == NULL)? 0: pdata->trap_state();
1415
if (dos != 0) {
1416
xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));
1417
if (trap_state_is_recompiled(dos)) {
1418
int recnt2 = trap_mdo->overflow_recompile_count();
1419
if (recnt2 != 0)
1420
xtty->print(" recompiles2='%d'", recnt2);
1421
}
1422
}
1423
}
1424
if (xtty != NULL) {
1425
xtty->stamp();
1426
xtty->end_head();
1427
}
1428
if (TraceDeoptimization) { // make noise on the tty
1429
tty->print("Uncommon trap occurred in");
1430
nm->method()->print_short_name(tty);
1431
tty->print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d",
1432
fr.pc(),
1433
os::current_thread_id(),
1434
trap_reason_name(reason),
1435
trap_action_name(action),
1436
unloaded_class_index);
1437
if (class_name != NULL) {
1438
tty->print(unresolved ? " unresolved class: " : " symbol: ");
1439
class_name->print_symbol_on(tty);
1440
}
1441
tty->cr();
1442
}
1443
if (xtty != NULL) {
1444
// Log the precise location of the trap.
1445
for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {
1446
xtty->begin_elem("jvms bci='%d'", sd->bci());
1447
xtty->method(sd->method());
1448
xtty->end_elem();
1449
if (sd->is_top()) break;
1450
}
1451
xtty->tail("uncommon_trap");
1452
}
1453
}
1454
// (End diagnostic printout.)
1455
1456
// Load class if necessary
1457
if (unloaded_class_index >= 0) {
1458
constantPoolHandle constants(THREAD, trap_method->constants());
1459
load_class_by_index(constants, unloaded_class_index);
1460
}
1461
1462
// Flush the nmethod if necessary and desirable.
1463
//
1464
// We need to avoid situations where we are re-flushing the nmethod
1465
// because of a hot deoptimization site. Repeated flushes at the same
1466
// point need to be detected by the compiler and avoided. If the compiler
1467
// cannot avoid them (or has a bug and "refuses" to avoid them), this
1468
// module must take measures to avoid an infinite cycle of recompilation
1469
// and deoptimization. There are several such measures:
1470
//
1471
// 1. If a recompilation is ordered a second time at some site X
1472
// and for the same reason R, the action is adjusted to 'reinterpret',
1473
// to give the interpreter time to exercise the method more thoroughly.
1474
// If this happens, the method's overflow_recompile_count is incremented.
1475
//
1476
// 2. If the compiler fails to reduce the deoptimization rate, then
1477
// the method's overflow_recompile_count will begin to exceed the set
1478
// limit PerBytecodeRecompilationCutoff. If this happens, the action
1479
// is adjusted to 'make_not_compilable', and the method is abandoned
1480
// to the interpreter. This is a performance hit for hot methods,
1481
// but is better than a disastrous infinite cycle of recompilations.
1482
// (Actually, only the method containing the site X is abandoned.)
1483
//
1484
// 3. In parallel with the previous measures, if the total number of
1485
// recompilations of a method exceeds the much larger set limit
1486
// PerMethodRecompilationCutoff, the method is abandoned.
1487
// This should only happen if the method is very large and has
1488
// many "lukewarm" deoptimizations. The code which enforces this
1489
// limit is elsewhere (class nmethod, class Method).
1490
//
1491
// Note that the per-BCI 'is_recompiled' bit gives the compiler one chance
1492
// to recompile at each bytecode independently of the per-BCI cutoff.
1493
//
1494
// The decision to update code is up to the compiler, and is encoded
1495
// in the Action_xxx code. If the compiler requests Action_none
1496
// no trap state is changed, no compiled code is changed, and the
1497
// computation suffers along in the interpreter.
1498
//
1499
// The other action codes specify various tactics for decompilation
1500
// and recompilation. Action_maybe_recompile is the loosest, and
1501
// allows the compiled code to stay around until enough traps are seen,
1502
// and until the compiler gets around to recompiling the trapping method.
1503
//
1504
// The other actions cause immediate removal of the present code.
1505
1506
// Traps caused by injected profile shouldn't pollute trap counts.
1507
bool injected_profile_trap = trap_method->has_injected_profile() &&
1508
(reason == Reason_intrinsic || reason == Reason_unreached);
1509
bool update_trap_state = !injected_profile_trap;
1510
bool make_not_entrant = false;
1511
bool make_not_compilable = false;
1512
bool reprofile = false;
1513
switch (action) {
1514
case Action_none:
1515
// Keep the old code.
1516
update_trap_state = false;
1517
break;
1518
case Action_maybe_recompile:
1519
// Do not need to invalidate the present code, but we can
1520
// initiate another
1521
// Start compiler without (necessarily) invalidating the nmethod.
1522
// The system will tolerate the old code, but new code should be
1523
// generated when possible.
1524
break;
1525
case Action_reinterpret:
1526
// Go back into the interpreter for a while, and then consider
1527
// recompiling form scratch.
1528
make_not_entrant = true;
1529
// Reset invocation counter for outer most method.
1530
// This will allow the interpreter to exercise the bytecodes
1531
// for a while before recompiling.
1532
// By contrast, Action_make_not_entrant is immediate.
1533
//
1534
// Note that the compiler will track null_check, null_assert,
1535
// range_check, and class_check events and log them as if they
1536
// had been traps taken from compiled code. This will update
1537
// the MDO trap history so that the next compilation will
1538
// properly detect hot trap sites.
1539
reprofile = true;
1540
break;
1541
case Action_make_not_entrant:
1542
// Request immediate recompilation, and get rid of the old code.
1543
// Make them not entrant, so next time they are called they get
1544
// recompiled. Unloaded classes are loaded now so recompile before next
1545
// time they are called. Same for uninitialized. The interpreter will
1546
// link the missing class, if any.
1547
make_not_entrant = true;
1548
break;
1549
case Action_make_not_compilable:
1550
// Give up on compiling this method at all.
1551
make_not_entrant = true;
1552
make_not_compilable = true;
1553
break;
1554
default:
1555
ShouldNotReachHere();
1556
}
1557
1558
// Setting +ProfileTraps fixes the following, on all platforms:
1559
// 4852688: ProfileInterpreter is off by default for ia64. The result is
1560
// infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the
1561
// recompile relies on a MethodData* to record heroic opt failures.
1562
1563
// Whether the interpreter is producing MDO data or not, we also need
1564
// to use the MDO to detect hot deoptimization points and control
1565
// aggressive optimization.
1566
bool inc_recompile_count = false;
1567
ProfileData* pdata = NULL;
1568
if (ProfileTraps && update_trap_state && trap_mdo != NULL) {
1569
assert(trap_mdo == get_method_data(thread, trap_method, false), "sanity");
1570
uint this_trap_count = 0;
1571
bool maybe_prior_trap = false;
1572
bool maybe_prior_recompile = false;
1573
pdata = query_update_method_data(trap_mdo, trap_bci, reason,
1574
nm->method(),
1575
//outputs:
1576
this_trap_count,
1577
maybe_prior_trap,
1578
maybe_prior_recompile);
1579
// Because the interpreter also counts null, div0, range, and class
1580
// checks, these traps from compiled code are double-counted.
1581
// This is harmless; it just means that the PerXTrapLimit values
1582
// are in effect a little smaller than they look.
1583
1584
DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
1585
if (per_bc_reason != Reason_none) {
1586
// Now take action based on the partially known per-BCI history.
1587
if (maybe_prior_trap
1588
&& this_trap_count >= (uint)PerBytecodeTrapLimit) {
1589
// If there are too many traps at this BCI, force a recompile.
1590
// This will allow the compiler to see the limit overflow, and
1591
// take corrective action, if possible. The compiler generally
1592
// does not use the exact PerBytecodeTrapLimit value, but instead
1593
// changes its tactics if it sees any traps at all. This provides
1594
// a little hysteresis, delaying a recompile until a trap happens
1595
// several times.
1596
//
1597
// Actually, since there is only one bit of counter per BCI,
1598
// the possible per-BCI counts are {0,1,(per-method count)}.
1599
// This produces accurate results if in fact there is only
1600
// one hot trap site, but begins to get fuzzy if there are
1601
// many sites. For example, if there are ten sites each
1602
// trapping two or more times, they each get the blame for
1603
// all of their traps.
1604
make_not_entrant = true;
1605
}
1606
1607
// Detect repeated recompilation at the same BCI, and enforce a limit.
1608
if (make_not_entrant && maybe_prior_recompile) {
1609
// More than one recompile at this point.
1610
inc_recompile_count = maybe_prior_trap;
1611
}
1612
} else {
1613
// For reasons which are not recorded per-bytecode, we simply
1614
// force recompiles unconditionally.
1615
// (Note that PerMethodRecompilationCutoff is enforced elsewhere.)
1616
make_not_entrant = true;
1617
}
1618
1619
// Go back to the compiler if there are too many traps in this method.
1620
if (this_trap_count >= per_method_trap_limit(reason)) {
1621
// If there are too many traps in this method, force a recompile.
1622
// This will allow the compiler to see the limit overflow, and
1623
// take corrective action, if possible.
1624
// (This condition is an unlikely backstop only, because the
1625
// PerBytecodeTrapLimit is more likely to take effect first,
1626
// if it is applicable.)
1627
make_not_entrant = true;
1628
}
1629
1630
// Here's more hysteresis: If there has been a recompile at
1631
// this trap point already, run the method in the interpreter
1632
// for a while to exercise it more thoroughly.
1633
if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {
1634
reprofile = true;
1635
}
1636
1637
}
1638
1639
// Take requested actions on the method:
1640
1641
// Recompile
1642
if (make_not_entrant) {
1643
if (!nm->make_not_entrant()) {
1644
return; // the call did not change nmethod's state
1645
}
1646
1647
if (pdata != NULL) {
1648
// Record the recompilation event, if any.
1649
int tstate0 = pdata->trap_state();
1650
int tstate1 = trap_state_set_recompiled(tstate0, true);
1651
if (tstate1 != tstate0)
1652
pdata->set_trap_state(tstate1);
1653
}
1654
1655
#if INCLUDE_RTM_OPT
1656
// Restart collecting RTM locking abort statistic if the method
1657
// is recompiled for a reason other than RTM state change.
1658
// Assume that in new recompiled code the statistic could be different,
1659
// for example, due to different inlining.
1660
if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) &&
1661
UseRTMDeopt && (nm->rtm_state() != ProfileRTM)) {
1662
trap_mdo->atomic_set_rtm_state(ProfileRTM);
1663
}
1664
#endif
1665
}
1666
1667
if (inc_recompile_count) {
1668
trap_mdo->inc_overflow_recompile_count();
1669
if ((uint)trap_mdo->overflow_recompile_count() >
1670
(uint)PerBytecodeRecompilationCutoff) {
1671
// Give up on the method containing the bad BCI.
1672
if (trap_method() == nm->method()) {
1673
make_not_compilable = true;
1674
} else {
1675
trap_method->set_not_compilable(CompLevel_full_optimization, true, "overflow_recompile_count > PerBytecodeRecompilationCutoff");
1676
// But give grace to the enclosing nm->method().
1677
}
1678
}
1679
}
1680
1681
// Reprofile
1682
if (reprofile) {
1683
CompilationPolicy::policy()->reprofile(trap_scope, nm->is_osr_method());
1684
}
1685
1686
// Give up compiling
1687
if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {
1688
assert(make_not_entrant, "consistent");
1689
nm->method()->set_not_compilable(CompLevel_full_optimization);
1690
}
1691
1692
} // Free marked resources
1693
1694
}
1695
JRT_END
1696
1697
MethodData*
1698
Deoptimization::get_method_data(JavaThread* thread, methodHandle m,
1699
bool create_if_missing) {
1700
Thread* THREAD = thread;
1701
MethodData* mdo = m()->method_data();
1702
if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) {
1703
// Build an MDO. Ignore errors like OutOfMemory;
1704
// that simply means we won't have an MDO to update.
1705
Method::build_interpreter_method_data(m, THREAD);
1706
if (HAS_PENDING_EXCEPTION) {
1707
assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
1708
CLEAR_PENDING_EXCEPTION;
1709
}
1710
mdo = m()->method_data();
1711
}
1712
return mdo;
1713
}
1714
1715
ProfileData*
1716
Deoptimization::query_update_method_data(MethodData* trap_mdo,
1717
int trap_bci,
1718
Deoptimization::DeoptReason reason,
1719
Method* compiled_method,
1720
//outputs:
1721
uint& ret_this_trap_count,
1722
bool& ret_maybe_prior_trap,
1723
bool& ret_maybe_prior_recompile) {
1724
uint prior_trap_count = trap_mdo->trap_count(reason);
1725
uint this_trap_count = trap_mdo->inc_trap_count(reason);
1726
1727
// If the runtime cannot find a place to store trap history,
1728
// it is estimated based on the general condition of the method.
1729
// If the method has ever been recompiled, or has ever incurred
1730
// a trap with the present reason , then this BCI is assumed
1731
// (pessimistically) to be the culprit.
1732
bool maybe_prior_trap = (prior_trap_count != 0);
1733
bool maybe_prior_recompile = (trap_mdo->decompile_count() != 0);
1734
ProfileData* pdata = NULL;
1735
1736
1737
// For reasons which are recorded per bytecode, we check per-BCI data.
1738
DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
1739
if (per_bc_reason != Reason_none) {
1740
// Find the profile data for this BCI. If there isn't one,
1741
// try to allocate one from the MDO's set of spares.
1742
// This will let us detect a repeated trap at this point.
1743
pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL);
1744
1745
if (pdata != NULL) {
1746
if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {
1747
if (LogCompilation && xtty != NULL) {
1748
ttyLocker ttyl;
1749
// no more room for speculative traps in this MDO
1750
xtty->elem("speculative_traps_oom");
1751
}
1752
}
1753
// Query the trap state of this profile datum.
1754
int tstate0 = pdata->trap_state();
1755
if (!trap_state_has_reason(tstate0, per_bc_reason))
1756
maybe_prior_trap = false;
1757
if (!trap_state_is_recompiled(tstate0))
1758
maybe_prior_recompile = false;
1759
1760
// Update the trap state of this profile datum.
1761
int tstate1 = tstate0;
1762
// Record the reason.
1763
tstate1 = trap_state_add_reason(tstate1, per_bc_reason);
1764
// Store the updated state on the MDO, for next time.
1765
if (tstate1 != tstate0)
1766
pdata->set_trap_state(tstate1);
1767
} else {
1768
if (LogCompilation && xtty != NULL) {
1769
ttyLocker ttyl;
1770
// Missing MDP? Leave a small complaint in the log.
1771
xtty->elem("missing_mdp bci='%d'", trap_bci);
1772
}
1773
}
1774
}
1775
1776
// Return results:
1777
ret_this_trap_count = this_trap_count;
1778
ret_maybe_prior_trap = maybe_prior_trap;
1779
ret_maybe_prior_recompile = maybe_prior_recompile;
1780
return pdata;
1781
}
1782
1783
void
1784
Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
1785
ResourceMark rm;
1786
// Ignored outputs:
1787
uint ignore_this_trap_count;
1788
bool ignore_maybe_prior_trap;
1789
bool ignore_maybe_prior_recompile;
1790
assert(!reason_is_speculate(reason), "reason speculate only used by compiler");
1791
query_update_method_data(trap_mdo, trap_bci,
1792
(DeoptReason)reason,
1793
NULL,
1794
ignore_this_trap_count,
1795
ignore_maybe_prior_trap,
1796
ignore_maybe_prior_recompile);
1797
}
1798
1799
Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* thread, jint trap_request) {
1800
1801
// Still in Java no safepoints
1802
{
1803
// This enters VM and may safepoint
1804
uncommon_trap_inner(thread, trap_request);
1805
}
1806
return fetch_unroll_info_helper(thread);
1807
}
1808
1809
// Local derived constants.
1810
// Further breakdown of DataLayout::trap_state, as promised by DataLayout.
1811
const int DS_REASON_MASK = DataLayout::trap_mask >> 1;
1812
const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;
1813
1814
//---------------------------trap_state_reason---------------------------------
1815
Deoptimization::DeoptReason
1816
Deoptimization::trap_state_reason(int trap_state) {
1817
// This assert provides the link between the width of DataLayout::trap_bits
1818
// and the encoding of "recorded" reasons. It ensures there are enough
1819
// bits to store all needed reasons in the per-BCI MDO profile.
1820
assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
1821
int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
1822
trap_state -= recompile_bit;
1823
if (trap_state == DS_REASON_MASK) {
1824
return Reason_many;
1825
} else {
1826
assert((int)Reason_none == 0, "state=0 => Reason_none");
1827
return (DeoptReason)trap_state;
1828
}
1829
}
1830
//-------------------------trap_state_has_reason-------------------------------
1831
int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
1832
assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");
1833
assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
1834
int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
1835
trap_state -= recompile_bit;
1836
if (trap_state == DS_REASON_MASK) {
1837
return -1; // true, unspecifically (bottom of state lattice)
1838
} else if (trap_state == reason) {
1839
return 1; // true, definitely
1840
} else if (trap_state == 0) {
1841
return 0; // false, definitely (top of state lattice)
1842
} else {
1843
return 0; // false, definitely
1844
}
1845
}
1846
//-------------------------trap_state_add_reason-------------------------------
1847
int Deoptimization::trap_state_add_reason(int trap_state, int reason) {
1848
assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");
1849
int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
1850
trap_state -= recompile_bit;
1851
if (trap_state == DS_REASON_MASK) {
1852
return trap_state + recompile_bit; // already at state lattice bottom
1853
} else if (trap_state == reason) {
1854
return trap_state + recompile_bit; // the condition is already true
1855
} else if (trap_state == 0) {
1856
return reason + recompile_bit; // no condition has yet been true
1857
} else {
1858
return DS_REASON_MASK + recompile_bit; // fall to state lattice bottom
1859
}
1860
}
1861
//-----------------------trap_state_is_recompiled------------------------------
1862
bool Deoptimization::trap_state_is_recompiled(int trap_state) {
1863
return (trap_state & DS_RECOMPILE_BIT) != 0;
1864
}
1865
//-----------------------trap_state_set_recompiled-----------------------------
1866
int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {
1867
if (z) return trap_state | DS_RECOMPILE_BIT;
1868
else return trap_state & ~DS_RECOMPILE_BIT;
1869
}
1870
//---------------------------format_trap_state---------------------------------
1871
// This is used for debugging and diagnostics, including LogFile output.
1872
const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
1873
int trap_state) {
1874
DeoptReason reason = trap_state_reason(trap_state);
1875
bool recomp_flag = trap_state_is_recompiled(trap_state);
1876
// Re-encode the state from its decoded components.
1877
int decoded_state = 0;
1878
if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)
1879
decoded_state = trap_state_add_reason(decoded_state, reason);
1880
if (recomp_flag)
1881
decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);
1882
// If the state re-encodes properly, format it symbolically.
1883
// Because this routine is used for debugging and diagnostics,
1884
// be robust even if the state is a strange value.
1885
size_t len;
1886
if (decoded_state != trap_state) {
1887
// Random buggy state that doesn't decode??
1888
len = jio_snprintf(buf, buflen, "#%d", trap_state);
1889
} else {
1890
len = jio_snprintf(buf, buflen, "%s%s",
1891
trap_reason_name(reason),
1892
recomp_flag ? " recompiled" : "");
1893
}
1894
return buf;
1895
}
1896
1897
1898
//--------------------------------statics--------------------------------------
1899
Deoptimization::DeoptAction Deoptimization::_unloaded_action
1900
= Deoptimization::Action_reinterpret;
1901
const char* Deoptimization::_trap_reason_name[Reason_LIMIT] = {
1902
// Note: Keep this in sync. with enum DeoptReason.
1903
"none",
1904
"null_check",
1905
"null_assert",
1906
"range_check",
1907
"class_check",
1908
"array_check",
1909
"intrinsic",
1910
"bimorphic",
1911
"unloaded",
1912
"uninitialized",
1913
"unreached",
1914
"unhandled",
1915
"constraint",
1916
"div0_check",
1917
"age",
1918
"predicate",
1919
"loop_limit_check",
1920
"speculate_class_check",
1921
"rtm_state_change",
1922
"unstable_if"
1923
};
1924
const char* Deoptimization::_trap_action_name[Action_LIMIT] = {
1925
// Note: Keep this in sync. with enum DeoptAction.
1926
"none",
1927
"maybe_recompile",
1928
"reinterpret",
1929
"make_not_entrant",
1930
"make_not_compilable"
1931
};
1932
1933
const char* Deoptimization::trap_reason_name(int reason) {
1934
if (reason == Reason_many) return "many";
1935
if ((uint)reason < Reason_LIMIT)
1936
return _trap_reason_name[reason];
1937
static char buf[20];
1938
sprintf(buf, "reason%d", reason);
1939
return buf;
1940
}
1941
const char* Deoptimization::trap_action_name(int action) {
1942
if ((uint)action < Action_LIMIT)
1943
return _trap_action_name[action];
1944
static char buf[20];
1945
sprintf(buf, "action%d", action);
1946
return buf;
1947
}
1948
1949
// This is used for debugging and diagnostics, including LogFile output.
1950
const char* Deoptimization::format_trap_request(char* buf, size_t buflen,
1951
int trap_request) {
1952
jint unloaded_class_index = trap_request_index(trap_request);
1953
const char* reason = trap_reason_name(trap_request_reason(trap_request));
1954
const char* action = trap_action_name(trap_request_action(trap_request));
1955
size_t len;
1956
if (unloaded_class_index < 0) {
1957
len = jio_snprintf(buf, buflen, "reason='%s' action='%s'",
1958
reason, action);
1959
} else {
1960
len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'",
1961
reason, action, unloaded_class_index);
1962
}
1963
return buf;
1964
}
1965
1966
juint Deoptimization::_deoptimization_hist
1967
[Deoptimization::Reason_LIMIT]
1968
[1 + Deoptimization::Action_LIMIT]
1969
[Deoptimization::BC_CASE_LIMIT]
1970
= {0};
1971
1972
enum {
1973
LSB_BITS = 8,
1974
LSB_MASK = right_n_bits(LSB_BITS)
1975
};
1976
1977
void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
1978
Bytecodes::Code bc) {
1979
assert(reason >= 0 && reason < Reason_LIMIT, "oob");
1980
assert(action >= 0 && action < Action_LIMIT, "oob");
1981
_deoptimization_hist[Reason_none][0][0] += 1; // total
1982
_deoptimization_hist[reason][0][0] += 1; // per-reason total
1983
juint* cases = _deoptimization_hist[reason][1+action];
1984
juint* bc_counter_addr = NULL;
1985
juint bc_counter = 0;
1986
// Look for an unused counter, or an exact match to this BC.
1987
if (bc != Bytecodes::_illegal) {
1988
for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
1989
juint* counter_addr = &cases[bc_case];
1990
juint counter = *counter_addr;
1991
if ((counter == 0 && bc_counter_addr == NULL)
1992
|| (Bytecodes::Code)(counter & LSB_MASK) == bc) {
1993
// this counter is either free or is already devoted to this BC
1994
bc_counter_addr = counter_addr;
1995
bc_counter = counter | bc;
1996
}
1997
}
1998
}
1999
if (bc_counter_addr == NULL) {
2000
// Overflow, or no given bytecode.
2001
bc_counter_addr = &cases[BC_CASE_LIMIT-1];
2002
bc_counter = (*bc_counter_addr & ~LSB_MASK); // clear LSB
2003
}
2004
*bc_counter_addr = bc_counter + (1 << LSB_BITS);
2005
}
2006
2007
jint Deoptimization::total_deoptimization_count() {
2008
return _deoptimization_hist[Reason_none][0][0];
2009
}
2010
2011
jint Deoptimization::deoptimization_count(DeoptReason reason) {
2012
assert(reason >= 0 && reason < Reason_LIMIT, "oob");
2013
return _deoptimization_hist[reason][0][0];
2014
}
2015
2016
void Deoptimization::print_statistics() {
2017
juint total = total_deoptimization_count();
2018
juint account = total;
2019
if (total != 0) {
2020
ttyLocker ttyl;
2021
if (xtty != NULL) xtty->head("statistics type='deoptimization'");
2022
tty->print_cr("Deoptimization traps recorded:");
2023
#define PRINT_STAT_LINE(name, r) \
2024
tty->print_cr(" %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);
2025
PRINT_STAT_LINE("total", total);
2026
// For each non-zero entry in the histogram, print the reason,
2027
// the action, and (if specifically known) the type of bytecode.
2028
for (int reason = 0; reason < Reason_LIMIT; reason++) {
2029
for (int action = 0; action < Action_LIMIT; action++) {
2030
juint* cases = _deoptimization_hist[reason][1+action];
2031
for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2032
juint counter = cases[bc_case];
2033
if (counter != 0) {
2034
char name[1*K];
2035
Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
2036
if (bc_case == BC_CASE_LIMIT && (int)bc == 0)
2037
bc = Bytecodes::_illegal;
2038
sprintf(name, "%s/%s/%s",
2039
trap_reason_name(reason),
2040
trap_action_name(action),
2041
Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");
2042
juint r = counter >> LSB_BITS;
2043
tty->print_cr(" %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);
2044
account -= r;
2045
}
2046
}
2047
}
2048
}
2049
if (account != 0) {
2050
PRINT_STAT_LINE("unaccounted", account);
2051
}
2052
#undef PRINT_STAT_LINE
2053
if (xtty != NULL) xtty->tail("statistics");
2054
}
2055
}
2056
#else // COMPILER2 || SHARK
2057
2058
2059
// Stubs for C1 only system.
2060
bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2061
return false;
2062
}
2063
2064
const char* Deoptimization::trap_reason_name(int reason) {
2065
return "unknown";
2066
}
2067
2068
void Deoptimization::print_statistics() {
2069
// no output
2070
}
2071
2072
void
2073
Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
2074
// no udpate
2075
}
2076
2077
int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2078
return 0;
2079
}
2080
2081
void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2082
Bytecodes::Code bc) {
2083
// no update
2084
}
2085
2086
const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2087
int trap_state) {
2088
jio_snprintf(buf, buflen, "#%d", trap_state);
2089
return buf;
2090
}
2091
2092
#endif // COMPILER2 || SHARK
2093
2094