1 /*
2 * Copyright (c) 2000, 2025, 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 "cds/cdsConfig.hpp"
26 #include "ci/ciMethodData.hpp"
27 #include "classfile/systemDictionaryShared.hpp"
28 #include "classfile/vmSymbols.hpp"
29 #include "compiler/compilationPolicy.hpp"
30 #include "compiler/compilerDefinitions.inline.hpp"
31 #include "compiler/compilerOracle.hpp"
32 #include "interpreter/bytecode.hpp"
33 #include "interpreter/bytecodeStream.hpp"
34 #include "interpreter/linkResolver.hpp"
35 #include "memory/metaspaceClosure.hpp"
36 #include "memory/resourceArea.hpp"
37 #include "oops/klass.inline.hpp"
38 #include "oops/method.inline.hpp"
39 #include "oops/methodData.inline.hpp"
40 #include "prims/jvmtiRedefineClasses.hpp"
41 #include "runtime/atomicAccess.hpp"
42 #include "runtime/deoptimization.hpp"
43 #include "runtime/handles.inline.hpp"
44 #include "runtime/orderAccess.hpp"
45 #include "runtime/safepointVerifiers.hpp"
46 #include "runtime/signature.hpp"
47 #include "utilities/align.hpp"
48 #include "utilities/checkedCast.hpp"
49 #include "utilities/copy.hpp"
50
51 // ==================================================================
52 // DataLayout
53 //
54 // Overlay for generic profiling data.
55
56 // Some types of data layouts need a length field.
57 bool DataLayout::needs_array_len(u1 tag) {
58 return (tag == multi_branch_data_tag) || (tag == arg_info_data_tag) || (tag == parameters_type_data_tag);
59 }
60
61 // Perform generic initialization of the data. More specific
62 // initialization occurs in overrides of ProfileData::post_initialize.
63 void DataLayout::initialize(u1 tag, u2 bci, int cell_count) {
64 DataLayout temp;
65 temp._header._bits = (intptr_t)0;
66 temp._header._struct._tag = tag;
67 temp._header._struct._bci = bci;
68 // Write the header using a single intptr_t write. This ensures that if the layout is
69 // reinitialized readers will never see the transient state where the header is 0.
70 _header = temp._header;
71
72 for (int i = 0; i < cell_count; i++) {
73 set_cell_at(i, (intptr_t)0);
74 }
75 if (needs_array_len(tag)) {
76 set_cell_at(ArrayData::array_len_off_set, cell_count - 1); // -1 for header.
77 }
78 if (tag == call_type_data_tag) {
79 CallTypeData::initialize(this, cell_count);
80 } else if (tag == virtual_call_type_data_tag) {
81 VirtualCallTypeData::initialize(this, cell_count);
82 }
83 }
84
85 void DataLayout::clean_weak_klass_links(bool always_clean) {
86 ResourceMark m;
87 data_in()->clean_weak_klass_links(always_clean);
88 }
89
90
91 // ==================================================================
92 // ProfileData
93 //
94 // A ProfileData object is created to refer to a section of profiling
95 // data in a structured way.
96
97 // Constructor for invalid ProfileData.
98 ProfileData::ProfileData() {
99 _data = nullptr;
100 }
101
102 char* ProfileData::print_data_on_helper(const MethodData* md) const {
103 DataLayout* dp = md->extra_data_base();
104 DataLayout* end = md->args_data_limit();
105 stringStream ss;
106 for (;; dp = MethodData::next_extra(dp)) {
107 assert(dp < end, "moved past end of extra data");
108 switch(dp->tag()) {
109 case DataLayout::speculative_trap_data_tag:
110 if (dp->bci() == bci()) {
111 SpeculativeTrapData* data = new SpeculativeTrapData(dp);
112 int trap = data->trap_state();
113 char buf[100];
114 ss.print("trap/");
115 data->method()->print_short_name(&ss);
116 ss.print("(%s) ", Deoptimization::format_trap_state(buf, sizeof(buf), trap));
117 }
118 break;
119 case DataLayout::bit_data_tag:
120 break;
121 case DataLayout::no_tag:
122 case DataLayout::arg_info_data_tag:
123 return ss.as_string();
124 break;
125 default:
126 fatal("unexpected tag %d", dp->tag());
127 }
128 }
129 return nullptr;
130 }
131
132 void ProfileData::print_data_on(outputStream* st, const MethodData* md) const {
133 print_data_on(st, print_data_on_helper(md));
134 }
135
136 void ProfileData::print_shared(outputStream* st, const char* name, const char* extra) const {
137 st->print("bci: %d ", bci());
138 st->fill_to(tab_width_one + 1);
139 st->print("%s", name);
140 tab(st);
141 int trap = trap_state();
142 if (trap != 0) {
143 char buf[100];
144 st->print("trap(%s) ", Deoptimization::format_trap_state(buf, sizeof(buf), trap));
145 }
146 if (extra != nullptr) {
147 st->print("%s", extra);
148 }
149 int flags = data()->flags();
150 if (flags != 0) {
151 st->print("flags(%d) ", flags);
152 }
153 }
154
155 void ProfileData::tab(outputStream* st, bool first) const {
156 st->fill_to(first ? tab_width_one : tab_width_two);
157 }
158
159 // ==================================================================
160 // BitData
161 //
162 // A BitData corresponds to a one-bit flag. This is used to indicate
163 // whether a checkcast bytecode has seen a null value.
164
165
166 void BitData::print_data_on(outputStream* st, const char* extra) const {
167 print_shared(st, "BitData", extra);
168 st->cr();
169 }
170
171 // ==================================================================
172 // CounterData
173 //
174 // A CounterData corresponds to a simple counter.
175
176 void CounterData::print_data_on(outputStream* st, const char* extra) const {
177 print_shared(st, "CounterData", extra);
178 st->print_cr("count(%u)", count());
179 }
180
181 // ==================================================================
182 // JumpData
183 //
184 // A JumpData is used to access profiling information for a direct
185 // branch. It is a counter, used for counting the number of branches,
186 // plus a data displacement, used for realigning the data pointer to
187 // the corresponding target bci.
188
189 void JumpData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
190 assert(stream->bci() == bci(), "wrong pos");
191 int target;
192 Bytecodes::Code c = stream->code();
193 if (c == Bytecodes::_goto_w || c == Bytecodes::_jsr_w) {
194 target = stream->dest_w();
195 } else {
196 target = stream->dest();
197 }
198 int my_di = mdo->dp_to_di(dp());
199 int target_di = mdo->bci_to_di(target);
200 int offset = target_di - my_di;
201 set_displacement(offset);
202 }
203
204 void JumpData::print_data_on(outputStream* st, const char* extra) const {
205 print_shared(st, "JumpData", extra);
206 st->print_cr("taken(%u) displacement(%d)", taken(), displacement());
207 }
208
209 int TypeStackSlotEntries::compute_cell_count(Symbol* signature, bool include_receiver, int max) {
210 // Parameter profiling include the receiver
211 int args_count = include_receiver ? 1 : 0;
212 ResourceMark rm;
213 ReferenceArgumentCount rac(signature);
214 args_count += rac.count();
215 args_count = MIN2(args_count, max);
216 return args_count * per_arg_cell_count;
217 }
218
219 int TypeEntriesAtCall::compute_cell_count(BytecodeStream* stream) {
220 assert(Bytecodes::is_invoke(stream->code()), "should be invoke");
221 assert(TypeStackSlotEntries::per_arg_count() > ReturnTypeEntry::static_cell_count(), "code to test for arguments/results broken");
222 const methodHandle m = stream->method();
223 int bci = stream->bci();
224 Bytecode_invoke inv(m, bci);
225 int args_cell = 0;
226 if (MethodData::profile_arguments_for_invoke(m, bci)) {
227 args_cell = TypeStackSlotEntries::compute_cell_count(inv.signature(), false, TypeProfileArgsLimit);
228 }
229 int ret_cell = 0;
230 if (MethodData::profile_return_for_invoke(m, bci) && is_reference_type(inv.result_type())) {
231 ret_cell = ReturnTypeEntry::static_cell_count();
232 }
233 int header_cell = 0;
234 if (args_cell + ret_cell > 0) {
235 header_cell = header_cell_count();
236 }
237
238 return header_cell + args_cell + ret_cell;
239 }
240
241 class ArgumentOffsetComputer : public SignatureIterator {
242 private:
243 int _max;
244 int _offset;
245 GrowableArray<int> _offsets;
246
247 friend class SignatureIterator; // so do_parameters_on can call do_type
248 void do_type(BasicType type) {
249 if (is_reference_type(type) && _offsets.length() < _max) {
250 _offsets.push(_offset);
251 }
252 _offset += parameter_type_word_count(type);
253 }
254
255 public:
256 ArgumentOffsetComputer(Symbol* signature, int max)
257 : SignatureIterator(signature),
258 _max(max), _offset(0),
259 _offsets(max) {
260 do_parameters_on(this); // non-virtual template execution
261 }
262
263 int off_at(int i) const { return _offsets.at(i); }
264 };
265
266 void TypeStackSlotEntries::post_initialize(Symbol* signature, bool has_receiver, bool include_receiver) {
267 ResourceMark rm;
268 int start = 0;
269 // Parameter profiling include the receiver
270 if (include_receiver && has_receiver) {
271 set_stack_slot(0, 0);
272 set_type(0, type_none());
273 start += 1;
274 }
275 ArgumentOffsetComputer aos(signature, _number_of_entries-start);
276 for (int i = start; i < _number_of_entries; i++) {
277 set_stack_slot(i, aos.off_at(i-start) + (has_receiver ? 1 : 0));
278 set_type(i, type_none());
279 }
280 }
281
282 void CallTypeData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
283 assert(Bytecodes::is_invoke(stream->code()), "should be invoke");
284 Bytecode_invoke inv(stream->method(), stream->bci());
285
286 if (has_arguments()) {
287 #ifdef ASSERT
288 ResourceMark rm;
289 ReferenceArgumentCount rac(inv.signature());
290 int count = MIN2(rac.count(), (int)TypeProfileArgsLimit);
291 assert(count > 0, "room for args type but none found?");
292 check_number_of_arguments(count);
293 #endif
294 _args.post_initialize(inv.signature(), inv.has_receiver(), false);
295 }
296
297 if (has_return()) {
298 assert(is_reference_type(inv.result_type()), "room for a ret type but doesn't return obj?");
299 _ret.post_initialize();
300 }
301 }
302
303 void VirtualCallTypeData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
304 assert(Bytecodes::is_invoke(stream->code()), "should be invoke");
305 Bytecode_invoke inv(stream->method(), stream->bci());
306
307 if (has_arguments()) {
308 #ifdef ASSERT
309 ResourceMark rm;
310 ReferenceArgumentCount rac(inv.signature());
311 int count = MIN2(rac.count(), (int)TypeProfileArgsLimit);
312 assert(count > 0, "room for args type but none found?");
313 check_number_of_arguments(count);
314 #endif
315 _args.post_initialize(inv.signature(), inv.has_receiver(), false);
316 }
317
318 if (has_return()) {
319 assert(is_reference_type(inv.result_type()), "room for a ret type but doesn't return obj?");
320 _ret.post_initialize();
321 }
322 }
323
324 static bool is_excluded(Klass* k) {
325 #if INCLUDE_CDS
326 if (CDSConfig::is_at_aot_safepoint()) {
327 // Check for CDS exclusion only at CDS safe point.
328 if (k->is_instance_klass() && !InstanceKlass::cast(k)->is_loaded()) {
329 log_debug(aot, training)("Purged %s from MDO: unloaded class", k->name()->as_C_string());
330 return true;
331 } else {
332 bool excluded = SystemDictionaryShared::should_be_excluded(k);
333 if (excluded) {
334 log_debug(aot, training)("Purged %s from MDO: excluded class", k->name()->as_C_string());
335 }
336 return excluded;
337 }
338 }
339 #endif
340 return false;
341 }
342
343 void TypeStackSlotEntries::clean_weak_klass_links(bool always_clean) {
344 for (int i = 0; i < _number_of_entries; i++) {
345 intptr_t p = type(i);
346 Klass* k = (Klass*)klass_part(p);
347 if (k != nullptr) {
348 if (!always_clean && k->is_instance_klass() && InstanceKlass::cast(k)->is_not_initialized()) {
349 continue; // skip not-yet-initialized classes // TODO: maybe clear the slot instead?
350 }
351 if (always_clean || !k->is_loader_present_and_alive() || is_excluded(k)) {
352 set_type(i, with_status((Klass*)nullptr, p));
353 }
354 }
355 }
356 }
357
358 void TypeStackSlotEntries::metaspace_pointers_do(MetaspaceClosure* it) {
359 for (int i = 0; i < _number_of_entries; i++) {
360 Klass** k = (Klass**)type_adr(i); // tagged
361 it->push(k);
362 }
363 }
364
365 void ReturnTypeEntry::clean_weak_klass_links(bool always_clean) {
366 intptr_t p = type();
367 Klass* k = (Klass*)klass_part(p);
368 if (k != nullptr) {
369 if (!always_clean && k->is_instance_klass() && InstanceKlass::cast(k)->is_not_initialized()) {
370 return; // skip not-yet-initialized classes // TODO: maybe clear the slot instead?
371 }
372 if (always_clean || !k->is_loader_present_and_alive() || is_excluded(k)) {
373 set_type(with_status((Klass*)nullptr, p));
374 }
375 }
376 }
377
378 void ReturnTypeEntry::metaspace_pointers_do(MetaspaceClosure* it) {
379 Klass** k = (Klass**)type_adr(); // tagged
380 it->push(k);
381 }
382
383 bool TypeEntriesAtCall::return_profiling_enabled() {
384 return MethodData::profile_return();
385 }
386
387 bool TypeEntriesAtCall::arguments_profiling_enabled() {
388 return MethodData::profile_arguments();
389 }
390
391 void TypeEntries::print_klass(outputStream* st, intptr_t k) {
392 if (is_type_none(k)) {
393 st->print("none");
394 } else if (is_type_unknown(k)) {
395 st->print("unknown");
396 } else {
397 valid_klass(k)->print_value_on(st);
398 }
399 if (was_null_seen(k)) {
400 st->print(" (null seen)");
401 }
402 }
403
404 void TypeStackSlotEntries::print_data_on(outputStream* st) const {
405 for (int i = 0; i < _number_of_entries; i++) {
406 _pd->tab(st);
407 st->print("%d: stack(%u) ", i, stack_slot(i));
408 print_klass(st, type(i));
409 st->cr();
410 }
411 }
412
413 void ReturnTypeEntry::print_data_on(outputStream* st) const {
414 _pd->tab(st);
415 print_klass(st, type());
416 st->cr();
417 }
418
419 void CallTypeData::print_data_on(outputStream* st, const char* extra) const {
420 CounterData::print_data_on(st, extra);
421 if (has_arguments()) {
422 tab(st, true);
423 st->print("argument types");
424 _args.print_data_on(st);
425 }
426 if (has_return()) {
427 tab(st, true);
428 st->print("return type");
429 _ret.print_data_on(st);
430 }
431 }
432
433 void VirtualCallTypeData::print_data_on(outputStream* st, const char* extra) const {
434 VirtualCallData::print_data_on(st, extra);
435 if (has_arguments()) {
436 tab(st, true);
437 st->print("argument types");
438 _args.print_data_on(st);
439 }
440 if (has_return()) {
441 tab(st, true);
442 st->print("return type");
443 _ret.print_data_on(st);
444 }
445 }
446
447 // ==================================================================
448 // ReceiverTypeData
449 //
450 // A ReceiverTypeData is used to access profiling information about a
451 // dynamic type check. It consists of a counter which counts the total times
452 // that the check is reached, and a series of (Klass*, count) pairs
453 // which are used to store a type profile for the receiver of the check.
454
455 void ReceiverTypeData::clean_weak_klass_links(bool always_clean) {
456 for (uint row = 0; row < row_limit(); row++) {
457 Klass* p = receiver(row);
458 if (p != nullptr) {
459 if (!always_clean && p->is_instance_klass() && InstanceKlass::cast(p)->is_not_initialized()) {
460 continue; // skip not-yet-initialized classes // TODO: maybe clear the slot instead?
461 }
462 if (always_clean || !p->is_loader_present_and_alive() || is_excluded(p)) {
463 clear_row(row);
464 }
465 }
466 }
467 }
468
469 void ReceiverTypeData::metaspace_pointers_do(MetaspaceClosure *it) {
470 for (uint row = 0; row < row_limit(); row++) {
471 Klass** recv = (Klass**)intptr_at_adr(receiver_cell_index(row));
472 it->push(recv);
473 }
474 }
475
476 void ReceiverTypeData::print_receiver_data_on(outputStream* st) const {
477 uint row;
478 int entries = 0;
479 for (row = 0; row < row_limit(); row++) {
480 if (receiver(row) != nullptr) entries++;
481 }
482 st->print_cr("count(%u) entries(%u)", count(), entries);
483 int total = count();
484 for (row = 0; row < row_limit(); row++) {
485 if (receiver(row) != nullptr) {
486 total += receiver_count(row);
487 }
488 }
489 for (row = 0; row < row_limit(); row++) {
490 if (receiver(row) != nullptr) {
491 tab(st);
492 receiver(row)->print_value_on(st);
493 st->print_cr("(%u %4.2f)", receiver_count(row), (float) receiver_count(row) / (float) total);
494 }
495 }
496 }
497 void ReceiverTypeData::print_data_on(outputStream* st, const char* extra) const {
498 print_shared(st, "ReceiverTypeData", extra);
499 print_receiver_data_on(st);
500 }
501
502 void VirtualCallData::print_data_on(outputStream* st, const char* extra) const {
503 print_shared(st, "VirtualCallData", extra);
504 print_receiver_data_on(st);
505 }
506
507 // ==================================================================
508 // RetData
509 //
510 // A RetData is used to access profiling information for a ret bytecode.
511 // It is composed of a count of the number of times that the ret has
512 // been executed, followed by a series of triples of the form
513 // (bci, count, di) which count the number of times that some bci was the
514 // target of the ret and cache a corresponding displacement.
515
516 void RetData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
517 for (uint row = 0; row < row_limit(); row++) {
518 set_bci_displacement(row, -1);
519 set_bci(row, no_bci);
520 }
521 // release so other threads see a consistent state. bci is used as
522 // a valid flag for bci_displacement.
523 OrderAccess::release();
524 }
525
526 // This routine needs to atomically update the RetData structure, so the
527 // caller needs to hold the RetData_lock before it gets here. Since taking
528 // the lock can block (and allow GC) and since RetData is a ProfileData is a
529 // wrapper around a derived oop, taking the lock in _this_ method will
530 // basically cause the 'this' pointer's _data field to contain junk after the
531 // lock. We require the caller to take the lock before making the ProfileData
532 // structure. Currently the only caller is InterpreterRuntime::update_mdp_for_ret
533 address RetData::fixup_ret(int return_bci, MethodData* h_mdo) {
534 // First find the mdp which corresponds to the return bci.
535 address mdp = h_mdo->bci_to_dp(return_bci);
536
537 // Now check to see if any of the cache slots are open.
538 for (uint row = 0; row < row_limit(); row++) {
539 if (bci(row) == no_bci) {
540 set_bci_displacement(row, checked_cast<int>(mdp - dp()));
541 set_bci_count(row, DataLayout::counter_increment);
542 // Barrier to ensure displacement is written before the bci; allows
543 // the interpreter to read displacement without fear of race condition.
544 release_set_bci(row, return_bci);
545 break;
546 }
547 }
548 return mdp;
549 }
550
551 void RetData::print_data_on(outputStream* st, const char* extra) const {
552 print_shared(st, "RetData", extra);
553 uint row;
554 int entries = 0;
555 for (row = 0; row < row_limit(); row++) {
556 if (bci(row) != no_bci) entries++;
557 }
558 st->print_cr("count(%u) entries(%u)", count(), entries);
559 for (row = 0; row < row_limit(); row++) {
560 if (bci(row) != no_bci) {
561 tab(st);
562 st->print_cr("bci(%d: count(%u) displacement(%d))",
563 bci(row), bci_count(row), bci_displacement(row));
564 }
565 }
566 }
567
568 // ==================================================================
569 // BranchData
570 //
571 // A BranchData is used to access profiling data for a two-way branch.
572 // It consists of taken and not_taken counts as well as a data displacement
573 // for the taken case.
574
575 void BranchData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
576 assert(stream->bci() == bci(), "wrong pos");
577 int target = stream->dest();
578 int my_di = mdo->dp_to_di(dp());
579 int target_di = mdo->bci_to_di(target);
580 int offset = target_di - my_di;
581 set_displacement(offset);
582 }
583
584 void BranchData::print_data_on(outputStream* st, const char* extra) const {
585 print_shared(st, "BranchData", extra);
586 st->print_cr("taken(%u) displacement(%d)",
587 taken(), displacement());
588 tab(st);
589 st->print_cr("not taken(%u)", not_taken());
590 }
591
592 // ==================================================================
593 // MultiBranchData
594 //
595 // A MultiBranchData is used to access profiling information for
596 // a multi-way branch (*switch bytecodes). It consists of a series
597 // of (count, displacement) pairs, which count the number of times each
598 // case was taken and specify the data displacement for each branch target.
599
600 int MultiBranchData::compute_cell_count(BytecodeStream* stream) {
601 int cell_count = 0;
602 if (stream->code() == Bytecodes::_tableswitch) {
603 Bytecode_tableswitch sw(stream->method()(), stream->bcp());
604 cell_count = 1 + per_case_cell_count * (1 + sw.length()); // 1 for default
605 } else {
606 Bytecode_lookupswitch sw(stream->method()(), stream->bcp());
607 cell_count = 1 + per_case_cell_count * (sw.number_of_pairs() + 1); // 1 for default
608 }
609 return cell_count;
610 }
611
612 void MultiBranchData::post_initialize(BytecodeStream* stream,
613 MethodData* mdo) {
614 assert(stream->bci() == bci(), "wrong pos");
615 int target;
616 int my_di;
617 int target_di;
618 int offset;
619 if (stream->code() == Bytecodes::_tableswitch) {
620 Bytecode_tableswitch sw(stream->method()(), stream->bcp());
621 int len = sw.length();
622 assert(array_len() == per_case_cell_count * (len + 1), "wrong len");
623 for (int count = 0; count < len; count++) {
624 target = sw.dest_offset_at(count) + bci();
625 my_di = mdo->dp_to_di(dp());
626 target_di = mdo->bci_to_di(target);
627 offset = target_di - my_di;
628 set_displacement_at(count, offset);
629 }
630 target = sw.default_offset() + bci();
631 my_di = mdo->dp_to_di(dp());
632 target_di = mdo->bci_to_di(target);
633 offset = target_di - my_di;
634 set_default_displacement(offset);
635
636 } else {
637 Bytecode_lookupswitch sw(stream->method()(), stream->bcp());
638 int npairs = sw.number_of_pairs();
639 assert(array_len() == per_case_cell_count * (npairs + 1), "wrong len");
640 for (int count = 0; count < npairs; count++) {
641 LookupswitchPair pair = sw.pair_at(count);
642 target = pair.offset() + bci();
643 my_di = mdo->dp_to_di(dp());
644 target_di = mdo->bci_to_di(target);
645 offset = target_di - my_di;
646 set_displacement_at(count, offset);
647 }
648 target = sw.default_offset() + bci();
649 my_di = mdo->dp_to_di(dp());
650 target_di = mdo->bci_to_di(target);
651 offset = target_di - my_di;
652 set_default_displacement(offset);
653 }
654 }
655
656 void MultiBranchData::print_data_on(outputStream* st, const char* extra) const {
657 print_shared(st, "MultiBranchData", extra);
658 st->print_cr("default_count(%u) displacement(%d)",
659 default_count(), default_displacement());
660 int cases = number_of_cases();
661 for (int i = 0; i < cases; i++) {
662 tab(st);
663 st->print_cr("count(%u) displacement(%d)",
664 count_at(i), displacement_at(i));
665 }
666 }
667
668 void ArgInfoData::print_data_on(outputStream* st, const char* extra) const {
669 print_shared(st, "ArgInfoData", extra);
670 int nargs = number_of_args();
671 for (int i = 0; i < nargs; i++) {
672 st->print(" 0x%x", arg_modified(i));
673 }
674 st->cr();
675 }
676
677 int ParametersTypeData::compute_cell_count(Method* m) {
678 if (!MethodData::profile_parameters_for_method(methodHandle(Thread::current(), m))) {
679 return 0;
680 }
681 int max = TypeProfileParmsLimit == -1 ? INT_MAX : TypeProfileParmsLimit;
682 int obj_args = TypeStackSlotEntries::compute_cell_count(m->signature(), !m->is_static(), max);
683 if (obj_args > 0) {
684 return obj_args + 1; // 1 cell for array len
685 }
686 return 0;
687 }
688
689 void ParametersTypeData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
690 _parameters.post_initialize(mdo->method()->signature(), !mdo->method()->is_static(), true);
691 }
692
693 bool ParametersTypeData::profiling_enabled() {
694 return MethodData::profile_parameters();
695 }
696
697 void ParametersTypeData::print_data_on(outputStream* st, const char* extra) const {
698 print_shared(st, "ParametersTypeData", extra);
699 tab(st);
700 _parameters.print_data_on(st);
701 st->cr();
702 }
703
704 void SpeculativeTrapData::metaspace_pointers_do(MetaspaceClosure* it) {
705 Method** m = (Method**)intptr_at_adr(speculative_trap_method);
706 it->push(m);
707 }
708
709 void SpeculativeTrapData::print_data_on(outputStream* st, const char* extra) const {
710 print_shared(st, "SpeculativeTrapData", extra);
711 tab(st);
712 method()->print_short_name(st);
713 st->cr();
714 }
715
716 // ==================================================================
717 // MethodData*
718 //
719 // A MethodData* holds information which has been collected about
720 // a method.
721
722 MethodData* MethodData::allocate(ClassLoaderData* loader_data, const methodHandle& method, TRAPS) {
723 assert(!THREAD->owns_locks(), "Should not own any locks");
724 int size = MethodData::compute_allocation_size_in_words(method);
725
726 return new (loader_data, size, MetaspaceObj::MethodDataType, THREAD)
727 MethodData(method);
728 }
729
730 int MethodData::bytecode_cell_count(Bytecodes::Code code) {
731 switch (code) {
732 case Bytecodes::_checkcast:
733 case Bytecodes::_instanceof:
734 case Bytecodes::_aastore:
735 if (TypeProfileCasts) {
736 return ReceiverTypeData::static_cell_count();
737 } else {
738 return BitData::static_cell_count();
739 }
740 case Bytecodes::_invokespecial:
741 case Bytecodes::_invokestatic:
742 if (MethodData::profile_arguments() || MethodData::profile_return()) {
743 return variable_cell_count;
744 } else {
745 return CounterData::static_cell_count();
746 }
747 case Bytecodes::_goto:
748 case Bytecodes::_goto_w:
749 case Bytecodes::_jsr:
750 case Bytecodes::_jsr_w:
751 return JumpData::static_cell_count();
752 case Bytecodes::_invokevirtual:
753 case Bytecodes::_invokeinterface:
754 if (MethodData::profile_arguments() || MethodData::profile_return()) {
755 return variable_cell_count;
756 } else {
757 return VirtualCallData::static_cell_count();
758 }
759 case Bytecodes::_invokedynamic:
760 if (MethodData::profile_arguments() || MethodData::profile_return()) {
761 return variable_cell_count;
762 } else {
763 return CounterData::static_cell_count();
764 }
765 case Bytecodes::_ret:
766 return RetData::static_cell_count();
767 case Bytecodes::_ifeq:
768 case Bytecodes::_ifne:
769 case Bytecodes::_iflt:
770 case Bytecodes::_ifge:
771 case Bytecodes::_ifgt:
772 case Bytecodes::_ifle:
773 case Bytecodes::_if_icmpeq:
774 case Bytecodes::_if_icmpne:
775 case Bytecodes::_if_icmplt:
776 case Bytecodes::_if_icmpge:
777 case Bytecodes::_if_icmpgt:
778 case Bytecodes::_if_icmple:
779 case Bytecodes::_if_acmpeq:
780 case Bytecodes::_if_acmpne:
781 case Bytecodes::_ifnull:
782 case Bytecodes::_ifnonnull:
783 return BranchData::static_cell_count();
784 case Bytecodes::_lookupswitch:
785 case Bytecodes::_tableswitch:
786 return variable_cell_count;
787 default:
788 return no_profile_data;
789 }
790 }
791
792 // Compute the size of the profiling information corresponding to
793 // the current bytecode.
794 int MethodData::compute_data_size(BytecodeStream* stream) {
795 int cell_count = bytecode_cell_count(stream->code());
796 if (cell_count == no_profile_data) {
797 return 0;
798 }
799 if (cell_count == variable_cell_count) {
800 switch (stream->code()) {
801 case Bytecodes::_lookupswitch:
802 case Bytecodes::_tableswitch:
803 cell_count = MultiBranchData::compute_cell_count(stream);
804 break;
805 case Bytecodes::_invokespecial:
806 case Bytecodes::_invokestatic:
807 case Bytecodes::_invokedynamic:
808 assert(MethodData::profile_arguments() || MethodData::profile_return(), "should be collecting args profile");
809 if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
810 profile_return_for_invoke(stream->method(), stream->bci())) {
811 cell_count = CallTypeData::compute_cell_count(stream);
812 } else {
813 cell_count = CounterData::static_cell_count();
814 }
815 break;
816 case Bytecodes::_invokevirtual:
817 case Bytecodes::_invokeinterface: {
818 assert(MethodData::profile_arguments() || MethodData::profile_return(), "should be collecting args profile");
819 if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
820 profile_return_for_invoke(stream->method(), stream->bci())) {
821 cell_count = VirtualCallTypeData::compute_cell_count(stream);
822 } else {
823 cell_count = VirtualCallData::static_cell_count();
824 }
825 break;
826 }
827 default:
828 fatal("unexpected bytecode for var length profile data");
829 }
830 }
831 // Note: cell_count might be zero, meaning that there is just
832 // a DataLayout header, with no extra cells.
833 assert(cell_count >= 0, "sanity");
834 return DataLayout::compute_size_in_bytes(cell_count);
835 }
836
837 bool MethodData::is_speculative_trap_bytecode(Bytecodes::Code code) {
838 // Bytecodes for which we may use speculation
839 switch (code) {
840 case Bytecodes::_checkcast:
841 case Bytecodes::_instanceof:
842 case Bytecodes::_aastore:
843 case Bytecodes::_invokevirtual:
844 case Bytecodes::_invokeinterface:
845 case Bytecodes::_if_acmpeq:
846 case Bytecodes::_if_acmpne:
847 case Bytecodes::_ifnull:
848 case Bytecodes::_ifnonnull:
849 case Bytecodes::_invokestatic:
850 #ifdef COMPILER2
851 if (CompilerConfig::is_c2_enabled()) {
852 return UseTypeSpeculation;
853 }
854 #endif
855 default:
856 return false;
857 }
858 return false;
859 }
860
861 #if INCLUDE_JVMCI
862
863 void* FailedSpeculation::operator new(size_t size, size_t fs_size) throw() {
864 return CHeapObj<mtCompiler>::operator new(fs_size, std::nothrow);
865 }
866
867 FailedSpeculation::FailedSpeculation(address speculation, int speculation_len) : _data_len(speculation_len), _next(nullptr) {
868 memcpy(data(), speculation, speculation_len);
869 }
870
871 // A heuristic check to detect nmethods that outlive a failed speculations list.
872 static void guarantee_failed_speculations_alive(nmethod* nm, FailedSpeculation** failed_speculations_address) {
873 jlong head = (jlong)(address) *failed_speculations_address;
874 if ((head & 0x1) == 0x1) {
875 stringStream st;
876 if (nm != nullptr) {
877 st.print("%d", nm->compile_id());
878 Method* method = nm->method();
879 st.print_raw("{");
880 if (method != nullptr) {
881 method->print_name(&st);
882 } else {
883 const char* jvmci_name = nm->jvmci_name();
884 if (jvmci_name != nullptr) {
885 st.print_raw(jvmci_name);
886 }
887 }
888 st.print_raw("}");
889 } else {
890 st.print("<unknown>");
891 }
892 fatal("Adding to failed speculations list that appears to have been freed. Source: %s", st.as_string());
893 }
894 }
895
896 bool FailedSpeculation::add_failed_speculation(nmethod* nm, FailedSpeculation** failed_speculations_address, address speculation, int speculation_len) {
897 assert(failed_speculations_address != nullptr, "must be");
898 size_t fs_size = sizeof(FailedSpeculation) + speculation_len;
899
900 guarantee_failed_speculations_alive(nm, failed_speculations_address);
901
902 FailedSpeculation** cursor = failed_speculations_address;
903 FailedSpeculation* fs = nullptr;
904 do {
905 if (*cursor == nullptr) {
906 if (fs == nullptr) {
907 // lazily allocate FailedSpeculation
908 fs = new (fs_size) FailedSpeculation(speculation, speculation_len);
909 if (fs == nullptr) {
910 // no memory -> ignore failed speculation
911 return false;
912 }
913 guarantee(is_aligned(fs, sizeof(FailedSpeculation*)), "FailedSpeculation objects must be pointer aligned");
914 }
915 FailedSpeculation* old_fs = AtomicAccess::cmpxchg(cursor, (FailedSpeculation*) nullptr, fs);
916 if (old_fs == nullptr) {
917 // Successfully appended fs to end of the list
918 return true;
919 }
920 }
921 guarantee(*cursor != nullptr, "cursor must point to non-null FailedSpeculation");
922 // check if the current entry matches this thread's failed speculation
923 if ((*cursor)->data_len() == speculation_len && memcmp(speculation, (*cursor)->data(), speculation_len) == 0) {
924 if (fs != nullptr) {
925 delete fs;
926 }
927 return false;
928 }
929 cursor = (*cursor)->next_adr();
930 } while (true);
931 }
932
933 void FailedSpeculation::free_failed_speculations(FailedSpeculation** failed_speculations_address) {
934 assert(failed_speculations_address != nullptr, "must be");
935 FailedSpeculation* fs = *failed_speculations_address;
936 while (fs != nullptr) {
937 FailedSpeculation* next = fs->next();
938 delete fs;
939 fs = next;
940 }
941
942 // Write an unaligned value to failed_speculations_address to denote
943 // that it is no longer a valid pointer. This is allows for the check
944 // in add_failed_speculation against adding to a freed failed
945 // speculations list.
946 long* head = (long*) failed_speculations_address;
947 (*head) = (*head) | 0x1;
948 }
949 #endif // INCLUDE_JVMCI
950
951 int MethodData::compute_extra_data_count(int data_size, int empty_bc_count, bool needs_speculative_traps) {
952 #if INCLUDE_JVMCI
953 if (ProfileTraps) {
954 // Assume that up to 30% of the possibly trapping BCIs with no MDP will need to allocate one.
955 int extra_data_count = MIN2(empty_bc_count, MAX2(4, (empty_bc_count * 30) / 100));
956
957 // Make sure we have a minimum number of extra data slots to
958 // allocate SpeculativeTrapData entries. We would want to have one
959 // entry per compilation that inlines this method and for which
960 // some type speculation assumption fails. So the room we need for
961 // the SpeculativeTrapData entries doesn't directly depend on the
962 // size of the method. Because it's hard to estimate, we reserve
963 // space for an arbitrary number of entries.
964 int spec_data_count = (needs_speculative_traps ? SpecTrapLimitExtraEntries : 0) *
965 (SpeculativeTrapData::static_cell_count() + DataLayout::header_size_in_cells());
966
967 return MAX2(extra_data_count, spec_data_count);
968 } else {
969 return 0;
970 }
971 #else // INCLUDE_JVMCI
972 if (ProfileTraps) {
973 // Assume that up to 3% of BCIs with no MDP will need to allocate one.
974 int extra_data_count = (uint)(empty_bc_count * 3) / 128 + 1;
975 // If the method is large, let the extra BCIs grow numerous (to ~1%).
976 int one_percent_of_data
977 = (uint)data_size / (DataLayout::header_size_in_bytes()*128);
978 if (extra_data_count < one_percent_of_data)
979 extra_data_count = one_percent_of_data;
980 if (extra_data_count > empty_bc_count)
981 extra_data_count = empty_bc_count; // no need for more
982
983 // Make sure we have a minimum number of extra data slots to
984 // allocate SpeculativeTrapData entries. We would want to have one
985 // entry per compilation that inlines this method and for which
986 // some type speculation assumption fails. So the room we need for
987 // the SpeculativeTrapData entries doesn't directly depend on the
988 // size of the method. Because it's hard to estimate, we reserve
989 // space for an arbitrary number of entries.
990 int spec_data_count = (needs_speculative_traps ? SpecTrapLimitExtraEntries : 0) *
991 (SpeculativeTrapData::static_cell_count() + DataLayout::header_size_in_cells());
992
993 return MAX2(extra_data_count, spec_data_count);
994 } else {
995 return 0;
996 }
997 #endif // INCLUDE_JVMCI
998 }
999
1000 // Compute the size of the MethodData* necessary to store
1001 // profiling information about a given method. Size is in bytes.
1002 int MethodData::compute_allocation_size_in_bytes(const methodHandle& method) {
1003 int data_size = 0;
1004 BytecodeStream stream(method);
1005 Bytecodes::Code c;
1006 int empty_bc_count = 0; // number of bytecodes lacking data
1007 bool needs_speculative_traps = false;
1008 while ((c = stream.next()) >= 0) {
1009 int size_in_bytes = compute_data_size(&stream);
1010 data_size += size_in_bytes;
1011 if (size_in_bytes == 0 JVMCI_ONLY(&& Bytecodes::can_trap(c))) empty_bc_count += 1;
1012 needs_speculative_traps = needs_speculative_traps || is_speculative_trap_bytecode(c);
1013 }
1014 int object_size = in_bytes(data_offset()) + data_size;
1015
1016 // Add some extra DataLayout cells (at least one) to track stray traps.
1017 int extra_data_count = compute_extra_data_count(data_size, empty_bc_count, needs_speculative_traps);
1018 object_size += extra_data_count * DataLayout::compute_size_in_bytes(0);
1019
1020 // Add a cell to record information about modified arguments.
1021 int arg_size = method->size_of_parameters();
1022 object_size += DataLayout::compute_size_in_bytes(arg_size+1);
1023
1024 // Reserve room for an area of the MDO dedicated to profiling of
1025 // parameters
1026 int args_cell = ParametersTypeData::compute_cell_count(method());
1027 if (args_cell > 0) {
1028 object_size += DataLayout::compute_size_in_bytes(args_cell);
1029 }
1030
1031 if (ProfileExceptionHandlers && method()->has_exception_handler()) {
1032 int num_exception_handlers = method()->exception_table_length();
1033 object_size += num_exception_handlers * single_exception_handler_data_size();
1034 }
1035
1036 return object_size;
1037 }
1038
1039 // Compute the size of the MethodData* necessary to store
1040 // profiling information about a given method. Size is in words
1041 int MethodData::compute_allocation_size_in_words(const methodHandle& method) {
1042 int byte_size = compute_allocation_size_in_bytes(method);
1043 int word_size = align_up(byte_size, BytesPerWord) / BytesPerWord;
1044 return align_metadata_size(word_size);
1045 }
1046
1047 // Initialize an individual data segment. Returns the size of
1048 // the segment in bytes.
1049 int MethodData::initialize_data(BytecodeStream* stream,
1050 int data_index) {
1051 int cell_count = -1;
1052 u1 tag = DataLayout::no_tag;
1053 DataLayout* data_layout = data_layout_at(data_index);
1054 Bytecodes::Code c = stream->code();
1055 switch (c) {
1056 case Bytecodes::_checkcast:
1057 case Bytecodes::_instanceof:
1058 case Bytecodes::_aastore:
1059 if (TypeProfileCasts) {
1060 cell_count = ReceiverTypeData::static_cell_count();
1061 tag = DataLayout::receiver_type_data_tag;
1062 } else {
1063 cell_count = BitData::static_cell_count();
1064 tag = DataLayout::bit_data_tag;
1065 }
1066 break;
1067 case Bytecodes::_invokespecial:
1068 case Bytecodes::_invokestatic: {
1069 int counter_data_cell_count = CounterData::static_cell_count();
1070 if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
1071 profile_return_for_invoke(stream->method(), stream->bci())) {
1072 cell_count = CallTypeData::compute_cell_count(stream);
1073 } else {
1074 cell_count = counter_data_cell_count;
1075 }
1076 if (cell_count > counter_data_cell_count) {
1077 tag = DataLayout::call_type_data_tag;
1078 } else {
1079 tag = DataLayout::counter_data_tag;
1080 }
1081 break;
1082 }
1083 case Bytecodes::_goto:
1084 case Bytecodes::_goto_w:
1085 case Bytecodes::_jsr:
1086 case Bytecodes::_jsr_w:
1087 cell_count = JumpData::static_cell_count();
1088 tag = DataLayout::jump_data_tag;
1089 break;
1090 case Bytecodes::_invokevirtual:
1091 case Bytecodes::_invokeinterface: {
1092 int virtual_call_data_cell_count = VirtualCallData::static_cell_count();
1093 if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
1094 profile_return_for_invoke(stream->method(), stream->bci())) {
1095 cell_count = VirtualCallTypeData::compute_cell_count(stream);
1096 } else {
1097 cell_count = virtual_call_data_cell_count;
1098 }
1099 if (cell_count > virtual_call_data_cell_count) {
1100 tag = DataLayout::virtual_call_type_data_tag;
1101 } else {
1102 tag = DataLayout::virtual_call_data_tag;
1103 }
1104 break;
1105 }
1106 case Bytecodes::_invokedynamic: {
1107 // %%% should make a type profile for any invokedynamic that takes a ref argument
1108 int counter_data_cell_count = CounterData::static_cell_count();
1109 if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
1110 profile_return_for_invoke(stream->method(), stream->bci())) {
1111 cell_count = CallTypeData::compute_cell_count(stream);
1112 } else {
1113 cell_count = counter_data_cell_count;
1114 }
1115 if (cell_count > counter_data_cell_count) {
1116 tag = DataLayout::call_type_data_tag;
1117 } else {
1118 tag = DataLayout::counter_data_tag;
1119 }
1120 break;
1121 }
1122 case Bytecodes::_ret:
1123 cell_count = RetData::static_cell_count();
1124 tag = DataLayout::ret_data_tag;
1125 break;
1126 case Bytecodes::_ifeq:
1127 case Bytecodes::_ifne:
1128 case Bytecodes::_iflt:
1129 case Bytecodes::_ifge:
1130 case Bytecodes::_ifgt:
1131 case Bytecodes::_ifle:
1132 case Bytecodes::_if_icmpeq:
1133 case Bytecodes::_if_icmpne:
1134 case Bytecodes::_if_icmplt:
1135 case Bytecodes::_if_icmpge:
1136 case Bytecodes::_if_icmpgt:
1137 case Bytecodes::_if_icmple:
1138 case Bytecodes::_if_acmpeq:
1139 case Bytecodes::_if_acmpne:
1140 case Bytecodes::_ifnull:
1141 case Bytecodes::_ifnonnull:
1142 cell_count = BranchData::static_cell_count();
1143 tag = DataLayout::branch_data_tag;
1144 break;
1145 case Bytecodes::_lookupswitch:
1146 case Bytecodes::_tableswitch:
1147 cell_count = MultiBranchData::compute_cell_count(stream);
1148 tag = DataLayout::multi_branch_data_tag;
1149 break;
1150 default:
1151 break;
1152 }
1153 assert(tag == DataLayout::multi_branch_data_tag ||
1154 ((MethodData::profile_arguments() || MethodData::profile_return()) &&
1155 (tag == DataLayout::call_type_data_tag ||
1156 tag == DataLayout::counter_data_tag ||
1157 tag == DataLayout::virtual_call_type_data_tag ||
1158 tag == DataLayout::virtual_call_data_tag)) ||
1159 cell_count == bytecode_cell_count(c), "cell counts must agree");
1160 if (cell_count >= 0) {
1161 assert(tag != DataLayout::no_tag, "bad tag");
1162 assert(bytecode_has_profile(c), "agree w/ BHP");
1163 data_layout->initialize(tag, checked_cast<u2>(stream->bci()), cell_count);
1164 return DataLayout::compute_size_in_bytes(cell_count);
1165 } else {
1166 assert(!bytecode_has_profile(c), "agree w/ !BHP");
1167 return 0;
1168 }
1169 }
1170
1171 // Get the data at an arbitrary (sort of) data index.
1172 ProfileData* MethodData::data_at(int data_index) const {
1173 if (out_of_bounds(data_index)) {
1174 return nullptr;
1175 }
1176 DataLayout* data_layout = data_layout_at(data_index);
1177 return data_layout->data_in();
1178 }
1179
1180 int DataLayout::cell_count() {
1181 switch (tag()) {
1182 case DataLayout::no_tag:
1183 default:
1184 ShouldNotReachHere();
1185 return 0;
1186 case DataLayout::bit_data_tag:
1187 return BitData::static_cell_count();
1188 case DataLayout::counter_data_tag:
1189 return CounterData::static_cell_count();
1190 case DataLayout::jump_data_tag:
1191 return JumpData::static_cell_count();
1192 case DataLayout::receiver_type_data_tag:
1193 return ReceiverTypeData::static_cell_count();
1194 case DataLayout::virtual_call_data_tag:
1195 return VirtualCallData::static_cell_count();
1196 case DataLayout::ret_data_tag:
1197 return RetData::static_cell_count();
1198 case DataLayout::branch_data_tag:
1199 return BranchData::static_cell_count();
1200 case DataLayout::multi_branch_data_tag:
1201 return ((new MultiBranchData(this))->cell_count());
1202 case DataLayout::arg_info_data_tag:
1203 return ((new ArgInfoData(this))->cell_count());
1204 case DataLayout::call_type_data_tag:
1205 return ((new CallTypeData(this))->cell_count());
1206 case DataLayout::virtual_call_type_data_tag:
1207 return ((new VirtualCallTypeData(this))->cell_count());
1208 case DataLayout::parameters_type_data_tag:
1209 return ((new ParametersTypeData(this))->cell_count());
1210 case DataLayout::speculative_trap_data_tag:
1211 return SpeculativeTrapData::static_cell_count();
1212 }
1213 }
1214 ProfileData* DataLayout::data_in() {
1215 switch (tag()) {
1216 case DataLayout::no_tag:
1217 default:
1218 ShouldNotReachHere();
1219 return nullptr;
1220 case DataLayout::bit_data_tag:
1221 return new BitData(this);
1222 case DataLayout::counter_data_tag:
1223 return new CounterData(this);
1224 case DataLayout::jump_data_tag:
1225 return new JumpData(this);
1226 case DataLayout::receiver_type_data_tag:
1227 return new ReceiverTypeData(this);
1228 case DataLayout::virtual_call_data_tag:
1229 return new VirtualCallData(this);
1230 case DataLayout::ret_data_tag:
1231 return new RetData(this);
1232 case DataLayout::branch_data_tag:
1233 return new BranchData(this);
1234 case DataLayout::multi_branch_data_tag:
1235 return new MultiBranchData(this);
1236 case DataLayout::arg_info_data_tag:
1237 return new ArgInfoData(this);
1238 case DataLayout::call_type_data_tag:
1239 return new CallTypeData(this);
1240 case DataLayout::virtual_call_type_data_tag:
1241 return new VirtualCallTypeData(this);
1242 case DataLayout::parameters_type_data_tag:
1243 return new ParametersTypeData(this);
1244 case DataLayout::speculative_trap_data_tag:
1245 return new SpeculativeTrapData(this);
1246 }
1247 }
1248
1249 // Iteration over data.
1250 ProfileData* MethodData::next_data(ProfileData* current) const {
1251 int current_index = dp_to_di(current->dp());
1252 int next_index = current_index + current->size_in_bytes();
1253 ProfileData* next = data_at(next_index);
1254 return next;
1255 }
1256
1257 DataLayout* MethodData::next_data_layout(DataLayout* current) const {
1258 int current_index = dp_to_di((address)current);
1259 int next_index = current_index + current->size_in_bytes();
1260 if (out_of_bounds(next_index)) {
1261 return nullptr;
1262 }
1263 DataLayout* next = data_layout_at(next_index);
1264 return next;
1265 }
1266
1267 // Give each of the data entries a chance to perform specific
1268 // data initialization.
1269 void MethodData::post_initialize(BytecodeStream* stream) {
1270 ResourceMark rm;
1271 ProfileData* data;
1272 for (data = first_data(); is_valid(data); data = next_data(data)) {
1273 stream->set_start(data->bci());
1274 stream->next();
1275 data->post_initialize(stream, this);
1276 }
1277 if (_parameters_type_data_di != no_parameters) {
1278 parameters_type_data()->post_initialize(nullptr, this);
1279 }
1280 }
1281
1282 // Initialize the MethodData* corresponding to a given method.
1283 MethodData::MethodData(const methodHandle& method)
1284 : _method(method()),
1285 // Holds Compile_lock
1286 _compiler_counters(),
1287 _parameters_type_data_di(parameters_uninitialized) {
1288 _extra_data_lock = nullptr;
1289 initialize();
1290 }
1291
1292 #if INCLUDE_CDS
1293 MethodData::MethodData() {
1294 // Used by cppVtables.cpp only
1295 assert(CDSConfig::is_dumping_static_archive() || UseSharedSpaces, "only for CDS");
1296 }
1297 #endif
1298
1299 // Reinitialize the storage of an existing MDO at a safepoint. Doing it this way will ensure it's
1300 // not being accessed while the contents are being rewritten.
1301 class VM_ReinitializeMDO: public VM_Operation {
1302 private:
1303 MethodData* _mdo;
1304 public:
1305 VM_ReinitializeMDO(MethodData* mdo): _mdo(mdo) {}
1306 VMOp_Type type() const { return VMOp_ReinitializeMDO; }
1307 void doit() {
1308 // The extra data is being zero'd, we'd like to acquire the extra_data_lock but it can't be held
1309 // over a safepoint. This means that we don't actually need to acquire the lock.
1310 _mdo->initialize();
1311 }
1312 bool allow_nested_vm_operations() const { return true; }
1313 };
1314
1315 void MethodData::reinitialize() {
1316 VM_ReinitializeMDO op(this);
1317 VMThread::execute(&op);
1318 }
1319
1320
1321 void MethodData::initialize() {
1322 Thread* thread = Thread::current();
1323 NoSafepointVerifier no_safepoint; // init function atomic wrt GC
1324 ResourceMark rm(thread);
1325
1326 init();
1327
1328 // Go through the bytecodes and allocate and initialize the
1329 // corresponding data cells.
1330 int data_size = 0;
1331 int empty_bc_count = 0; // number of bytecodes lacking data
1332 _data[0] = 0; // apparently not set below.
1333 BytecodeStream stream(methodHandle(thread, method()));
1334 Bytecodes::Code c;
1335 bool needs_speculative_traps = false;
1336 while ((c = stream.next()) >= 0) {
1337 int size_in_bytes = initialize_data(&stream, data_size);
1338 data_size += size_in_bytes;
1339 if (size_in_bytes == 0 JVMCI_ONLY(&& Bytecodes::can_trap(c))) empty_bc_count += 1;
1340 needs_speculative_traps = needs_speculative_traps || is_speculative_trap_bytecode(c);
1341 }
1342 _data_size = data_size;
1343 int object_size = in_bytes(data_offset()) + data_size;
1344
1345 // Add some extra DataLayout cells (at least one) to track stray traps.
1346 int extra_data_count = compute_extra_data_count(data_size, empty_bc_count, needs_speculative_traps);
1347 int extra_size = extra_data_count * DataLayout::compute_size_in_bytes(0);
1348
1349 // Let's zero the space for the extra data
1350 if (extra_size > 0) {
1351 Copy::zero_to_bytes(((address)_data) + data_size, extra_size);
1352 }
1353
1354 // Add a cell to record information about modified arguments.
1355 // Set up _args_modified array after traps cells so that
1356 // the code for traps cells works.
1357 DataLayout *dp = data_layout_at(data_size + extra_size);
1358
1359 int arg_size = method()->size_of_parameters();
1360 dp->initialize(DataLayout::arg_info_data_tag, 0, arg_size+1);
1361
1362 int arg_data_size = DataLayout::compute_size_in_bytes(arg_size+1);
1363 object_size += extra_size + arg_data_size;
1364
1365 int parms_cell = ParametersTypeData::compute_cell_count(method());
1366 // If we are profiling parameters, we reserved an area near the end
1367 // of the MDO after the slots for bytecodes (because there's no bci
1368 // for method entry so they don't fit with the framework for the
1369 // profiling of bytecodes). We store the offset within the MDO of
1370 // this area (or -1 if no parameter is profiled)
1371 int parm_data_size = 0;
1372 if (parms_cell > 0) {
1373 parm_data_size = DataLayout::compute_size_in_bytes(parms_cell);
1374 object_size += parm_data_size;
1375 _parameters_type_data_di = data_size + extra_size + arg_data_size;
1376 DataLayout *dp = data_layout_at(data_size + extra_size + arg_data_size);
1377 dp->initialize(DataLayout::parameters_type_data_tag, 0, parms_cell);
1378 } else {
1379 _parameters_type_data_di = no_parameters;
1380 }
1381
1382 _exception_handler_data_di = data_size + extra_size + arg_data_size + parm_data_size;
1383 if (ProfileExceptionHandlers && method()->has_exception_handler()) {
1384 int num_exception_handlers = method()->exception_table_length();
1385 object_size += num_exception_handlers * single_exception_handler_data_size();
1386 ExceptionTableElement* exception_handlers = method()->exception_table_start();
1387 for (int i = 0; i < num_exception_handlers; i++) {
1388 DataLayout *dp = exception_handler_data_at(i);
1389 dp->initialize(DataLayout::bit_data_tag, exception_handlers[i].handler_pc, single_exception_handler_data_cell_count());
1390 }
1391 }
1392
1393 // Set an initial hint. Don't use set_hint_di() because
1394 // first_di() may be out of bounds if data_size is 0.
1395 // In that situation, _hint_di is never used, but at
1396 // least well-defined.
1397 _hint_di = first_di();
1398
1399 post_initialize(&stream);
1400
1401 assert(object_size == compute_allocation_size_in_bytes(methodHandle(thread, _method)), "MethodData: computed size != initialized size");
1402 set_size(object_size);
1403 }
1404
1405 void MethodData::init() {
1406 _compiler_counters = CompilerCounters(); // reset compiler counters
1407 _invocation_counter.init();
1408 _backedge_counter.init();
1409 _invocation_counter_start = 0;
1410 _backedge_counter_start = 0;
1411
1412 // Set per-method invoke- and backedge mask.
1413 double scale = 1.0;
1414 methodHandle mh(Thread::current(), _method);
1415 CompilerOracle::has_option_value(mh, CompileCommandEnum::CompileThresholdScaling, scale);
1416 _invoke_mask = (int)right_n_bits(CompilerConfig::scaled_freq_log(Tier0InvokeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
1417 _backedge_mask = (int)right_n_bits(CompilerConfig::scaled_freq_log(Tier0BackedgeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
1418
1419 _tenure_traps = 0;
1420 _num_loops = 0;
1421 _num_blocks = 0;
1422 _would_profile = unknown;
1423
1424 #if INCLUDE_JVMCI
1425 _jvmci_ir_size = 0;
1426 _failed_speculations = nullptr;
1427 #endif
1428
1429 // Initialize escape flags.
1430 clear_escape_info();
1431 }
1432
1433 bool MethodData::is_mature() const {
1434 return CompilationPolicy::is_mature(const_cast<MethodData*>(this));
1435 }
1436
1437 // Translate a bci to its corresponding data index (di).
1438 address MethodData::bci_to_dp(int bci) {
1439 ResourceMark rm;
1440 DataLayout* data = data_layout_before(bci);
1441 DataLayout* prev = nullptr;
1442 for ( ; is_valid(data); data = next_data_layout(data)) {
1443 if (data->bci() >= bci) {
1444 if (data->bci() == bci) set_hint_di(dp_to_di((address)data));
1445 else if (prev != nullptr) set_hint_di(dp_to_di((address)prev));
1446 return (address)data;
1447 }
1448 prev = data;
1449 }
1450 return (address)limit_data_position();
1451 }
1452
1453 // Translate a bci to its corresponding data, or null.
1454 ProfileData* MethodData::bci_to_data(int bci) {
1455 check_extra_data_locked();
1456
1457 DataLayout* data = data_layout_before(bci);
1458 for ( ; is_valid(data); data = next_data_layout(data)) {
1459 if (data->bci() == bci) {
1460 set_hint_di(dp_to_di((address)data));
1461 return data->data_in();
1462 } else if (data->bci() > bci) {
1463 break;
1464 }
1465 }
1466 return bci_to_extra_data(bci, nullptr, false);
1467 }
1468
1469 DataLayout* MethodData::exception_handler_bci_to_data_helper(int bci) {
1470 assert(ProfileExceptionHandlers, "not profiling");
1471 for (int i = 0; i < num_exception_handler_data(); i++) {
1472 DataLayout* exception_handler_data = exception_handler_data_at(i);
1473 if (exception_handler_data->bci() == bci) {
1474 return exception_handler_data;
1475 }
1476 }
1477 return nullptr;
1478 }
1479
1480 BitData* MethodData::exception_handler_bci_to_data_or_null(int bci) {
1481 DataLayout* data = exception_handler_bci_to_data_helper(bci);
1482 return data != nullptr ? new BitData(data) : nullptr;
1483 }
1484
1485 BitData MethodData::exception_handler_bci_to_data(int bci) {
1486 DataLayout* data = exception_handler_bci_to_data_helper(bci);
1487 assert(data != nullptr, "invalid bci");
1488 return BitData(data);
1489 }
1490
1491 DataLayout* MethodData::next_extra(DataLayout* dp) {
1492 int nb_cells = 0;
1493 switch(dp->tag()) {
1494 case DataLayout::bit_data_tag:
1495 case DataLayout::no_tag:
1496 nb_cells = BitData::static_cell_count();
1497 break;
1498 case DataLayout::speculative_trap_data_tag:
1499 nb_cells = SpeculativeTrapData::static_cell_count();
1500 break;
1501 default:
1502 fatal("unexpected tag %d", dp->tag());
1503 }
1504 return (DataLayout*)((address)dp + DataLayout::compute_size_in_bytes(nb_cells));
1505 }
1506
1507 ProfileData* MethodData::bci_to_extra_data_find(int bci, Method* m, DataLayout*& dp) {
1508 check_extra_data_locked();
1509
1510 DataLayout* end = args_data_limit();
1511
1512 for (;; dp = next_extra(dp)) {
1513 assert(dp < end, "moved past end of extra data");
1514 // No need for "AtomicAccess::load_acquire" ops,
1515 // since the data structure is monotonic.
1516 switch(dp->tag()) {
1517 case DataLayout::no_tag:
1518 return nullptr;
1519 case DataLayout::arg_info_data_tag:
1520 dp = end;
1521 return nullptr; // ArgInfoData is at the end of extra data section.
1522 case DataLayout::bit_data_tag:
1523 if (m == nullptr && dp->bci() == bci) {
1524 return new BitData(dp);
1525 }
1526 break;
1527 case DataLayout::speculative_trap_data_tag:
1528 if (m != nullptr) {
1529 SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1530 if (dp->bci() == bci) {
1531 assert(data->method() != nullptr, "method must be set");
1532 if (data->method() == m) {
1533 return data;
1534 }
1535 }
1536 }
1537 break;
1538 default:
1539 fatal("unexpected tag %d", dp->tag());
1540 }
1541 }
1542 return nullptr;
1543 }
1544
1545
1546 // Translate a bci to its corresponding extra data, or null.
1547 ProfileData* MethodData::bci_to_extra_data(int bci, Method* m, bool create_if_missing) {
1548 check_extra_data_locked();
1549
1550 // This code assumes an entry for a SpeculativeTrapData is 2 cells
1551 assert(2*DataLayout::compute_size_in_bytes(BitData::static_cell_count()) ==
1552 DataLayout::compute_size_in_bytes(SpeculativeTrapData::static_cell_count()),
1553 "code needs to be adjusted");
1554
1555 // Do not create one of these if method has been redefined.
1556 if (m != nullptr && m->is_old()) {
1557 return nullptr;
1558 }
1559
1560 DataLayout* dp = extra_data_base();
1561 DataLayout* end = args_data_limit();
1562
1563 // Find if already exists
1564 ProfileData* result = bci_to_extra_data_find(bci, m, dp);
1565 if (result != nullptr || dp >= end) {
1566 return result;
1567 }
1568
1569 if (create_if_missing) {
1570 // Not found -> Allocate
1571 assert(dp->tag() == DataLayout::no_tag || (dp->tag() == DataLayout::speculative_trap_data_tag && m != nullptr), "should be free");
1572 assert(next_extra(dp)->tag() == DataLayout::no_tag || next_extra(dp)->tag() == DataLayout::arg_info_data_tag, "should be free or arg info");
1573 u1 tag = m == nullptr ? DataLayout::bit_data_tag : DataLayout::speculative_trap_data_tag;
1574 // SpeculativeTrapData is 2 slots. Make sure we have room.
1575 if (m != nullptr && next_extra(dp)->tag() != DataLayout::no_tag) {
1576 return nullptr;
1577 }
1578 DataLayout temp;
1579 temp.initialize(tag, checked_cast<u2>(bci), 0);
1580
1581 dp->set_header(temp.header());
1582 assert(dp->tag() == tag, "sane");
1583 assert(dp->bci() == bci, "no concurrent allocation");
1584 if (tag == DataLayout::bit_data_tag) {
1585 return new BitData(dp);
1586 } else {
1587 SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1588 data->set_method(m);
1589 return data;
1590 }
1591 }
1592 return nullptr;
1593 }
1594
1595 ArgInfoData *MethodData::arg_info() {
1596 DataLayout* dp = extra_data_base();
1597 DataLayout* end = args_data_limit();
1598 for (; dp < end; dp = next_extra(dp)) {
1599 if (dp->tag() == DataLayout::arg_info_data_tag)
1600 return new ArgInfoData(dp);
1601 }
1602 return nullptr;
1603 }
1604
1605 // Printing
1606
1607 void MethodData::print_on(outputStream* st) const {
1608 assert(is_methodData(), "should be method data");
1609 st->print("method data for ");
1610 method()->print_value_on(st);
1611 st->cr();
1612 print_data_on(st);
1613 }
1614
1615 void MethodData::print_value_on(outputStream* st) const {
1616 assert(is_methodData(), "should be method data");
1617 st->print("method data for ");
1618 method()->print_value_on(st);
1619 }
1620
1621 void MethodData::print_data_on(outputStream* st) const {
1622 Mutex* lock = const_cast<MethodData*>(this)->extra_data_lock();
1623 ConditionalMutexLocker ml(lock, !lock->owned_by_self(),
1624 Mutex::_no_safepoint_check_flag);
1625 ResourceMark rm;
1626 ProfileData* data = first_data();
1627 if (_parameters_type_data_di != no_parameters) {
1628 parameters_type_data()->print_data_on(st);
1629 }
1630 for ( ; is_valid(data); data = next_data(data)) {
1631 st->print("%d", dp_to_di(data->dp()));
1632 st->fill_to(6);
1633 data->print_data_on(st, this);
1634 }
1635
1636 st->print_cr("--- Extra data:");
1637 DataLayout* dp = extra_data_base();
1638 DataLayout* end = args_data_limit();
1639 for (;; dp = next_extra(dp)) {
1640 assert(dp < end, "moved past end of extra data");
1641 // No need for "AtomicAccess::load_acquire" ops,
1642 // since the data structure is monotonic.
1643 switch(dp->tag()) {
1644 case DataLayout::no_tag:
1645 continue;
1646 case DataLayout::bit_data_tag:
1647 data = new BitData(dp);
1648 break;
1649 case DataLayout::speculative_trap_data_tag:
1650 data = new SpeculativeTrapData(dp);
1651 break;
1652 case DataLayout::arg_info_data_tag:
1653 data = new ArgInfoData(dp);
1654 dp = end; // ArgInfoData is at the end of extra data section.
1655 break;
1656 default:
1657 fatal("unexpected tag %d", dp->tag());
1658 }
1659 st->print("%d", dp_to_di(data->dp()));
1660 st->fill_to(6);
1661 data->print_data_on(st);
1662 if (dp >= end) return;
1663 }
1664 }
1665
1666 // Verification
1667
1668 void MethodData::verify_on(outputStream* st) {
1669 guarantee(is_methodData(), "object must be method data");
1670 // guarantee(m->is_perm(), "should be in permspace");
1671 this->verify_data_on(st);
1672 }
1673
1674 void MethodData::verify_data_on(outputStream* st) {
1675 NEEDS_CLEANUP;
1676 // not yet implemented.
1677 }
1678
1679 bool MethodData::profile_jsr292(const methodHandle& m, int bci) {
1680 if (m->is_compiled_lambda_form()) {
1681 return true;
1682 }
1683
1684 Bytecode_invoke inv(m , bci);
1685 return inv.is_invokedynamic() || inv.is_invokehandle();
1686 }
1687
1688 bool MethodData::profile_unsafe(const methodHandle& m, int bci) {
1689 Bytecode_invoke inv(m , bci);
1690 if (inv.is_invokevirtual()) {
1691 Symbol* klass = inv.klass();
1692 if (klass == vmSymbols::jdk_internal_misc_Unsafe() ||
1693 klass == vmSymbols::sun_misc_Unsafe() ||
1694 klass == vmSymbols::jdk_internal_misc_ScopedMemoryAccess()) {
1695 Symbol* name = inv.name();
1696 if (name->starts_with("get") || name->starts_with("put")) {
1697 return true;
1698 }
1699 }
1700 }
1701 return false;
1702 }
1703
1704 int MethodData::profile_arguments_flag() {
1705 return TypeProfileLevel % 10;
1706 }
1707
1708 bool MethodData::profile_arguments() {
1709 return profile_arguments_flag() > no_type_profile && profile_arguments_flag() <= type_profile_all && TypeProfileArgsLimit > 0;
1710 }
1711
1712 bool MethodData::profile_arguments_jsr292_only() {
1713 return profile_arguments_flag() == type_profile_jsr292;
1714 }
1715
1716 bool MethodData::profile_all_arguments() {
1717 return profile_arguments_flag() == type_profile_all;
1718 }
1719
1720 bool MethodData::profile_arguments_for_invoke(const methodHandle& m, int bci) {
1721 if (!profile_arguments()) {
1722 return false;
1723 }
1724
1725 if (profile_all_arguments()) {
1726 return true;
1727 }
1728
1729 if (profile_unsafe(m, bci)) {
1730 return true;
1731 }
1732
1733 assert(profile_arguments_jsr292_only(), "inconsistent");
1734 return profile_jsr292(m, bci);
1735 }
1736
1737 int MethodData::profile_return_flag() {
1738 return (TypeProfileLevel % 100) / 10;
1739 }
1740
1741 bool MethodData::profile_return() {
1742 return profile_return_flag() > no_type_profile && profile_return_flag() <= type_profile_all;
1743 }
1744
1745 bool MethodData::profile_return_jsr292_only() {
1746 return profile_return_flag() == type_profile_jsr292;
1747 }
1748
1749 bool MethodData::profile_all_return() {
1750 return profile_return_flag() == type_profile_all;
1751 }
1752
1753 bool MethodData::profile_return_for_invoke(const methodHandle& m, int bci) {
1754 if (!profile_return()) {
1755 return false;
1756 }
1757
1758 if (profile_all_return()) {
1759 return true;
1760 }
1761
1762 assert(profile_return_jsr292_only(), "inconsistent");
1763 return profile_jsr292(m, bci);
1764 }
1765
1766 int MethodData::profile_parameters_flag() {
1767 return TypeProfileLevel / 100;
1768 }
1769
1770 bool MethodData::profile_parameters() {
1771 return profile_parameters_flag() > no_type_profile && profile_parameters_flag() <= type_profile_all;
1772 }
1773
1774 bool MethodData::profile_parameters_jsr292_only() {
1775 return profile_parameters_flag() == type_profile_jsr292;
1776 }
1777
1778 bool MethodData::profile_all_parameters() {
1779 return profile_parameters_flag() == type_profile_all;
1780 }
1781
1782 bool MethodData::profile_parameters_for_method(const methodHandle& m) {
1783 if (!profile_parameters()) {
1784 return false;
1785 }
1786
1787 if (profile_all_parameters()) {
1788 return true;
1789 }
1790
1791 assert(profile_parameters_jsr292_only(), "inconsistent");
1792 return m->is_compiled_lambda_form();
1793 }
1794
1795 void MethodData::metaspace_pointers_do(MetaspaceClosure* it) {
1796 log_trace(aot, training)("Iter(MethodData): %p for %p %s", this, _method, _method->name_and_sig_as_C_string());
1797 it->push(&_method);
1798 if (_parameters_type_data_di != no_parameters) {
1799 parameters_type_data()->metaspace_pointers_do(it);
1800 }
1801 for (ProfileData* data = first_data(); is_valid(data); data = next_data(data)) {
1802 data->metaspace_pointers_do(it);
1803 }
1804 for (DataLayout* dp = extra_data_base();
1805 dp < extra_data_limit();
1806 dp = MethodData::next_extra(dp)) {
1807 if (dp->tag() == DataLayout::speculative_trap_data_tag) {
1808 ResourceMark rm;
1809 SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1810 data->metaspace_pointers_do(it);
1811 } else if (dp->tag() == DataLayout::no_tag ||
1812 dp->tag() == DataLayout::arg_info_data_tag) {
1813 break;
1814 }
1815 }
1816 }
1817
1818 void MethodData::clean_extra_data_helper(DataLayout* dp, int shift, bool reset) {
1819 check_extra_data_locked();
1820
1821 if (shift == 0) {
1822 return;
1823 }
1824 if (!reset) {
1825 // Move all cells of trap entry at dp left by "shift" cells
1826 intptr_t* start = (intptr_t*)dp;
1827 intptr_t* end = (intptr_t*)next_extra(dp);
1828 for (intptr_t* ptr = start; ptr < end; ptr++) {
1829 *(ptr-shift) = *ptr;
1830 }
1831 } else {
1832 // Reset "shift" cells stopping at dp
1833 intptr_t* start = ((intptr_t*)dp) - shift;
1834 intptr_t* end = (intptr_t*)dp;
1835 for (intptr_t* ptr = start; ptr < end; ptr++) {
1836 *ptr = 0;
1837 }
1838 }
1839 }
1840
1841 // Check for entries that reference an unloaded method
1842 class CleanExtraDataKlassClosure : public CleanExtraDataClosure {
1843 bool _always_clean;
1844 public:
1845 CleanExtraDataKlassClosure(bool always_clean) : _always_clean(always_clean) {}
1846 bool is_live(Method* m) {
1847 if (!_always_clean && m->method_holder()->is_instance_klass() && InstanceKlass::cast(m->method_holder())->is_not_initialized()) {
1848 return true; // TODO: treat as unloaded instead?
1849 }
1850 return !(_always_clean) && m->method_holder()->is_loader_alive();
1851 }
1852 };
1853
1854 // Check for entries that reference a redefined method
1855 class CleanExtraDataMethodClosure : public CleanExtraDataClosure {
1856 public:
1857 CleanExtraDataMethodClosure() {}
1858 bool is_live(Method* m) { return !m->is_old(); }
1859 };
1860
1861 Mutex* MethodData::extra_data_lock() {
1862 Mutex* lock = AtomicAccess::load_acquire(&_extra_data_lock);
1863 if (lock == nullptr) {
1864 // This lock could be acquired while we are holding DumpTimeTable_lock/nosafepoint
1865 lock = new Mutex(Mutex::nosafepoint-1, "MDOExtraData_lock");
1866 Mutex* old = AtomicAccess::cmpxchg(&_extra_data_lock, (Mutex*)nullptr, lock);
1867 if (old != nullptr) {
1868 // Another thread created the lock before us. Use that lock instead.
1869 delete lock;
1870 return old;
1871 }
1872 }
1873 return lock;
1874 }
1875
1876 // Remove SpeculativeTrapData entries that reference an unloaded or
1877 // redefined method
1878 void MethodData::clean_extra_data(CleanExtraDataClosure* cl) {
1879 check_extra_data_locked();
1880
1881 DataLayout* dp = extra_data_base();
1882 DataLayout* end = args_data_limit();
1883
1884 int shift = 0;
1885 for (; dp < end; dp = next_extra(dp)) {
1886 switch(dp->tag()) {
1887 case DataLayout::speculative_trap_data_tag: {
1888 SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1889 Method* m = data->method();
1890 assert(m != nullptr, "should have a method");
1891 if (is_excluded(m->method_holder()) || !cl->is_live(m)) {
1892 // "shift" accumulates the number of cells for dead
1893 // SpeculativeTrapData entries that have been seen so
1894 // far. Following entries must be shifted left by that many
1895 // cells to remove the dead SpeculativeTrapData entries.
1896 shift += (int)((intptr_t*)next_extra(dp) - (intptr_t*)dp);
1897 } else {
1898 // Shift this entry left if it follows dead
1899 // SpeculativeTrapData entries
1900 clean_extra_data_helper(dp, shift);
1901 }
1902 break;
1903 }
1904 case DataLayout::bit_data_tag:
1905 // Shift this entry left if it follows dead SpeculativeTrapData
1906 // entries
1907 clean_extra_data_helper(dp, shift);
1908 continue;
1909 case DataLayout::no_tag:
1910 case DataLayout::arg_info_data_tag:
1911 // We are at end of the live trap entries. The previous "shift"
1912 // cells contain entries that are either dead or were shifted
1913 // left. They need to be reset to no_tag
1914 clean_extra_data_helper(dp, shift, true);
1915 return;
1916 default:
1917 fatal("unexpected tag %d", dp->tag());
1918 }
1919 }
1920 }
1921
1922 // Verify there's no unloaded or redefined method referenced by a
1923 // SpeculativeTrapData entry
1924 void MethodData::verify_extra_data_clean(CleanExtraDataClosure* cl) {
1925 check_extra_data_locked();
1926
1927 #ifdef ASSERT
1928 DataLayout* dp = extra_data_base();
1929 DataLayout* end = args_data_limit();
1930
1931 for (; dp < end; dp = next_extra(dp)) {
1932 switch(dp->tag()) {
1933 case DataLayout::speculative_trap_data_tag: {
1934 SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1935 Method* m = data->method();
1936 assert(m != nullptr && cl->is_live(m), "Method should exist");
1937 break;
1938 }
1939 case DataLayout::bit_data_tag:
1940 continue;
1941 case DataLayout::no_tag:
1942 case DataLayout::arg_info_data_tag:
1943 return;
1944 default:
1945 fatal("unexpected tag %d", dp->tag());
1946 }
1947 }
1948 #endif
1949 }
1950
1951 void MethodData::clean_method_data(bool always_clean) {
1952 ResourceMark rm;
1953 for (ProfileData* data = first_data();
1954 is_valid(data);
1955 data = next_data(data)) {
1956 data->clean_weak_klass_links(always_clean);
1957 }
1958 ParametersTypeData* parameters = parameters_type_data();
1959 if (parameters != nullptr) {
1960 parameters->clean_weak_klass_links(always_clean);
1961 }
1962
1963 CleanExtraDataKlassClosure cl(always_clean);
1964
1965 // Lock to modify extra data, and prevent Safepoint from breaking the lock
1966 MutexLocker ml(extra_data_lock(), Mutex::_no_safepoint_check_flag);
1967
1968 clean_extra_data(&cl);
1969 verify_extra_data_clean(&cl);
1970 }
1971
1972 // This is called during redefinition to clean all "old" redefined
1973 // methods out of MethodData for all methods.
1974 void MethodData::clean_weak_method_links() {
1975 ResourceMark rm;
1976 CleanExtraDataMethodClosure cl;
1977
1978 // Lock to modify extra data, and prevent Safepoint from breaking the lock
1979 MutexLocker ml(extra_data_lock(), Mutex::_no_safepoint_check_flag);
1980
1981 clean_extra_data(&cl);
1982 verify_extra_data_clean(&cl);
1983 }
1984
1985 void MethodData::deallocate_contents(ClassLoaderData* loader_data) {
1986 release_C_heap_structures();
1987 }
1988
1989 void MethodData::release_C_heap_structures() {
1990 #if INCLUDE_JVMCI
1991 FailedSpeculation::free_failed_speculations(get_failed_speculations_address());
1992 #endif
1993 }
1994
1995 #if INCLUDE_CDS
1996 void MethodData::remove_unshareable_info() {
1997 _extra_data_lock = nullptr;
1998 #if INCLUDE_JVMCI
1999 _failed_speculations = nullptr;
2000 #endif
2001 }
2002
2003 void MethodData::restore_unshareable_info(TRAPS) {
2004 //_extra_data_lock = new Mutex(Mutex::nosafepoint, "MDOExtraData_lock");
2005 }
2006 #endif // INCLUDE_CDS
2007
2008 #ifdef ASSERT
2009 void MethodData::check_extra_data_locked() const {
2010 // Cast const away, just to be able to verify the lock
2011 // Usually we only want non-const accesses on the lock,
2012 // so this here is an exception.
2013 MethodData* self = (MethodData*)this;
2014 assert(self->extra_data_lock()->owned_by_self() || CDSConfig::is_dumping_archive(), "must have lock");
2015 assert(!Thread::current()->is_Java_thread() ||
2016 JavaThread::current()->is_in_no_safepoint_scope(),
2017 "JavaThread must have NoSafepointVerifier inside lock scope");
2018 }
2019 #endif