This repository has been archived by the owner on Aug 16, 2023. It is now read-only.
/
deoptimization.cpp
2384 lines (2132 loc) · 92.6 KB
/
deoptimization.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "classfile/systemDictionary.hpp"
#include "code/debugInfoRec.hpp"
#include "code/nmethod.hpp"
#include "code/pcDesc.hpp"
#include "code/scopeDesc.hpp"
#include "interpreter/bytecode.hpp"
#include "interpreter/interpreter.hpp"
#include "interpreter/oopMapCache.hpp"
#include "memory/allocation.inline.hpp"
#include "memory/oopFactory.hpp"
#include "memory/resourceArea.hpp"
#include "oops/method.hpp"
#include "oops/oop.inline.hpp"
#include "oops/fieldStreams.hpp"
#include "prims/jvmtiThreadState.hpp"
#include "runtime/biasedLocking.hpp"
#include "runtime/compilationPolicy.hpp"
#include "runtime/deoptimization.hpp"
#include "runtime/interfaceSupport.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/signature.hpp"
#include "runtime/stubRoutines.hpp"
#include "runtime/thread.hpp"
#include "runtime/vframe.hpp"
#include "runtime/vframeArray.hpp"
#include "runtime/vframe_hp.hpp"
#include "utilities/events.hpp"
#include "utilities/xmlstream.hpp"
#ifdef TARGET_ARCH_x86
# include "vmreg_x86.inline.hpp"
#endif
#ifdef TARGET_ARCH_sparc
# include "vmreg_sparc.inline.hpp"
#endif
#ifdef TARGET_ARCH_zero
# include "vmreg_zero.inline.hpp"
#endif
#ifdef TARGET_ARCH_arm
# include "vmreg_arm.inline.hpp"
#endif
#ifdef TARGET_ARCH_ppc
# include "vmreg_ppc.inline.hpp"
#endif
#ifdef COMPILER2
#if defined AD_MD_HPP
# include AD_MD_HPP
#elif defined TARGET_ARCH_MODEL_x86_32
# include "adfiles/ad_x86_32.hpp"
#elif defined TARGET_ARCH_MODEL_x86_64
# include "adfiles/ad_x86_64.hpp"
#elif defined TARGET_ARCH_MODEL_sparc
# include "adfiles/ad_sparc.hpp"
#elif defined TARGET_ARCH_MODEL_zero
# include "adfiles/ad_zero.hpp"
#elif defined TARGET_ARCH_MODEL_ppc_64
# include "adfiles/ad_ppc_64.hpp"
#endif
#endif // COMPILER2
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
#if INCLUDE_JVMCI
#include "jvmci/jvmciRuntime.hpp"
#include "jvmci/jvmciJavaClasses.hpp"
#endif
bool DeoptimizationMarker::_is_active = false;
Deoptimization::UnrollBlock::UnrollBlock(int size_of_deoptimized_frame,
int caller_adjustment,
int caller_actual_parameters,
int number_of_frames,
intptr_t* frame_sizes,
address* frame_pcs,
BasicType return_type,
int exec_mode) {
_size_of_deoptimized_frame = size_of_deoptimized_frame;
_caller_adjustment = caller_adjustment;
_caller_actual_parameters = caller_actual_parameters;
_number_of_frames = number_of_frames;
_frame_sizes = frame_sizes;
_frame_pcs = frame_pcs;
_register_block = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);
_return_type = return_type;
_initial_info = 0;
// PD (x86 only)
_counter_temp = 0;
_unpack_kind = exec_mode;
_sender_sp_temp = 0;
_total_frame_sizes = size_of_frames();
assert(exec_mode >= 0 && exec_mode < Unpack_LIMIT, "Unexpected exec_mode");
}
Deoptimization::UnrollBlock::~UnrollBlock() {
FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes, mtCompiler);
FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs, mtCompiler);
FREE_C_HEAP_ARRAY(intptr_t, _register_block, mtCompiler);
}
intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const {
assert(register_number < RegisterMap::reg_count, "checking register number");
return &_register_block[register_number * 2];
}
int Deoptimization::UnrollBlock::size_of_frames() const {
// Acount first for the adjustment of the initial frame
int result = _caller_adjustment;
for (int index = 0; index < number_of_frames(); index++) {
result += frame_sizes()[index];
}
return result;
}
void Deoptimization::UnrollBlock::print() {
ttyLocker ttyl;
tty->print_cr("UnrollBlock");
tty->print_cr(" size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
tty->print( " frame_sizes: ");
for (int index = 0; index < number_of_frames(); index++) {
tty->print("%d ", frame_sizes()[index]);
}
tty->cr();
}
// In order to make fetch_unroll_info work properly with escape
// analysis, The method was changed from JRT_LEAF to JRT_BLOCK_ENTRY and
// ResetNoHandleMark and HandleMark were removed from it. The actual reallocation
// of previously eliminated objects occurs in realloc_objects, which is
// called from the method fetch_unroll_info_helper below.
JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* thread, int exec_mode))
// It is actually ok to allocate handles in a leaf method. It causes no safepoints,
// but makes the entry a little slower. There is however a little dance we have to
// do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
// fetch_unroll_info() is called at the beginning of the deoptimization
// handler. Note this fact before we start generating temporary frames
// that can confuse an asynchronous stack walker. This counter is
// decremented at the end of unpack_frames().
if (TraceDeoptimization) {
tty->print_cr("Deoptimizing thread " INTPTR_FORMAT, thread);
}
thread->inc_in_deopt_handler();
return fetch_unroll_info_helper(thread, exec_mode);
JRT_END
// This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)
Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* thread, int exec_mode) {
// Note: there is a safepoint safety issue here. No matter whether we enter
// via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once
// the vframeArray is created.
//
// Allocate our special deoptimization ResourceMark
DeoptResourceMark* dmark = new DeoptResourceMark(thread);
assert(thread->deopt_mark() == NULL, "Pending deopt!");
thread->set_deopt_mark(dmark);
frame stub_frame = thread->last_frame(); // Makes stack walkable as side effect
RegisterMap map(thread, true);
RegisterMap dummy_map(thread, false);
// Now get the deoptee with a valid map
frame deoptee = stub_frame.sender(&map);
// Set the deoptee nmethod
assert(thread->deopt_nmethod() == NULL, "Pending deopt!");
thread->set_deopt_nmethod(deoptee.cb()->as_nmethod_or_null());
bool skip_internal = thread->deopt_nmethod() != NULL && !thread->deopt_nmethod()->compiler()->is_jvmci();
if (VerifyStack) {
thread->validate_frame_layout();
}
// Create a growable array of VFrames where each VFrame represents an inlined
// Java frame. This storage is allocated with the usual system arena.
assert(deoptee.is_compiled_frame(), "Wrong frame type");
GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);
vframe* vf = vframe::new_vframe(&deoptee, &map, thread);
while (!vf->is_top()) {
assert(vf->is_compiled_frame(), "Wrong frame type");
chunk->push(compiledVFrame::cast(vf));
vf = vf->sender();
}
assert(vf->is_compiled_frame(), "Wrong frame type");
chunk->push(compiledVFrame::cast(vf));
bool realloc_failures = false;
#if defined(COMPILER2) || INCLUDE_JVMCI
// Reallocate the non-escaping objects and restore their fields. Then
// relock objects if synchronization on them was eliminated.
#ifndef INCLUDE_JVMCI
if (DoEscapeAnalysis || EliminateNestedLocks) {
if (EliminateAllocations) {
#endif // INCLUDE_JVMCI
assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames");
GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects();
// The flag return_oop() indicates call sites which return oop
// in compiled code. Such sites include java method calls,
// runtime calls (for example, used to allocate new objects/arrays
// on slow code path) and any other calls generated in compiled code.
// It is not guaranteed that we can get such information here only
// by analyzing bytecode in deoptimized frames. This is why this flag
// is set during method compilation (see Compile::Process_OopMap_Node()).
// If the previous frame was popped or if we are dispatching an exception,
// we don't have an oop result.
bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Unpack_deopt);
Handle return_value;
if (save_oop_result) {
// Reallocation may trigger GC. If deoptimization happened on return from
// call which returns oop we need to save it since it is not in oopmap.
oop result = deoptee.saved_oop_result(&map);
assert(result == NULL || result->is_oop(), "must be oop");
return_value = Handle(thread, result);
assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
if (TraceDeoptimization) {
ttyLocker ttyl;
tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, (void *)result, thread);
}
}
if (objects != NULL) {
JRT_BLOCK
realloc_failures = realloc_objects(thread, &deoptee, &map, objects, THREAD);
JRT_END
reassign_fields(&deoptee, &map, objects, realloc_failures, skip_internal);
#ifndef PRODUCT
if (TraceDeoptimization) {
ttyLocker ttyl;
tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, thread);
print_objects(objects, realloc_failures);
}
#endif
}
if (save_oop_result) {
// Restore result.
deoptee.set_saved_oop_result(&map, return_value());
}
#ifndef INCLUDE_JVMCI
}
if (EliminateLocks) {
#endif // INCLUDE_JVMCI
#ifndef PRODUCT
bool first = true;
#endif
for (int i = 0; i < chunk->length(); i++) {
compiledVFrame* cvf = chunk->at(i);
assert (cvf->scope() != NULL,"expect only compiled java frames");
GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
if (monitors->is_nonempty()) {
relock_objects(monitors, thread, realloc_failures);
#ifndef PRODUCT
if (PrintDeoptimizationDetails) {
ttyLocker ttyl;
for (int j = 0; j < monitors->length(); j++) {
MonitorInfo* mi = monitors->at(j);
if (mi->eliminated()) {
if (first) {
first = false;
tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, thread);
}
if (mi->owner_is_scalar_replaced()) {
Klass* k = java_lang_Class::as_Klass(mi->owner_klass());
tty->print_cr(" failed reallocation for klass %s", k->external_name());
} else {
tty->print_cr(" object <" INTPTR_FORMAT "> locked", (void *)mi->owner());
}
}
}
}
#endif
}
}
#ifndef INCLUDE_JVMCI
}
}
#endif // INCLUDE_JVMCI
#endif // COMPILER2 || INCLUDE_JVMCI
ScopeDesc* trap_scope = chunk->at(0)->scope();
Handle exceptionObject;
if (trap_scope->rethrow_exception()) {
if (PrintDeoptimizationDetails || TraceDeoptimization) {
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());
}
GrowableArray<ScopeValue*>* expressions = trap_scope->expressions();
guarantee(expressions != NULL && expressions->length() > 0, "must have exception to throw");
ScopeValue* topOfStack = expressions->top();
exceptionObject = StackValue::create_stack_value(&deoptee, &map, topOfStack)->get_obj();
guarantee(exceptionObject() != NULL, "exception oop can not be null");
}
// Ensure that no safepoint is taken after pointers have been stored
// in fields of rematerialized objects. If a safepoint occurs from here on
// out the java state residing in the vframeArray will be missed.
No_Safepoint_Verifier no_safepoint;
vframeArray* array = create_vframeArray(thread, deoptee, &map, chunk, realloc_failures);
#if defined(COMPILER2) || INCLUDE_JVMCI
if (realloc_failures) {
pop_frames_failed_reallocs(thread, array);
}
#endif
assert(thread->vframe_array_head() == NULL, "Pending deopt!");
thread->set_vframe_array_head(array);
// Now that the vframeArray has been created if we have any deferred local writes
// added by jvmti then we can free up that structure as the data is now in the
// vframeArray
if (thread->deferred_locals() != NULL) {
GrowableArray<jvmtiDeferredLocalVariableSet*>* list = thread->deferred_locals();
int i = 0;
do {
// Because of inlining we could have multiple vframes for a single frame
// and several of the vframes could have deferred writes. Find them all.
if (list->at(i)->id() == array->original().id()) {
jvmtiDeferredLocalVariableSet* dlv = list->at(i);
list->remove_at(i);
// individual jvmtiDeferredLocalVariableSet are CHeapObj's
delete dlv;
} else {
i++;
}
} while ( i < list->length() );
if (list->length() == 0) {
thread->set_deferred_locals(NULL);
// free the list and elements back to C heap.
delete list;
}
}
#ifndef SHARK
// Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.
CodeBlob* cb = stub_frame.cb();
// Verify we have the right vframeArray
assert(cb->frame_size() >= 0, "Unexpected frame size");
intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();
// If the deopt call site is a MethodHandle invoke call site we have
// to adjust the unpack_sp.
nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null();
if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc()))
unpack_sp = deoptee.unextended_sp();
#ifdef ASSERT
assert(cb->is_deoptimization_stub() ||
cb->is_uncommon_trap_stub() ||
strcmp("Stub<DeoptimizationStub.deoptimizationHandler>", cb->name()) == 0 ||
strcmp("Stub<UncommonTrapStub.uncommonTrapHandler>", cb->name()) == 0,
err_msg("unexpected code blob: %s", cb->name()));
#endif
#else
intptr_t* unpack_sp = stub_frame.sender(&dummy_map).unextended_sp();
#endif // !SHARK
// This is a guarantee instead of an assert because if vframe doesn't match
// we will unpack the wrong deoptimized frame and wind up in strange places
// where it will be very difficult to figure out what went wrong. Better
// to die an early death here than some very obscure death later when the
// trail is cold.
// Note: on ia64 this guarantee can be fooled by frames with no memory stack
// in that it will fail to detect a problem when there is one. This needs
// more work in tiger timeframe.
guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");
int number_of_frames = array->frames();
// Compute the vframes' sizes. Note that frame_sizes[] entries are ordered from outermost to innermost
// virtual activation, which is the reverse of the elements in the vframes array.
intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);
// +1 because we always have an interpreter return address for the final slot.
address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);
int popframe_extra_args = 0;
// Create an interpreter return address for the stub to use as its return
// address so the skeletal frames are perfectly walkable
frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);
// PopFrame requires that the preserved incoming arguments from the recently-popped topmost
// activation be put back on the expression stack of the caller for reexecution
if (JvmtiExport::can_pop_frame() && thread->popframe_forcing_deopt_reexecution()) {
popframe_extra_args = in_words(thread->popframe_preserved_args_size_in_words());
}
// Find the current pc for sender of the deoptee. Since the sender may have been deoptimized
// itself since the deoptee vframeArray was created we must get a fresh value of the pc rather
// than simply use array->sender.pc(). This requires us to walk the current set of frames
//
frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame
deopt_sender = deopt_sender.sender(&dummy_map); // Now deoptee caller
// It's possible that the number of paramters at the call site is
// different than number of arguments in the callee when method
// handles are used. If the caller is interpreted get the real
// value so that the proper amount of space can be added to it's
// frame.
bool caller_was_method_handle = false;
if (deopt_sender.is_interpreted_frame()) {
methodHandle method = deopt_sender.interpreter_frame_method();
Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci());
if (cur.is_invokedynamic() || cur.is_invokehandle()) {
// Method handle invokes may involve fairly arbitrary chains of
// calls so it's impossible to know how much actual space the
// caller has for locals.
caller_was_method_handle = true;
}
}
//
// frame_sizes/frame_pcs[0] oldest frame (int or c2i)
// frame_sizes/frame_pcs[1] next oldest frame (int)
// frame_sizes/frame_pcs[n] youngest frame (int)
//
// Now a pc in frame_pcs is actually the return address to the frame's caller (a frame
// owns the space for the return address to it's caller). Confusing ain't it.
//
// The vframe array can address vframes with indices running from
// 0.._frames-1. Index 0 is the youngest frame and _frame - 1 is the oldest (root) frame.
// When we create the skeletal frames we need the oldest frame to be in the zero slot
// in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.
// so things look a little strange in this loop.
//
int callee_parameters = 0;
int callee_locals = 0;
for (int index = 0; index < array->frames(); index++ ) {
// frame[number_of_frames - 1 ] = on_stack_size(youngest)
// frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))
// frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))
frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,
callee_locals,
index == 0,
popframe_extra_args);
// This pc doesn't have to be perfect just good enough to identify the frame
// as interpreted so the skeleton frame will be walkable
// The correct pc will be set when the skeleton frame is completely filled out
// The final pc we store in the loop is wrong and will be overwritten below
frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;
callee_parameters = array->element(index)->method()->size_of_parameters();
callee_locals = array->element(index)->method()->max_locals();
popframe_extra_args = 0;
}
// Compute whether the root vframe returns a float or double value.
BasicType return_type;
{
HandleMark hm;
methodHandle method(thread, array->element(0)->method());
Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());
return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;
}
// Compute information for handling adapters and adjusting the frame size of the caller.
int caller_adjustment = 0;
// Compute the amount the oldest interpreter frame will have to adjust
// its caller's stack by. If the caller is a compiled frame then
// we pretend that the callee has no parameters so that the
// extension counts for the full amount of locals and not just
// locals-parms. This is because without a c2i adapter the parm
// area as created by the compiled frame will not be usable by
// the interpreter. (Depending on the calling convention there
// may not even be enough space).
// QQQ I'd rather see this pushed down into last_frame_adjust
// and have it take the sender (aka caller).
if (deopt_sender.is_compiled_frame() || caller_was_method_handle) {
caller_adjustment = last_frame_adjust(0, callee_locals);
} else if (callee_locals > callee_parameters) {
// The caller frame may need extending to accommodate
// non-parameter locals of the first unpacked interpreted frame.
// Compute that adjustment.
caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
}
// If the sender is deoptimized the we must retrieve the address of the handler
// since the frame will "magically" show the original pc before the deopt
// and we'd undo the deopt.
frame_pcs[0] = deopt_sender.raw_pc();
#ifndef SHARK
assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc");
#endif // SHARK
#if INCLUDE_JVMCI
if (exceptionObject() != NULL) {
thread->set_exception_oop(exceptionObject());
exec_mode = Unpack_exception;
}
#endif
UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,
caller_adjustment * BytesPerWord,
caller_was_method_handle ? 0 : callee_parameters,
number_of_frames,
frame_sizes,
frame_pcs,
return_type,
exec_mode);
// On some platforms, we need a way to pass some platform dependent
// information to the unpacking code so the skeletal frames come out
// correct (initial fp value, unextended sp, ...)
info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());
if (array->frames() > 1) {
if (VerifyStack && TraceDeoptimization) {
ttyLocker ttyl;
tty->print_cr("Deoptimizing method containing inlining");
}
}
array->set_unroll_block(info);
return info;
}
// Called to cleanup deoptimization data structures in normal case
// after unpacking to stack and when stack overflow error occurs
void Deoptimization::cleanup_deopt_info(JavaThread *thread,
vframeArray *array) {
// Get array if coming from exception
if (array == NULL) {
array = thread->vframe_array_head();
}
thread->set_vframe_array_head(NULL);
// Free the previous UnrollBlock
vframeArray* old_array = thread->vframe_array_last();
thread->set_vframe_array_last(array);
if (old_array != NULL) {
UnrollBlock* old_info = old_array->unroll_block();
old_array->set_unroll_block(NULL);
delete old_info;
delete old_array;
}
// Deallocate any resource creating in this routine and any ResourceObjs allocated
// inside the vframeArray (StackValueCollections)
delete thread->deopt_mark();
thread->set_deopt_mark(NULL);
thread->set_deopt_nmethod(NULL);
if (JvmtiExport::can_pop_frame()) {
#ifndef CC_INTERP
// Regardless of whether we entered this routine with the pending
// popframe condition bit set, we should always clear it now
thread->clear_popframe_condition();
#else
// C++ interpeter will clear has_pending_popframe when it enters
// with method_resume. For deopt_resume2 we clear it now.
if (thread->popframe_forcing_deopt_reexecution())
thread->clear_popframe_condition();
#endif /* CC_INTERP */
}
// unpack_frames() is called at the end of the deoptimization handler
// and (in C2) at the end of the uncommon trap handler. Note this fact
// so that an asynchronous stack walker can work again. This counter is
// incremented at the beginning of fetch_unroll_info() and (in C2) at
// the beginning of uncommon_trap().
thread->dec_in_deopt_handler();
}
// Return BasicType of value being returned
JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
// We are already active int he special DeoptResourceMark any ResourceObj's we
// allocate will be freed at the end of the routine.
// It is actually ok to allocate handles in a leaf method. It causes no safepoints,
// but makes the entry a little slower. There is however a little dance we have to
// do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
ResetNoHandleMark rnhm; // No-op in release/product versions
HandleMark hm;
frame stub_frame = thread->last_frame();
// Since the frame to unpack is the top frame of this thread, the vframe_array_head
// must point to the vframeArray for the unpack frame.
vframeArray* array = thread->vframe_array_head();
#ifndef PRODUCT
if (TraceDeoptimization) {
ttyLocker ttyl;
tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d", thread, array, exec_mode);
}
#endif
Events::log(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d",
stub_frame.pc(), stub_frame.sp(), exec_mode);
UnrollBlock* info = array->unroll_block();
// Unpack the interpreter frames and any adapter frame (c2 only) we might create.
array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());
BasicType bt = info->return_type();
// If we have an exception pending, claim that the return type is an oop
// so the deopt_blob does not overwrite the exception_oop.
if (exec_mode == Unpack_exception)
bt = T_OBJECT;
// Cleanup thread deopt data
cleanup_deopt_info(thread, array);
#ifndef PRODUCT
if (VerifyStack) {
ResourceMark res_mark;
thread->validate_frame_layout();
// Verify that the just-unpacked frames match the interpreter's
// notions of expression stack and locals
vframeArray* cur_array = thread->vframe_array_last();
RegisterMap rm(thread, false);
rm.set_include_argument_oops(false);
bool is_top_frame = true;
int callee_size_of_parameters = 0;
int callee_max_locals = 0;
for (int i = 0; i < cur_array->frames(); i++) {
vframeArrayElement* el = cur_array->element(i);
frame* iframe = el->iframe();
guarantee(iframe->is_interpreted_frame(), "Wrong frame type");
// Get the oop map for this bci
InterpreterOopMap mask;
int cur_invoke_parameter_size = 0;
bool try_next_mask = false;
int next_mask_expression_stack_size = -1;
int top_frame_expression_stack_adjustment = 0;
methodHandle mh(thread, iframe->interpreter_frame_method());
OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask);
BytecodeStream str(mh);
str.set_start(iframe->interpreter_frame_bci());
int max_bci = mh->code_size();
// Get to the next bytecode if possible
assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
// Check to see if we can grab the number of outgoing arguments
// at an uncommon trap for an invoke (where the compiler
// generates debug info before the invoke has executed)
Bytecodes::Code cur_code = str.next();
if (cur_code == Bytecodes::_invokevirtual ||
cur_code == Bytecodes::_invokespecial ||
cur_code == Bytecodes::_invokestatic ||
cur_code == Bytecodes::_invokeinterface ||
cur_code == Bytecodes::_invokedynamic) {
Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci());
Symbol* signature = invoke.signature();
ArgumentSizeComputer asc(signature);
cur_invoke_parameter_size = asc.size();
if (invoke.has_receiver()) {
// Add in receiver
++cur_invoke_parameter_size;
}
if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) {
callee_size_of_parameters++;
}
}
if (str.bci() < max_bci) {
Bytecodes::Code bc = str.next();
if (bc >= 0) {
// The interpreter oop map generator reports results before
// the current bytecode has executed except in the case of
// calls. It seems to be hard to tell whether the compiler
// has emitted debug information matching the "state before"
// a given bytecode or the state after, so we try both
switch (cur_code) {
case Bytecodes::_invokevirtual:
case Bytecodes::_invokespecial:
case Bytecodes::_invokestatic:
case Bytecodes::_invokeinterface:
case Bytecodes::_invokedynamic:
case Bytecodes::_athrow:
break;
default: {
InterpreterOopMap next_mask;
OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask);
next_mask_expression_stack_size = next_mask.expression_stack_size();
// Need to subtract off the size of the result type of
// the bytecode because this is not described in the
// debug info but returned to the interpreter in the TOS
// caching register
BasicType bytecode_result_type = Bytecodes::result_type(cur_code);
if (bytecode_result_type != T_ILLEGAL) {
top_frame_expression_stack_adjustment = type2size[bytecode_result_type];
}
assert(top_frame_expression_stack_adjustment >= 0, "");
try_next_mask = true;
break;
}
}
}
}
// Verify stack depth and oops in frame
// This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc)
if (!(
/* SPARC */
(iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) ||
/* x86 */
(iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) ||
(try_next_mask &&
(iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size -
top_frame_expression_stack_adjustment))) ||
(is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) ||
(is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute || el->should_reexecute()) &&
(iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size))
)) {
ttyLocker ttyl;
// Print out some information that will help us debug the problem
tty->print_cr("Wrong number of expression stack elements during deoptimization");
tty->print_cr(" Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1);
tty->print_cr(" Fabricated interpreter frame had %d expression stack elements",
iframe->interpreter_frame_expression_stack_size());
tty->print_cr(" Interpreter oop map had %d expression stack elements", mask.expression_stack_size());
tty->print_cr(" try_next_mask = %d", try_next_mask);
tty->print_cr(" next_mask_expression_stack_size = %d", next_mask_expression_stack_size);
tty->print_cr(" callee_size_of_parameters = %d", callee_size_of_parameters);
tty->print_cr(" callee_max_locals = %d", callee_max_locals);
tty->print_cr(" top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);
tty->print_cr(" exec_mode = %d", exec_mode);
tty->print_cr(" cur_invoke_parameter_size = %d", cur_invoke_parameter_size);
tty->print_cr(" Thread = " INTPTR_FORMAT ", thread ID = " UINTX_FORMAT, thread, thread->osthread()->thread_id());
tty->print_cr(" Interpreted frames:");
for (int k = 0; k < cur_array->frames(); k++) {
vframeArrayElement* el = cur_array->element(k);
tty->print_cr(" %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());
}
cur_array->print_on_2(tty);
guarantee(false, "wrong number of expression stack elements during deopt");
}
VerifyOopClosure verify;
iframe->oops_interpreted_do(&verify, NULL, &rm, false);
callee_size_of_parameters = mh->size_of_parameters();
callee_max_locals = mh->max_locals();
is_top_frame = false;
}
}
#endif /* !PRODUCT */
return bt;
JRT_END
int Deoptimization::deoptimize_dependents() {
Threads::deoptimized_wrt_marked_nmethods();
return 0;
}
#if defined(COMPILER2) || INCLUDE_JVMCI
bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) {
Handle pending_exception(thread->pending_exception());
const char* exception_file = thread->exception_file();
int exception_line = thread->exception_line();
thread->clear_pending_exception();
bool failures = false;
for (int i = 0; i < objects->length(); i++) {
assert(objects->at(i)->is_object(), "invalid debug information");
ObjectValue* sv = (ObjectValue*) objects->at(i);
KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
if (reg_map == NULL && (!sv->base_object()->is_constant_oop() || !sv->base_object()->as_ConstantOopReadValue()->value().is_null())) {
// skip element with base object if we don't have a register map
continue;
}
oop obj = StackValue::create_stack_value(fr, reg_map, sv->base_object())->get_obj()();
if (obj == NULL) {
if (k->oop_is_instance()) {
InstanceKlass* ik = InstanceKlass::cast(k());
obj = ik->allocate_instance(THREAD);
} else if (k->oop_is_typeArray()) {
TypeArrayKlass* ak = TypeArrayKlass::cast(k());
assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
int len = sv->field_size() / type2size[ak->element_type()];
obj = ak->allocate(len, THREAD);
} else if (k->oop_is_objArray()) {
ObjArrayKlass* ak = ObjArrayKlass::cast(k());
obj = ak->allocate(sv->field_size(), THREAD);
}
}
if (obj == NULL) {
failures = true;
}
assert(sv->value().is_null(), "redundant reallocation");
assert(obj != NULL || HAS_PENDING_EXCEPTION, "allocation should succeed or we should get an exception");
CLEAR_PENDING_EXCEPTION;
sv->set_value(obj);
}
if (failures) {
THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
} else if (pending_exception.not_null()) {
thread->set_pending_exception(pending_exception(), exception_file, exception_line);
}
return failures;
}
// restore elements of an eliminated type array
void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {
int index = 0;
intptr_t val;
for (int i = 0; i < sv->field_size(); i++) {
StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
if (value->type() == T_CONFLICT) {
// skip fields with no values
index += (type == T_LONG || type == T_DOUBLE) ? 2 : 1;
continue;
}
switch(type) {
case T_LONG: case T_DOUBLE: {
assert(value->type() == T_INT, "Agreement.");
StackValue* low =
StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
#ifdef _LP64
jlong res = (jlong)low->get_int();
#else
#ifdef SPARC
// For SPARC we have to swap high and low words.
jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
#else
jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
#endif //SPARC
#endif
obj->long_at_put(index, res);
break;
}
// Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
case T_INT: case T_FLOAT: { // 4 bytes.
assert(value->type() == T_INT, "Agreement.");
bool big_value = false;
if (i + 1 < sv->field_size() && type == T_INT) {
if (sv->field_at(i)->is_location()) {
Location::Type type = ((LocationValue*) sv->field_at(i))->location().type();
if (type == Location::dbl || type == Location::lng) {
big_value = true;
}
} else if (sv->field_at(i)->is_constant_int()) {
ScopeValue* next_scope_field = sv->field_at(i + 1);
if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
big_value = true;
}
}
}
if (big_value) {
StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
#ifdef _LP64
jlong res = (jlong)low->get_int();
#else
#ifdef SPARC
// For SPARC we have to swap high and low words.
jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
#else
jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
#endif //SPARC
#endif
obj->int_at_put(index, (jint)*((jint*)&res));
obj->int_at_put(++index, (jint)*(((jint*)&res) + 1));
} else {
val = value->get_int();
obj->int_at_put(index, (jint)*((jint*)&val));
}
break;
}
case T_SHORT:
assert(value->type() == T_INT, "Agreement.");
val = value->get_int();
obj->short_at_put(index, (jshort)*((jint*)&val));
break;
case T_CHAR:
assert(value->type() == T_INT, "Agreement.");
val = value->get_int();
obj->char_at_put(index, (jchar)*((jint*)&val));
break;
case T_BYTE:
assert(value->type() == T_INT, "Agreement.");
val = value->get_int();
obj->byte_at_put(index, (jbyte)*((jint*)&val));
break;
case T_BOOLEAN:
assert(value->type() == T_INT, "Agreement.");
val = value->get_int();
obj->bool_at_put(index, (jboolean)*((jint*)&val));
break;
default:
ShouldNotReachHere();
}
index++;
}
}
// restore fields of an eliminated object array
void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
for (int i = 0; i < sv->field_size(); i++) {
StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
if (value->type() == T_CONFLICT) {
// skip fields with no values
continue;
}
assert(value->type() == T_OBJECT, "object element expected");
obj->obj_at_put(i, value->get_obj()());
}
}
class ReassignedField {
public:
int _offset;
BasicType _type;
public:
ReassignedField() {
_offset = 0;
_type = T_ILLEGAL;
}
};
int compare(ReassignedField* left, ReassignedField* right) {
return left->_offset - right->_offset;
}
// Restore fields of an eliminated instance object using the same field order
// returned by HotSpotResolvedObjectTypeImpl.getInstanceFields(true)
static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool skip_internal) {
if (klass->superklass() != NULL) {
svIndex = reassign_fields_by_klass(klass->superklass(), fr, reg_map, sv, svIndex, obj, skip_internal);
}
GrowableArray<ReassignedField>* fields = new GrowableArray<ReassignedField>();
for (AllFieldStream fs(klass); !fs.done(); fs.next()) {
if (!fs.access_flags().is_static() && (!skip_internal || !fs.access_flags().is_internal())) {
ReassignedField field;
field._offset = fs.offset();
field._type = FieldType::basic_type(fs.signature());
fields->append(field);
}
}
fields->sort(compare);
for (int i = 0; i < fields->length(); i++) {
intptr_t val;
ScopeValue* scope_field = sv->field_at(svIndex);
StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);