1 /*
2  * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 #include "precompiled.hpp"
26 #include "classfile/systemDictionary.hpp"
27 #include "compiler/compilerOracle.hpp"
28 #include "interpreter/bytecode.hpp"
29 #include "interpreter/bytecodeStream.hpp"
30 #include "interpreter/linkResolver.hpp"
31 #include "memory/heapInspection.hpp"
32 #include "memory/metaspaceClosure.hpp"
33 #include "memory/resourceArea.hpp"
34 #include "oops/methodData.inline.hpp"
35 #include "prims/jvmtiRedefineClasses.hpp"
36 #include "runtime/arguments.hpp"
37 #include "runtime/compilationPolicy.hpp"
38 #include "runtime/deoptimization.hpp"
39 #include "runtime/handles.inline.hpp"
40 #include "runtime/orderAccess.hpp"
41 #include "runtime/safepointVerifiers.hpp"
42 #include "utilities/align.hpp"
43 #include "utilities/copy.hpp"
44 
45 // ==================================================================
46 // DataLayout
47 //
48 // Overlay for generic profiling data.
49 
50 // Some types of data layouts need a length field.
needs_array_len(u1 tag)51 bool DataLayout::needs_array_len(u1 tag) {
52   return (tag == multi_branch_data_tag) || (tag == arg_info_data_tag) || (tag == parameters_type_data_tag);
53 }
54 
55 // Perform generic initialization of the data.  More specific
56 // initialization occurs in overrides of ProfileData::post_initialize.
initialize(u1 tag,u2 bci,int cell_count)57 void DataLayout::initialize(u1 tag, u2 bci, int cell_count) {
58   _header._bits = (intptr_t)0;
59   _header._struct._tag = tag;
60   _header._struct._bci = bci;
61   for (int i = 0; i < cell_count; i++) {
62     set_cell_at(i, (intptr_t)0);
63   }
64   if (needs_array_len(tag)) {
65     set_cell_at(ArrayData::array_len_off_set, cell_count - 1); // -1 for header.
66   }
67   if (tag == call_type_data_tag) {
68     CallTypeData::initialize(this, cell_count);
69   } else if (tag == virtual_call_type_data_tag) {
70     VirtualCallTypeData::initialize(this, cell_count);
71   }
72 }
73 
clean_weak_klass_links(bool always_clean)74 void DataLayout::clean_weak_klass_links(bool always_clean) {
75   ResourceMark m;
76   data_in()->clean_weak_klass_links(always_clean);
77 }
78 
79 
80 // ==================================================================
81 // ProfileData
82 //
83 // A ProfileData object is created to refer to a section of profiling
84 // data in a structured way.
85 
86 // Constructor for invalid ProfileData.
ProfileData()87 ProfileData::ProfileData() {
88   _data = NULL;
89 }
90 
print_data_on_helper(const MethodData * md) const91 char* ProfileData::print_data_on_helper(const MethodData* md) const {
92   DataLayout* dp  = md->extra_data_base();
93   DataLayout* end = md->args_data_limit();
94   stringStream ss;
95   for (;; dp = MethodData::next_extra(dp)) {
96     assert(dp < end, "moved past end of extra data");
97     switch(dp->tag()) {
98     case DataLayout::speculative_trap_data_tag:
99       if (dp->bci() == bci()) {
100         SpeculativeTrapData* data = new SpeculativeTrapData(dp);
101         int trap = data->trap_state();
102         char buf[100];
103         ss.print("trap/");
104         data->method()->print_short_name(&ss);
105         ss.print("(%s) ", Deoptimization::format_trap_state(buf, sizeof(buf), trap));
106       }
107       break;
108     case DataLayout::bit_data_tag:
109       break;
110     case DataLayout::no_tag:
111     case DataLayout::arg_info_data_tag:
112       return ss.as_string();
113       break;
114     default:
115       fatal("unexpected tag %d", dp->tag());
116     }
117   }
118   return NULL;
119 }
120 
print_data_on(outputStream * st,const MethodData * md) const121 void ProfileData::print_data_on(outputStream* st, const MethodData* md) const {
122   print_data_on(st, print_data_on_helper(md));
123 }
124 
print_shared(outputStream * st,const char * name,const char * extra) const125 void ProfileData::print_shared(outputStream* st, const char* name, const char* extra) const {
126   st->print("bci: %d", bci());
127   st->fill_to(tab_width_one);
128   st->print("%s", name);
129   tab(st);
130   int trap = trap_state();
131   if (trap != 0) {
132     char buf[100];
133     st->print("trap(%s) ", Deoptimization::format_trap_state(buf, sizeof(buf), trap));
134   }
135   if (extra != NULL) {
136     st->print("%s", extra);
137   }
138   int flags = data()->flags();
139   if (flags != 0) {
140     st->print("flags(%d) ", flags);
141   }
142 }
143 
tab(outputStream * st,bool first) const144 void ProfileData::tab(outputStream* st, bool first) const {
145   st->fill_to(first ? tab_width_one : tab_width_two);
146 }
147 
148 // ==================================================================
149 // BitData
150 //
151 // A BitData corresponds to a one-bit flag.  This is used to indicate
152 // whether a checkcast bytecode has seen a null value.
153 
154 
print_data_on(outputStream * st,const char * extra) const155 void BitData::print_data_on(outputStream* st, const char* extra) const {
156   print_shared(st, "BitData", extra);
157   st->cr();
158 }
159 
160 // ==================================================================
161 // CounterData
162 //
163 // A CounterData corresponds to a simple counter.
164 
print_data_on(outputStream * st,const char * extra) const165 void CounterData::print_data_on(outputStream* st, const char* extra) const {
166   print_shared(st, "CounterData", extra);
167   st->print_cr("count(%u)", count());
168 }
169 
170 // ==================================================================
171 // JumpData
172 //
173 // A JumpData is used to access profiling information for a direct
174 // branch.  It is a counter, used for counting the number of branches,
175 // plus a data displacement, used for realigning the data pointer to
176 // the corresponding target bci.
177 
post_initialize(BytecodeStream * stream,MethodData * mdo)178 void JumpData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
179   assert(stream->bci() == bci(), "wrong pos");
180   int target;
181   Bytecodes::Code c = stream->code();
182   if (c == Bytecodes::_goto_w || c == Bytecodes::_jsr_w) {
183     target = stream->dest_w();
184   } else {
185     target = stream->dest();
186   }
187   int my_di = mdo->dp_to_di(dp());
188   int target_di = mdo->bci_to_di(target);
189   int offset = target_di - my_di;
190   set_displacement(offset);
191 }
192 
print_data_on(outputStream * st,const char * extra) const193 void JumpData::print_data_on(outputStream* st, const char* extra) const {
194   print_shared(st, "JumpData", extra);
195   st->print_cr("taken(%u) displacement(%d)", taken(), displacement());
196 }
197 
compute_cell_count(Symbol * signature,bool include_receiver,int max)198 int TypeStackSlotEntries::compute_cell_count(Symbol* signature, bool include_receiver, int max) {
199   // Parameter profiling include the receiver
200   int args_count = include_receiver ? 1 : 0;
201   ResourceMark rm;
202   SignatureStream ss(signature);
203   args_count += ss.reference_parameter_count();
204   args_count = MIN2(args_count, max);
205   return args_count * per_arg_cell_count;
206 }
207 
compute_cell_count(BytecodeStream * stream)208 int TypeEntriesAtCall::compute_cell_count(BytecodeStream* stream) {
209   assert(Bytecodes::is_invoke(stream->code()), "should be invoke");
210   assert(TypeStackSlotEntries::per_arg_count() > ReturnTypeEntry::static_cell_count(), "code to test for arguments/results broken");
211   const methodHandle m = stream->method();
212   int bci = stream->bci();
213   Bytecode_invoke inv(m, bci);
214   int args_cell = 0;
215   if (MethodData::profile_arguments_for_invoke(m, bci)) {
216     args_cell = TypeStackSlotEntries::compute_cell_count(inv.signature(), false, TypeProfileArgsLimit);
217   }
218   int ret_cell = 0;
219   if (MethodData::profile_return_for_invoke(m, bci) && (inv.result_type() == T_OBJECT || inv.result_type() == T_ARRAY)) {
220     ret_cell = ReturnTypeEntry::static_cell_count();
221   }
222   int header_cell = 0;
223   if (args_cell + ret_cell > 0) {
224     header_cell = header_cell_count();
225   }
226 
227   return header_cell + args_cell + ret_cell;
228 }
229 
230 class ArgumentOffsetComputer : public SignatureInfo {
231 private:
232   int _max;
233   GrowableArray<int> _offsets;
234 
set(int size,BasicType type)235   void set(int size, BasicType type) { _size += size; }
do_object(int begin,int end)236   void do_object(int begin, int end) {
237     if (_offsets.length() < _max) {
238       _offsets.push(_size);
239     }
240     SignatureInfo::do_object(begin, end);
241   }
do_array(int begin,int end)242   void do_array (int begin, int end) {
243     if (_offsets.length() < _max) {
244       _offsets.push(_size);
245     }
246     SignatureInfo::do_array(begin, end);
247   }
248 
249 public:
ArgumentOffsetComputer(Symbol * signature,int max)250   ArgumentOffsetComputer(Symbol* signature, int max)
251     : SignatureInfo(signature), _max(max), _offsets(Thread::current(), max) {
252   }
253 
total()254   int total() { lazy_iterate_parameters(); return _size; }
255 
off_at(int i) const256   int off_at(int i) const { return _offsets.at(i); }
257 };
258 
post_initialize(Symbol * signature,bool has_receiver,bool include_receiver)259 void TypeStackSlotEntries::post_initialize(Symbol* signature, bool has_receiver, bool include_receiver) {
260   ResourceMark rm;
261   int start = 0;
262   // Parameter profiling include the receiver
263   if (include_receiver && has_receiver) {
264     set_stack_slot(0, 0);
265     set_type(0, type_none());
266     start += 1;
267   }
268   ArgumentOffsetComputer aos(signature, _number_of_entries-start);
269   aos.total();
270   for (int i = start; i < _number_of_entries; i++) {
271     set_stack_slot(i, aos.off_at(i-start) + (has_receiver ? 1 : 0));
272     set_type(i, type_none());
273   }
274 }
275 
post_initialize(BytecodeStream * stream,MethodData * mdo)276 void CallTypeData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
277   assert(Bytecodes::is_invoke(stream->code()), "should be invoke");
278   Bytecode_invoke inv(stream->method(), stream->bci());
279 
280   SignatureStream ss(inv.signature());
281   if (has_arguments()) {
282 #ifdef ASSERT
283     ResourceMark rm;
284     int count = MIN2(ss.reference_parameter_count(), (int)TypeProfileArgsLimit);
285     assert(count > 0, "room for args type but none found?");
286     check_number_of_arguments(count);
287 #endif
288     _args.post_initialize(inv.signature(), inv.has_receiver(), false);
289   }
290 
291   if (has_return()) {
292     assert(inv.result_type() == T_OBJECT || inv.result_type() == T_ARRAY, "room for a ret type but doesn't return obj?");
293     _ret.post_initialize();
294   }
295 }
296 
post_initialize(BytecodeStream * stream,MethodData * mdo)297 void VirtualCallTypeData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
298   assert(Bytecodes::is_invoke(stream->code()), "should be invoke");
299   Bytecode_invoke inv(stream->method(), stream->bci());
300 
301   if (has_arguments()) {
302 #ifdef ASSERT
303     ResourceMark rm;
304     SignatureStream ss(inv.signature());
305     int count = MIN2(ss.reference_parameter_count(), (int)TypeProfileArgsLimit);
306     assert(count > 0, "room for args type but none found?");
307     check_number_of_arguments(count);
308 #endif
309     _args.post_initialize(inv.signature(), inv.has_receiver(), false);
310   }
311 
312   if (has_return()) {
313     assert(inv.result_type() == T_OBJECT || inv.result_type() == T_ARRAY, "room for a ret type but doesn't return obj?");
314     _ret.post_initialize();
315   }
316 }
317 
clean_weak_klass_links(bool always_clean)318 void TypeStackSlotEntries::clean_weak_klass_links(bool always_clean) {
319   for (int i = 0; i < _number_of_entries; i++) {
320     intptr_t p = type(i);
321     Klass* k = (Klass*)klass_part(p);
322     if (k != NULL && (always_clean || !k->is_loader_alive())) {
323       set_type(i, with_status((Klass*)NULL, p));
324     }
325   }
326 }
327 
clean_weak_klass_links(bool always_clean)328 void ReturnTypeEntry::clean_weak_klass_links(bool always_clean) {
329   intptr_t p = type();
330   Klass* k = (Klass*)klass_part(p);
331   if (k != NULL && (always_clean || !k->is_loader_alive())) {
332     set_type(with_status((Klass*)NULL, p));
333   }
334 }
335 
return_profiling_enabled()336 bool TypeEntriesAtCall::return_profiling_enabled() {
337   return MethodData::profile_return();
338 }
339 
arguments_profiling_enabled()340 bool TypeEntriesAtCall::arguments_profiling_enabled() {
341   return MethodData::profile_arguments();
342 }
343 
print_klass(outputStream * st,intptr_t k)344 void TypeEntries::print_klass(outputStream* st, intptr_t k) {
345   if (is_type_none(k)) {
346     st->print("none");
347   } else if (is_type_unknown(k)) {
348     st->print("unknown");
349   } else {
350     valid_klass(k)->print_value_on(st);
351   }
352   if (was_null_seen(k)) {
353     st->print(" (null seen)");
354   }
355 }
356 
print_data_on(outputStream * st) const357 void TypeStackSlotEntries::print_data_on(outputStream* st) const {
358   for (int i = 0; i < _number_of_entries; i++) {
359     _pd->tab(st);
360     st->print("%d: stack(%u) ", i, stack_slot(i));
361     print_klass(st, type(i));
362     st->cr();
363   }
364 }
365 
print_data_on(outputStream * st) const366 void ReturnTypeEntry::print_data_on(outputStream* st) const {
367   _pd->tab(st);
368   print_klass(st, type());
369   st->cr();
370 }
371 
print_data_on(outputStream * st,const char * extra) const372 void CallTypeData::print_data_on(outputStream* st, const char* extra) const {
373   CounterData::print_data_on(st, extra);
374   if (has_arguments()) {
375     tab(st, true);
376     st->print("argument types");
377     _args.print_data_on(st);
378   }
379   if (has_return()) {
380     tab(st, true);
381     st->print("return type");
382     _ret.print_data_on(st);
383   }
384 }
385 
print_data_on(outputStream * st,const char * extra) const386 void VirtualCallTypeData::print_data_on(outputStream* st, const char* extra) const {
387   VirtualCallData::print_data_on(st, extra);
388   if (has_arguments()) {
389     tab(st, true);
390     st->print("argument types");
391     _args.print_data_on(st);
392   }
393   if (has_return()) {
394     tab(st, true);
395     st->print("return type");
396     _ret.print_data_on(st);
397   }
398 }
399 
400 // ==================================================================
401 // ReceiverTypeData
402 //
403 // A ReceiverTypeData is used to access profiling information about a
404 // dynamic type check.  It consists of a counter which counts the total times
405 // that the check is reached, and a series of (Klass*, count) pairs
406 // which are used to store a type profile for the receiver of the check.
407 
clean_weak_klass_links(bool always_clean)408 void ReceiverTypeData::clean_weak_klass_links(bool always_clean) {
409     for (uint row = 0; row < row_limit(); row++) {
410     Klass* p = receiver(row);
411     if (p != NULL && (always_clean || !p->is_loader_alive())) {
412       clear_row(row);
413     }
414   }
415 }
416 
417 #if INCLUDE_JVMCI
clean_weak_klass_links(bool always_clean)418 void VirtualCallData::clean_weak_klass_links(bool always_clean) {
419   ReceiverTypeData::clean_weak_klass_links(always_clean);
420   for (uint row = 0; row < method_row_limit(); row++) {
421     Method* p = method(row);
422     if (p != NULL && (always_clean || !p->method_holder()->is_loader_alive())) {
423       clear_method_row(row);
424     }
425   }
426 }
427 
clean_weak_method_links()428 void VirtualCallData::clean_weak_method_links() {
429   ReceiverTypeData::clean_weak_method_links();
430   for (uint row = 0; row < method_row_limit(); row++) {
431     Method* p = method(row);
432     if (p != NULL && p->is_old()) {
433       clear_method_row(row);
434     }
435   }
436 }
437 #endif // INCLUDE_JVMCI
438 
print_receiver_data_on(outputStream * st) const439 void ReceiverTypeData::print_receiver_data_on(outputStream* st) const {
440   uint row;
441   int entries = 0;
442   for (row = 0; row < row_limit(); row++) {
443     if (receiver(row) != NULL)  entries++;
444   }
445 #if INCLUDE_JVMCI
446   st->print_cr("count(%u) nonprofiled_count(%u) entries(%u)", count(), nonprofiled_count(), entries);
447 #else
448   st->print_cr("count(%u) entries(%u)", count(), entries);
449 #endif
450   int total = count();
451   for (row = 0; row < row_limit(); row++) {
452     if (receiver(row) != NULL) {
453       total += receiver_count(row);
454     }
455   }
456   for (row = 0; row < row_limit(); row++) {
457     if (receiver(row) != NULL) {
458       tab(st);
459       receiver(row)->print_value_on(st);
460       st->print_cr("(%u %4.2f)", receiver_count(row), (float) receiver_count(row) / (float) total);
461     }
462   }
463 }
print_data_on(outputStream * st,const char * extra) const464 void ReceiverTypeData::print_data_on(outputStream* st, const char* extra) const {
465   print_shared(st, "ReceiverTypeData", extra);
466   print_receiver_data_on(st);
467 }
468 
469 #if INCLUDE_JVMCI
print_method_data_on(outputStream * st) const470 void VirtualCallData::print_method_data_on(outputStream* st) const {
471   uint row;
472   int entries = 0;
473   for (row = 0; row < method_row_limit(); row++) {
474     if (method(row) != NULL) entries++;
475   }
476   tab(st);
477   st->print_cr("method_entries(%u)", entries);
478   int total = count();
479   for (row = 0; row < method_row_limit(); row++) {
480     if (method(row) != NULL) {
481       total += method_count(row);
482     }
483   }
484   for (row = 0; row < method_row_limit(); row++) {
485     if (method(row) != NULL) {
486       tab(st);
487       method(row)->print_value_on(st);
488       st->print_cr("(%u %4.2f)", method_count(row), (float) method_count(row) / (float) total);
489     }
490   }
491 }
492 #endif // INCLUDE_JVMCI
493 
print_data_on(outputStream * st,const char * extra) const494 void VirtualCallData::print_data_on(outputStream* st, const char* extra) const {
495   print_shared(st, "VirtualCallData", extra);
496   print_receiver_data_on(st);
497   print_method_data_on(st);
498 }
499 
500 // ==================================================================
501 // RetData
502 //
503 // A RetData is used to access profiling information for a ret bytecode.
504 // It is composed of a count of the number of times that the ret has
505 // been executed, followed by a series of triples of the form
506 // (bci, count, di) which count the number of times that some bci was the
507 // target of the ret and cache a corresponding displacement.
508 
post_initialize(BytecodeStream * stream,MethodData * mdo)509 void RetData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
510   for (uint row = 0; row < row_limit(); row++) {
511     set_bci_displacement(row, -1);
512     set_bci(row, no_bci);
513   }
514   // release so other threads see a consistent state.  bci is used as
515   // a valid flag for bci_displacement.
516   OrderAccess::release();
517 }
518 
519 // This routine needs to atomically update the RetData structure, so the
520 // caller needs to hold the RetData_lock before it gets here.  Since taking
521 // the lock can block (and allow GC) and since RetData is a ProfileData is a
522 // wrapper around a derived oop, taking the lock in _this_ method will
523 // basically cause the 'this' pointer's _data field to contain junk after the
524 // lock.  We require the caller to take the lock before making the ProfileData
525 // structure.  Currently the only caller is InterpreterRuntime::update_mdp_for_ret
fixup_ret(int return_bci,MethodData * h_mdo)526 address RetData::fixup_ret(int return_bci, MethodData* h_mdo) {
527   // First find the mdp which corresponds to the return bci.
528   address mdp = h_mdo->bci_to_dp(return_bci);
529 
530   // Now check to see if any of the cache slots are open.
531   for (uint row = 0; row < row_limit(); row++) {
532     if (bci(row) == no_bci) {
533       set_bci_displacement(row, mdp - dp());
534       set_bci_count(row, DataLayout::counter_increment);
535       // Barrier to ensure displacement is written before the bci; allows
536       // the interpreter to read displacement without fear of race condition.
537       release_set_bci(row, return_bci);
538       break;
539     }
540   }
541   return mdp;
542 }
543 
print_data_on(outputStream * st,const char * extra) const544 void RetData::print_data_on(outputStream* st, const char* extra) const {
545   print_shared(st, "RetData", extra);
546   uint row;
547   int entries = 0;
548   for (row = 0; row < row_limit(); row++) {
549     if (bci(row) != no_bci)  entries++;
550   }
551   st->print_cr("count(%u) entries(%u)", count(), entries);
552   for (row = 0; row < row_limit(); row++) {
553     if (bci(row) != no_bci) {
554       tab(st);
555       st->print_cr("bci(%d: count(%u) displacement(%d))",
556                    bci(row), bci_count(row), bci_displacement(row));
557     }
558   }
559 }
560 
561 // ==================================================================
562 // BranchData
563 //
564 // A BranchData is used to access profiling data for a two-way branch.
565 // It consists of taken and not_taken counts as well as a data displacement
566 // for the taken case.
567 
post_initialize(BytecodeStream * stream,MethodData * mdo)568 void BranchData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
569   assert(stream->bci() == bci(), "wrong pos");
570   int target = stream->dest();
571   int my_di = mdo->dp_to_di(dp());
572   int target_di = mdo->bci_to_di(target);
573   int offset = target_di - my_di;
574   set_displacement(offset);
575 }
576 
print_data_on(outputStream * st,const char * extra) const577 void BranchData::print_data_on(outputStream* st, const char* extra) const {
578   print_shared(st, "BranchData", extra);
579   st->print_cr("taken(%u) displacement(%d)",
580                taken(), displacement());
581   tab(st);
582   st->print_cr("not taken(%u)", not_taken());
583 }
584 
585 // ==================================================================
586 // MultiBranchData
587 //
588 // A MultiBranchData is used to access profiling information for
589 // a multi-way branch (*switch bytecodes).  It consists of a series
590 // of (count, displacement) pairs, which count the number of times each
591 // case was taken and specify the data displacment for each branch target.
592 
compute_cell_count(BytecodeStream * stream)593 int MultiBranchData::compute_cell_count(BytecodeStream* stream) {
594   int cell_count = 0;
595   if (stream->code() == Bytecodes::_tableswitch) {
596     Bytecode_tableswitch sw(stream->method()(), stream->bcp());
597     cell_count = 1 + per_case_cell_count * (1 + sw.length()); // 1 for default
598   } else {
599     Bytecode_lookupswitch sw(stream->method()(), stream->bcp());
600     cell_count = 1 + per_case_cell_count * (sw.number_of_pairs() + 1); // 1 for default
601   }
602   return cell_count;
603 }
604 
post_initialize(BytecodeStream * stream,MethodData * mdo)605 void MultiBranchData::post_initialize(BytecodeStream* stream,
606                                       MethodData* mdo) {
607   assert(stream->bci() == bci(), "wrong pos");
608   int target;
609   int my_di;
610   int target_di;
611   int offset;
612   if (stream->code() == Bytecodes::_tableswitch) {
613     Bytecode_tableswitch sw(stream->method()(), stream->bcp());
614     int len = sw.length();
615     assert(array_len() == per_case_cell_count * (len + 1), "wrong len");
616     for (int count = 0; count < len; count++) {
617       target = sw.dest_offset_at(count) + bci();
618       my_di = mdo->dp_to_di(dp());
619       target_di = mdo->bci_to_di(target);
620       offset = target_di - my_di;
621       set_displacement_at(count, offset);
622     }
623     target = sw.default_offset() + bci();
624     my_di = mdo->dp_to_di(dp());
625     target_di = mdo->bci_to_di(target);
626     offset = target_di - my_di;
627     set_default_displacement(offset);
628 
629   } else {
630     Bytecode_lookupswitch sw(stream->method()(), stream->bcp());
631     int npairs = sw.number_of_pairs();
632     assert(array_len() == per_case_cell_count * (npairs + 1), "wrong len");
633     for (int count = 0; count < npairs; count++) {
634       LookupswitchPair pair = sw.pair_at(count);
635       target = pair.offset() + bci();
636       my_di = mdo->dp_to_di(dp());
637       target_di = mdo->bci_to_di(target);
638       offset = target_di - my_di;
639       set_displacement_at(count, offset);
640     }
641     target = sw.default_offset() + bci();
642     my_di = mdo->dp_to_di(dp());
643     target_di = mdo->bci_to_di(target);
644     offset = target_di - my_di;
645     set_default_displacement(offset);
646   }
647 }
648 
print_data_on(outputStream * st,const char * extra) const649 void MultiBranchData::print_data_on(outputStream* st, const char* extra) const {
650   print_shared(st, "MultiBranchData", extra);
651   st->print_cr("default_count(%u) displacement(%d)",
652                default_count(), default_displacement());
653   int cases = number_of_cases();
654   for (int i = 0; i < cases; i++) {
655     tab(st);
656     st->print_cr("count(%u) displacement(%d)",
657                  count_at(i), displacement_at(i));
658   }
659 }
660 
print_data_on(outputStream * st,const char * extra) const661 void ArgInfoData::print_data_on(outputStream* st, const char* extra) const {
662   print_shared(st, "ArgInfoData", extra);
663   int nargs = number_of_args();
664   for (int i = 0; i < nargs; i++) {
665     st->print("  0x%x", arg_modified(i));
666   }
667   st->cr();
668 }
669 
compute_cell_count(Method * m)670 int ParametersTypeData::compute_cell_count(Method* m) {
671   if (!MethodData::profile_parameters_for_method(m)) {
672     return 0;
673   }
674   int max = TypeProfileParmsLimit == -1 ? INT_MAX : TypeProfileParmsLimit;
675   int obj_args = TypeStackSlotEntries::compute_cell_count(m->signature(), !m->is_static(), max);
676   if (obj_args > 0) {
677     return obj_args + 1; // 1 cell for array len
678   }
679   return 0;
680 }
681 
post_initialize(BytecodeStream * stream,MethodData * mdo)682 void ParametersTypeData::post_initialize(BytecodeStream* stream, MethodData* mdo) {
683   _parameters.post_initialize(mdo->method()->signature(), !mdo->method()->is_static(), true);
684 }
685 
profiling_enabled()686 bool ParametersTypeData::profiling_enabled() {
687   return MethodData::profile_parameters();
688 }
689 
print_data_on(outputStream * st,const char * extra) const690 void ParametersTypeData::print_data_on(outputStream* st, const char* extra) const {
691   st->print("parameter types"); // FIXME extra ignored?
692   _parameters.print_data_on(st);
693 }
694 
print_data_on(outputStream * st,const char * extra) const695 void SpeculativeTrapData::print_data_on(outputStream* st, const char* extra) const {
696   print_shared(st, "SpeculativeTrapData", extra);
697   tab(st);
698   method()->print_short_name(st);
699   st->cr();
700 }
701 
702 // ==================================================================
703 // MethodData*
704 //
705 // A MethodData* holds information which has been collected about
706 // a method.
707 
allocate(ClassLoaderData * loader_data,const methodHandle & method,TRAPS)708 MethodData* MethodData::allocate(ClassLoaderData* loader_data, const methodHandle& method, TRAPS) {
709   int size = MethodData::compute_allocation_size_in_words(method);
710 
711   return new (loader_data, size, MetaspaceObj::MethodDataType, THREAD)
712     MethodData(method(), size, THREAD);
713 }
714 
bytecode_cell_count(Bytecodes::Code code)715 int MethodData::bytecode_cell_count(Bytecodes::Code code) {
716   if (is_client_compilation_mode_vm()) {
717     return no_profile_data;
718   }
719   switch (code) {
720   case Bytecodes::_checkcast:
721   case Bytecodes::_instanceof:
722   case Bytecodes::_aastore:
723     if (TypeProfileCasts) {
724       return ReceiverTypeData::static_cell_count();
725     } else {
726       return BitData::static_cell_count();
727     }
728   case Bytecodes::_invokespecial:
729   case Bytecodes::_invokestatic:
730     if (MethodData::profile_arguments() || MethodData::profile_return()) {
731       return variable_cell_count;
732     } else {
733       return CounterData::static_cell_count();
734     }
735   case Bytecodes::_goto:
736   case Bytecodes::_goto_w:
737   case Bytecodes::_jsr:
738   case Bytecodes::_jsr_w:
739     return JumpData::static_cell_count();
740   case Bytecodes::_invokevirtual:
741   case Bytecodes::_invokeinterface:
742     if (MethodData::profile_arguments() || MethodData::profile_return()) {
743       return variable_cell_count;
744     } else {
745       return VirtualCallData::static_cell_count();
746     }
747   case Bytecodes::_invokedynamic:
748     if (MethodData::profile_arguments() || MethodData::profile_return()) {
749       return variable_cell_count;
750     } else {
751       return CounterData::static_cell_count();
752     }
753   case Bytecodes::_ret:
754     return RetData::static_cell_count();
755   case Bytecodes::_ifeq:
756   case Bytecodes::_ifne:
757   case Bytecodes::_iflt:
758   case Bytecodes::_ifge:
759   case Bytecodes::_ifgt:
760   case Bytecodes::_ifle:
761   case Bytecodes::_if_icmpeq:
762   case Bytecodes::_if_icmpne:
763   case Bytecodes::_if_icmplt:
764   case Bytecodes::_if_icmpge:
765   case Bytecodes::_if_icmpgt:
766   case Bytecodes::_if_icmple:
767   case Bytecodes::_if_acmpeq:
768   case Bytecodes::_if_acmpne:
769   case Bytecodes::_ifnull:
770   case Bytecodes::_ifnonnull:
771     return BranchData::static_cell_count();
772   case Bytecodes::_lookupswitch:
773   case Bytecodes::_tableswitch:
774     return variable_cell_count;
775   default:
776     return no_profile_data;
777   }
778 }
779 
780 // Compute the size of the profiling information corresponding to
781 // the current bytecode.
compute_data_size(BytecodeStream * stream)782 int MethodData::compute_data_size(BytecodeStream* stream) {
783   int cell_count = bytecode_cell_count(stream->code());
784   if (cell_count == no_profile_data) {
785     return 0;
786   }
787   if (cell_count == variable_cell_count) {
788     switch (stream->code()) {
789     case Bytecodes::_lookupswitch:
790     case Bytecodes::_tableswitch:
791       cell_count = MultiBranchData::compute_cell_count(stream);
792       break;
793     case Bytecodes::_invokespecial:
794     case Bytecodes::_invokestatic:
795     case Bytecodes::_invokedynamic:
796       assert(MethodData::profile_arguments() || MethodData::profile_return(), "should be collecting args profile");
797       if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
798           profile_return_for_invoke(stream->method(), stream->bci())) {
799         cell_count = CallTypeData::compute_cell_count(stream);
800       } else {
801         cell_count = CounterData::static_cell_count();
802       }
803       break;
804     case Bytecodes::_invokevirtual:
805     case Bytecodes::_invokeinterface: {
806       assert(MethodData::profile_arguments() || MethodData::profile_return(), "should be collecting args profile");
807       if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
808           profile_return_for_invoke(stream->method(), stream->bci())) {
809         cell_count = VirtualCallTypeData::compute_cell_count(stream);
810       } else {
811         cell_count = VirtualCallData::static_cell_count();
812       }
813       break;
814     }
815     default:
816       fatal("unexpected bytecode for var length profile data");
817     }
818   }
819   // Note:  cell_count might be zero, meaning that there is just
820   //        a DataLayout header, with no extra cells.
821   assert(cell_count >= 0, "sanity");
822   return DataLayout::compute_size_in_bytes(cell_count);
823 }
824 
is_speculative_trap_bytecode(Bytecodes::Code code)825 bool MethodData::is_speculative_trap_bytecode(Bytecodes::Code code) {
826   // Bytecodes for which we may use speculation
827   switch (code) {
828   case Bytecodes::_checkcast:
829   case Bytecodes::_instanceof:
830   case Bytecodes::_aastore:
831   case Bytecodes::_invokevirtual:
832   case Bytecodes::_invokeinterface:
833   case Bytecodes::_if_acmpeq:
834   case Bytecodes::_if_acmpne:
835   case Bytecodes::_ifnull:
836   case Bytecodes::_ifnonnull:
837   case Bytecodes::_invokestatic:
838 #ifdef COMPILER2
839     if (is_server_compilation_mode_vm()) {
840       return UseTypeSpeculation;
841     }
842 #endif
843   default:
844     return false;
845   }
846   return false;
847 }
848 
compute_extra_data_count(int data_size,int empty_bc_count,bool needs_speculative_traps)849 int MethodData::compute_extra_data_count(int data_size, int empty_bc_count, bool needs_speculative_traps) {
850 #if INCLUDE_JVMCI
851   if (ProfileTraps) {
852     // Assume that up to 30% of the possibly trapping BCIs with no MDP will need to allocate one.
853     int extra_data_count = MIN2(empty_bc_count, MAX2(4, (empty_bc_count * 30) / 100));
854 
855     // Make sure we have a minimum number of extra data slots to
856     // allocate SpeculativeTrapData entries. We would want to have one
857     // entry per compilation that inlines this method and for which
858     // some type speculation assumption fails. So the room we need for
859     // the SpeculativeTrapData entries doesn't directly depend on the
860     // size of the method. Because it's hard to estimate, we reserve
861     // space for an arbitrary number of entries.
862     int spec_data_count = (needs_speculative_traps ? SpecTrapLimitExtraEntries : 0) *
863       (SpeculativeTrapData::static_cell_count() + DataLayout::header_size_in_cells());
864 
865     return MAX2(extra_data_count, spec_data_count);
866   } else {
867     return 0;
868   }
869 #else // INCLUDE_JVMCI
870   if (ProfileTraps) {
871     // Assume that up to 3% of BCIs with no MDP will need to allocate one.
872     int extra_data_count = (uint)(empty_bc_count * 3) / 128 + 1;
873     // If the method is large, let the extra BCIs grow numerous (to ~1%).
874     int one_percent_of_data
875       = (uint)data_size / (DataLayout::header_size_in_bytes()*128);
876     if (extra_data_count < one_percent_of_data)
877       extra_data_count = one_percent_of_data;
878     if (extra_data_count > empty_bc_count)
879       extra_data_count = empty_bc_count;  // no need for more
880 
881     // Make sure we have a minimum number of extra data slots to
882     // allocate SpeculativeTrapData entries. We would want to have one
883     // entry per compilation that inlines this method and for which
884     // some type speculation assumption fails. So the room we need for
885     // the SpeculativeTrapData entries doesn't directly depend on the
886     // size of the method. Because it's hard to estimate, we reserve
887     // space for an arbitrary number of entries.
888     int spec_data_count = (needs_speculative_traps ? SpecTrapLimitExtraEntries : 0) *
889       (SpeculativeTrapData::static_cell_count() + DataLayout::header_size_in_cells());
890 
891     return MAX2(extra_data_count, spec_data_count);
892   } else {
893     return 0;
894   }
895 #endif // INCLUDE_JVMCI
896 }
897 
898 // Compute the size of the MethodData* necessary to store
899 // profiling information about a given method.  Size is in bytes.
compute_allocation_size_in_bytes(const methodHandle & method)900 int MethodData::compute_allocation_size_in_bytes(const methodHandle& method) {
901   int data_size = 0;
902   BytecodeStream stream(method);
903   Bytecodes::Code c;
904   int empty_bc_count = 0;  // number of bytecodes lacking data
905   bool needs_speculative_traps = false;
906   while ((c = stream.next()) >= 0) {
907     int size_in_bytes = compute_data_size(&stream);
908     data_size += size_in_bytes;
909     if (size_in_bytes == 0 JVMCI_ONLY(&& Bytecodes::can_trap(c)))  empty_bc_count += 1;
910     needs_speculative_traps = needs_speculative_traps || is_speculative_trap_bytecode(c);
911   }
912   int object_size = in_bytes(data_offset()) + data_size;
913 
914   // Add some extra DataLayout cells (at least one) to track stray traps.
915   int extra_data_count = compute_extra_data_count(data_size, empty_bc_count, needs_speculative_traps);
916   object_size += extra_data_count * DataLayout::compute_size_in_bytes(0);
917 
918   // Add a cell to record information about modified arguments.
919   int arg_size = method->size_of_parameters();
920   object_size += DataLayout::compute_size_in_bytes(arg_size+1);
921 
922   // Reserve room for an area of the MDO dedicated to profiling of
923   // parameters
924   int args_cell = ParametersTypeData::compute_cell_count(method());
925   if (args_cell > 0) {
926     object_size += DataLayout::compute_size_in_bytes(args_cell);
927   }
928   return object_size;
929 }
930 
931 // Compute the size of the MethodData* necessary to store
932 // profiling information about a given method.  Size is in words
compute_allocation_size_in_words(const methodHandle & method)933 int MethodData::compute_allocation_size_in_words(const methodHandle& method) {
934   int byte_size = compute_allocation_size_in_bytes(method);
935   int word_size = align_up(byte_size, BytesPerWord) / BytesPerWord;
936   return align_metadata_size(word_size);
937 }
938 
939 // Initialize an individual data segment.  Returns the size of
940 // the segment in bytes.
initialize_data(BytecodeStream * stream,int data_index)941 int MethodData::initialize_data(BytecodeStream* stream,
942                                        int data_index) {
943   if (is_client_compilation_mode_vm()) {
944     return 0;
945   }
946   int cell_count = -1;
947   int tag = DataLayout::no_tag;
948   DataLayout* data_layout = data_layout_at(data_index);
949   Bytecodes::Code c = stream->code();
950   switch (c) {
951   case Bytecodes::_checkcast:
952   case Bytecodes::_instanceof:
953   case Bytecodes::_aastore:
954     if (TypeProfileCasts) {
955       cell_count = ReceiverTypeData::static_cell_count();
956       tag = DataLayout::receiver_type_data_tag;
957     } else {
958       cell_count = BitData::static_cell_count();
959       tag = DataLayout::bit_data_tag;
960     }
961     break;
962   case Bytecodes::_invokespecial:
963   case Bytecodes::_invokestatic: {
964     int counter_data_cell_count = CounterData::static_cell_count();
965     if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
966         profile_return_for_invoke(stream->method(), stream->bci())) {
967       cell_count = CallTypeData::compute_cell_count(stream);
968     } else {
969       cell_count = counter_data_cell_count;
970     }
971     if (cell_count > counter_data_cell_count) {
972       tag = DataLayout::call_type_data_tag;
973     } else {
974       tag = DataLayout::counter_data_tag;
975     }
976     break;
977   }
978   case Bytecodes::_goto:
979   case Bytecodes::_goto_w:
980   case Bytecodes::_jsr:
981   case Bytecodes::_jsr_w:
982     cell_count = JumpData::static_cell_count();
983     tag = DataLayout::jump_data_tag;
984     break;
985   case Bytecodes::_invokevirtual:
986   case Bytecodes::_invokeinterface: {
987     int virtual_call_data_cell_count = VirtualCallData::static_cell_count();
988     if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
989         profile_return_for_invoke(stream->method(), stream->bci())) {
990       cell_count = VirtualCallTypeData::compute_cell_count(stream);
991     } else {
992       cell_count = virtual_call_data_cell_count;
993     }
994     if (cell_count > virtual_call_data_cell_count) {
995       tag = DataLayout::virtual_call_type_data_tag;
996     } else {
997       tag = DataLayout::virtual_call_data_tag;
998     }
999     break;
1000   }
1001   case Bytecodes::_invokedynamic: {
1002     // %%% should make a type profile for any invokedynamic that takes a ref argument
1003     int counter_data_cell_count = CounterData::static_cell_count();
1004     if (profile_arguments_for_invoke(stream->method(), stream->bci()) ||
1005         profile_return_for_invoke(stream->method(), stream->bci())) {
1006       cell_count = CallTypeData::compute_cell_count(stream);
1007     } else {
1008       cell_count = counter_data_cell_count;
1009     }
1010     if (cell_count > counter_data_cell_count) {
1011       tag = DataLayout::call_type_data_tag;
1012     } else {
1013       tag = DataLayout::counter_data_tag;
1014     }
1015     break;
1016   }
1017   case Bytecodes::_ret:
1018     cell_count = RetData::static_cell_count();
1019     tag = DataLayout::ret_data_tag;
1020     break;
1021   case Bytecodes::_ifeq:
1022   case Bytecodes::_ifne:
1023   case Bytecodes::_iflt:
1024   case Bytecodes::_ifge:
1025   case Bytecodes::_ifgt:
1026   case Bytecodes::_ifle:
1027   case Bytecodes::_if_icmpeq:
1028   case Bytecodes::_if_icmpne:
1029   case Bytecodes::_if_icmplt:
1030   case Bytecodes::_if_icmpge:
1031   case Bytecodes::_if_icmpgt:
1032   case Bytecodes::_if_icmple:
1033   case Bytecodes::_if_acmpeq:
1034   case Bytecodes::_if_acmpne:
1035   case Bytecodes::_ifnull:
1036   case Bytecodes::_ifnonnull:
1037     cell_count = BranchData::static_cell_count();
1038     tag = DataLayout::branch_data_tag;
1039     break;
1040   case Bytecodes::_lookupswitch:
1041   case Bytecodes::_tableswitch:
1042     cell_count = MultiBranchData::compute_cell_count(stream);
1043     tag = DataLayout::multi_branch_data_tag;
1044     break;
1045   default:
1046     break;
1047   }
1048   assert(tag == DataLayout::multi_branch_data_tag ||
1049          ((MethodData::profile_arguments() || MethodData::profile_return()) &&
1050           (tag == DataLayout::call_type_data_tag ||
1051            tag == DataLayout::counter_data_tag ||
1052            tag == DataLayout::virtual_call_type_data_tag ||
1053            tag == DataLayout::virtual_call_data_tag)) ||
1054          cell_count == bytecode_cell_count(c), "cell counts must agree");
1055   if (cell_count >= 0) {
1056     assert(tag != DataLayout::no_tag, "bad tag");
1057     assert(bytecode_has_profile(c), "agree w/ BHP");
1058     data_layout->initialize(tag, stream->bci(), cell_count);
1059     return DataLayout::compute_size_in_bytes(cell_count);
1060   } else {
1061     assert(!bytecode_has_profile(c), "agree w/ !BHP");
1062     return 0;
1063   }
1064 }
1065 
1066 // Get the data at an arbitrary (sort of) data index.
data_at(int data_index) const1067 ProfileData* MethodData::data_at(int data_index) const {
1068   if (out_of_bounds(data_index)) {
1069     return NULL;
1070   }
1071   DataLayout* data_layout = data_layout_at(data_index);
1072   return data_layout->data_in();
1073 }
1074 
data_in()1075 ProfileData* DataLayout::data_in() {
1076   switch (tag()) {
1077   case DataLayout::no_tag:
1078   default:
1079     ShouldNotReachHere();
1080     return NULL;
1081   case DataLayout::bit_data_tag:
1082     return new BitData(this);
1083   case DataLayout::counter_data_tag:
1084     return new CounterData(this);
1085   case DataLayout::jump_data_tag:
1086     return new JumpData(this);
1087   case DataLayout::receiver_type_data_tag:
1088     return new ReceiverTypeData(this);
1089   case DataLayout::virtual_call_data_tag:
1090     return new VirtualCallData(this);
1091   case DataLayout::ret_data_tag:
1092     return new RetData(this);
1093   case DataLayout::branch_data_tag:
1094     return new BranchData(this);
1095   case DataLayout::multi_branch_data_tag:
1096     return new MultiBranchData(this);
1097   case DataLayout::arg_info_data_tag:
1098     return new ArgInfoData(this);
1099   case DataLayout::call_type_data_tag:
1100     return new CallTypeData(this);
1101   case DataLayout::virtual_call_type_data_tag:
1102     return new VirtualCallTypeData(this);
1103   case DataLayout::parameters_type_data_tag:
1104     return new ParametersTypeData(this);
1105   case DataLayout::speculative_trap_data_tag:
1106     return new SpeculativeTrapData(this);
1107   }
1108 }
1109 
1110 // Iteration over data.
next_data(ProfileData * current) const1111 ProfileData* MethodData::next_data(ProfileData* current) const {
1112   int current_index = dp_to_di(current->dp());
1113   int next_index = current_index + current->size_in_bytes();
1114   ProfileData* next = data_at(next_index);
1115   return next;
1116 }
1117 
1118 // Give each of the data entries a chance to perform specific
1119 // data initialization.
post_initialize(BytecodeStream * stream)1120 void MethodData::post_initialize(BytecodeStream* stream) {
1121   ResourceMark rm;
1122   ProfileData* data;
1123   for (data = first_data(); is_valid(data); data = next_data(data)) {
1124     stream->set_start(data->bci());
1125     stream->next();
1126     data->post_initialize(stream, this);
1127   }
1128   if (_parameters_type_data_di != no_parameters) {
1129     parameters_type_data()->post_initialize(NULL, this);
1130   }
1131 }
1132 
1133 // Initialize the MethodData* corresponding to a given method.
MethodData(const methodHandle & method,int size,TRAPS)1134 MethodData::MethodData(const methodHandle& method, int size, TRAPS)
1135   : _extra_data_lock(Monitor::leaf, "MDO extra data lock"),
1136     _parameters_type_data_di(parameters_uninitialized) {
1137   // Set the method back-pointer.
1138   _method = method();
1139   initialize();
1140 }
1141 
initialize()1142 void MethodData::initialize() {
1143   NoSafepointVerifier no_safepoint;  // init function atomic wrt GC
1144   ResourceMark rm;
1145 
1146   init();
1147   set_creation_mileage(mileage_of(method()));
1148 
1149   // Go through the bytecodes and allocate and initialize the
1150   // corresponding data cells.
1151   int data_size = 0;
1152   int empty_bc_count = 0;  // number of bytecodes lacking data
1153   _data[0] = 0;  // apparently not set below.
1154   BytecodeStream stream(method());
1155   Bytecodes::Code c;
1156   bool needs_speculative_traps = false;
1157   while ((c = stream.next()) >= 0) {
1158     int size_in_bytes = initialize_data(&stream, data_size);
1159     data_size += size_in_bytes;
1160     if (size_in_bytes == 0 JVMCI_ONLY(&& Bytecodes::can_trap(c)))  empty_bc_count += 1;
1161     needs_speculative_traps = needs_speculative_traps || is_speculative_trap_bytecode(c);
1162   }
1163   _data_size = data_size;
1164   int object_size = in_bytes(data_offset()) + data_size;
1165 
1166   // Add some extra DataLayout cells (at least one) to track stray traps.
1167   int extra_data_count = compute_extra_data_count(data_size, empty_bc_count, needs_speculative_traps);
1168   int extra_size = extra_data_count * DataLayout::compute_size_in_bytes(0);
1169 
1170   // Let's zero the space for the extra data
1171   Copy::zero_to_bytes(((address)_data) + data_size, extra_size);
1172 
1173   // Add a cell to record information about modified arguments.
1174   // Set up _args_modified array after traps cells so that
1175   // the code for traps cells works.
1176   DataLayout *dp = data_layout_at(data_size + extra_size);
1177 
1178   int arg_size = method()->size_of_parameters();
1179   dp->initialize(DataLayout::arg_info_data_tag, 0, arg_size+1);
1180 
1181   int arg_data_size = DataLayout::compute_size_in_bytes(arg_size+1);
1182   object_size += extra_size + arg_data_size;
1183 
1184   int parms_cell = ParametersTypeData::compute_cell_count(method());
1185   // If we are profiling parameters, we reserver an area near the end
1186   // of the MDO after the slots for bytecodes (because there's no bci
1187   // for method entry so they don't fit with the framework for the
1188   // profiling of bytecodes). We store the offset within the MDO of
1189   // this area (or -1 if no parameter is profiled)
1190   if (parms_cell > 0) {
1191     object_size += DataLayout::compute_size_in_bytes(parms_cell);
1192     _parameters_type_data_di = data_size + extra_size + arg_data_size;
1193     DataLayout *dp = data_layout_at(data_size + extra_size + arg_data_size);
1194     dp->initialize(DataLayout::parameters_type_data_tag, 0, parms_cell);
1195   } else {
1196     _parameters_type_data_di = no_parameters;
1197   }
1198 
1199   // Set an initial hint. Don't use set_hint_di() because
1200   // first_di() may be out of bounds if data_size is 0.
1201   // In that situation, _hint_di is never used, but at
1202   // least well-defined.
1203   _hint_di = first_di();
1204 
1205   post_initialize(&stream);
1206 
1207   assert(object_size == compute_allocation_size_in_bytes(methodHandle(_method)), "MethodData: computed size != initialized size");
1208   set_size(object_size);
1209 }
1210 
init()1211 void MethodData::init() {
1212   _invocation_counter.init();
1213   _backedge_counter.init();
1214   _invocation_counter_start = 0;
1215   _backedge_counter_start = 0;
1216 
1217   // Set per-method invoke- and backedge mask.
1218   double scale = 1.0;
1219   CompilerOracle::has_option_value(_method, "CompileThresholdScaling", scale);
1220   _invoke_mask = right_n_bits(CompilerConfig::scaled_freq_log(Tier0InvokeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
1221   _backedge_mask = right_n_bits(CompilerConfig::scaled_freq_log(Tier0BackedgeNotifyFreqLog, scale)) << InvocationCounter::count_shift;
1222 
1223   _tenure_traps = 0;
1224   _num_loops = 0;
1225   _num_blocks = 0;
1226   _would_profile = unknown;
1227 
1228 #if INCLUDE_JVMCI
1229   _jvmci_ir_size = 0;
1230 #endif
1231 
1232 #if INCLUDE_RTM_OPT
1233   _rtm_state = NoRTM; // No RTM lock eliding by default
1234   if (UseRTMLocking &&
1235       !CompilerOracle::has_option_string(_method, "NoRTMLockEliding")) {
1236     if (CompilerOracle::has_option_string(_method, "UseRTMLockEliding") || !UseRTMDeopt) {
1237       // Generate RTM lock eliding code without abort ratio calculation code.
1238       _rtm_state = UseRTM;
1239     } else if (UseRTMDeopt) {
1240       // Generate RTM lock eliding code and include abort ratio calculation
1241       // code if UseRTMDeopt is on.
1242       _rtm_state = ProfileRTM;
1243     }
1244   }
1245 #endif
1246 
1247   // Initialize flags and trap history.
1248   _nof_decompiles = 0;
1249   _nof_overflow_recompiles = 0;
1250   _nof_overflow_traps = 0;
1251   clear_escape_info();
1252   assert(sizeof(_trap_hist) % sizeof(HeapWord) == 0, "align");
1253   Copy::zero_to_words((HeapWord*) &_trap_hist,
1254                       sizeof(_trap_hist) / sizeof(HeapWord));
1255 }
1256 
1257 // Get a measure of how much mileage the method has on it.
mileage_of(Method * method)1258 int MethodData::mileage_of(Method* method) {
1259   int mileage = 0;
1260   if (TieredCompilation) {
1261     mileage = MAX2(method->invocation_count(), method->backedge_count());
1262   } else {
1263     int iic = method->interpreter_invocation_count();
1264     if (mileage < iic)  mileage = iic;
1265     MethodCounters* mcs = method->method_counters();
1266     if (mcs != NULL) {
1267       InvocationCounter* ic = mcs->invocation_counter();
1268       InvocationCounter* bc = mcs->backedge_counter();
1269       int icval = ic->count();
1270       if (ic->carry()) icval += CompileThreshold;
1271       if (mileage < icval)  mileage = icval;
1272       int bcval = bc->count();
1273       if (bc->carry()) bcval += CompileThreshold;
1274       if (mileage < bcval)  mileage = bcval;
1275     }
1276   }
1277   return mileage;
1278 }
1279 
is_mature() const1280 bool MethodData::is_mature() const {
1281   return CompilationPolicy::policy()->is_mature(_method);
1282 }
1283 
1284 // Translate a bci to its corresponding data index (di).
bci_to_dp(int bci)1285 address MethodData::bci_to_dp(int bci) {
1286   ResourceMark rm;
1287   ProfileData* data = data_before(bci);
1288   ProfileData* prev = NULL;
1289   for ( ; is_valid(data); data = next_data(data)) {
1290     if (data->bci() >= bci) {
1291       if (data->bci() == bci)  set_hint_di(dp_to_di(data->dp()));
1292       else if (prev != NULL)   set_hint_di(dp_to_di(prev->dp()));
1293       return data->dp();
1294     }
1295     prev = data;
1296   }
1297   return (address)limit_data_position();
1298 }
1299 
1300 // Translate a bci to its corresponding data, or NULL.
bci_to_data(int bci)1301 ProfileData* MethodData::bci_to_data(int bci) {
1302   ProfileData* data = data_before(bci);
1303   for ( ; is_valid(data); data = next_data(data)) {
1304     if (data->bci() == bci) {
1305       set_hint_di(dp_to_di(data->dp()));
1306       return data;
1307     } else if (data->bci() > bci) {
1308       break;
1309     }
1310   }
1311   return bci_to_extra_data(bci, NULL, false);
1312 }
1313 
next_extra(DataLayout * dp)1314 DataLayout* MethodData::next_extra(DataLayout* dp) {
1315   int nb_cells = 0;
1316   switch(dp->tag()) {
1317   case DataLayout::bit_data_tag:
1318   case DataLayout::no_tag:
1319     nb_cells = BitData::static_cell_count();
1320     break;
1321   case DataLayout::speculative_trap_data_tag:
1322     nb_cells = SpeculativeTrapData::static_cell_count();
1323     break;
1324   default:
1325     fatal("unexpected tag %d", dp->tag());
1326   }
1327   return (DataLayout*)((address)dp + DataLayout::compute_size_in_bytes(nb_cells));
1328 }
1329 
bci_to_extra_data_helper(int bci,Method * m,DataLayout * & dp,bool concurrent)1330 ProfileData* MethodData::bci_to_extra_data_helper(int bci, Method* m, DataLayout*& dp, bool concurrent) {
1331   DataLayout* end = args_data_limit();
1332 
1333   for (;; dp = next_extra(dp)) {
1334     assert(dp < end, "moved past end of extra data");
1335     // No need for "OrderAccess::load_acquire" ops,
1336     // since the data structure is monotonic.
1337     switch(dp->tag()) {
1338     case DataLayout::no_tag:
1339       return NULL;
1340     case DataLayout::arg_info_data_tag:
1341       dp = end;
1342       return NULL; // ArgInfoData is at the end of extra data section.
1343     case DataLayout::bit_data_tag:
1344       if (m == NULL && dp->bci() == bci) {
1345         return new BitData(dp);
1346       }
1347       break;
1348     case DataLayout::speculative_trap_data_tag:
1349       if (m != NULL) {
1350         SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1351         // data->method() may be null in case of a concurrent
1352         // allocation. Maybe it's for the same method. Try to use that
1353         // entry in that case.
1354         if (dp->bci() == bci) {
1355           if (data->method() == NULL) {
1356             assert(concurrent, "impossible because no concurrent allocation");
1357             return NULL;
1358           } else if (data->method() == m) {
1359             return data;
1360           }
1361         }
1362       }
1363       break;
1364     default:
1365       fatal("unexpected tag %d", dp->tag());
1366     }
1367   }
1368   return NULL;
1369 }
1370 
1371 
1372 // Translate a bci to its corresponding extra data, or NULL.
bci_to_extra_data(int bci,Method * m,bool create_if_missing)1373 ProfileData* MethodData::bci_to_extra_data(int bci, Method* m, bool create_if_missing) {
1374   // This code assumes an entry for a SpeculativeTrapData is 2 cells
1375   assert(2*DataLayout::compute_size_in_bytes(BitData::static_cell_count()) ==
1376          DataLayout::compute_size_in_bytes(SpeculativeTrapData::static_cell_count()),
1377          "code needs to be adjusted");
1378 
1379   // Do not create one of these if method has been redefined.
1380   if (m != NULL && m->is_old()) {
1381     return NULL;
1382   }
1383 
1384   DataLayout* dp  = extra_data_base();
1385   DataLayout* end = args_data_limit();
1386 
1387   // Allocation in the extra data space has to be atomic because not
1388   // all entries have the same size and non atomic concurrent
1389   // allocation would result in a corrupted extra data space.
1390   ProfileData* result = bci_to_extra_data_helper(bci, m, dp, true);
1391   if (result != NULL) {
1392     return result;
1393   }
1394 
1395   if (create_if_missing && dp < end) {
1396     MutexLocker ml(&_extra_data_lock);
1397     // Check again now that we have the lock. Another thread may
1398     // have added extra data entries.
1399     ProfileData* result = bci_to_extra_data_helper(bci, m, dp, false);
1400     if (result != NULL || dp >= end) {
1401       return result;
1402     }
1403 
1404     assert(dp->tag() == DataLayout::no_tag || (dp->tag() == DataLayout::speculative_trap_data_tag && m != NULL), "should be free");
1405     assert(next_extra(dp)->tag() == DataLayout::no_tag || next_extra(dp)->tag() == DataLayout::arg_info_data_tag, "should be free or arg info");
1406     u1 tag = m == NULL ? DataLayout::bit_data_tag : DataLayout::speculative_trap_data_tag;
1407     // SpeculativeTrapData is 2 slots. Make sure we have room.
1408     if (m != NULL && next_extra(dp)->tag() != DataLayout::no_tag) {
1409       return NULL;
1410     }
1411     DataLayout temp;
1412     temp.initialize(tag, bci, 0);
1413 
1414     dp->set_header(temp.header());
1415     assert(dp->tag() == tag, "sane");
1416     assert(dp->bci() == bci, "no concurrent allocation");
1417     if (tag == DataLayout::bit_data_tag) {
1418       return new BitData(dp);
1419     } else {
1420       SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1421       data->set_method(m);
1422       return data;
1423     }
1424   }
1425   return NULL;
1426 }
1427 
arg_info()1428 ArgInfoData *MethodData::arg_info() {
1429   DataLayout* dp    = extra_data_base();
1430   DataLayout* end   = args_data_limit();
1431   for (; dp < end; dp = next_extra(dp)) {
1432     if (dp->tag() == DataLayout::arg_info_data_tag)
1433       return new ArgInfoData(dp);
1434   }
1435   return NULL;
1436 }
1437 
1438 // Printing
1439 
print_on(outputStream * st) const1440 void MethodData::print_on(outputStream* st) const {
1441   assert(is_methodData(), "should be method data");
1442   st->print("method data for ");
1443   method()->print_value_on(st);
1444   st->cr();
1445   print_data_on(st);
1446 }
1447 
print_value_on(outputStream * st) const1448 void MethodData::print_value_on(outputStream* st) const {
1449   assert(is_methodData(), "should be method data");
1450   st->print("method data for ");
1451   method()->print_value_on(st);
1452 }
1453 
print_data_on(outputStream * st) const1454 void MethodData::print_data_on(outputStream* st) const {
1455   ResourceMark rm;
1456   ProfileData* data = first_data();
1457   if (_parameters_type_data_di != no_parameters) {
1458     parameters_type_data()->print_data_on(st);
1459   }
1460   for ( ; is_valid(data); data = next_data(data)) {
1461     st->print("%d", dp_to_di(data->dp()));
1462     st->fill_to(6);
1463     data->print_data_on(st, this);
1464   }
1465   st->print_cr("--- Extra data:");
1466   DataLayout* dp    = extra_data_base();
1467   DataLayout* end   = args_data_limit();
1468   for (;; dp = next_extra(dp)) {
1469     assert(dp < end, "moved past end of extra data");
1470     // No need for "OrderAccess::load_acquire" ops,
1471     // since the data structure is monotonic.
1472     switch(dp->tag()) {
1473     case DataLayout::no_tag:
1474       continue;
1475     case DataLayout::bit_data_tag:
1476       data = new BitData(dp);
1477       break;
1478     case DataLayout::speculative_trap_data_tag:
1479       data = new SpeculativeTrapData(dp);
1480       break;
1481     case DataLayout::arg_info_data_tag:
1482       data = new ArgInfoData(dp);
1483       dp = end; // ArgInfoData is at the end of extra data section.
1484       break;
1485     default:
1486       fatal("unexpected tag %d", dp->tag());
1487     }
1488     st->print("%d", dp_to_di(data->dp()));
1489     st->fill_to(6);
1490     data->print_data_on(st);
1491     if (dp >= end) return;
1492   }
1493 }
1494 
1495 #if INCLUDE_SERVICES
1496 // Size Statistics
collect_statistics(KlassSizeStats * sz) const1497 void MethodData::collect_statistics(KlassSizeStats *sz) const {
1498   int n = sz->count(this);
1499   sz->_method_data_bytes += n;
1500   sz->_method_all_bytes += n;
1501   sz->_rw_bytes += n;
1502 }
1503 #endif // INCLUDE_SERVICES
1504 
1505 // Verification
1506 
verify_on(outputStream * st)1507 void MethodData::verify_on(outputStream* st) {
1508   guarantee(is_methodData(), "object must be method data");
1509   // guarantee(m->is_perm(), "should be in permspace");
1510   this->verify_data_on(st);
1511 }
1512 
verify_data_on(outputStream * st)1513 void MethodData::verify_data_on(outputStream* st) {
1514   NEEDS_CLEANUP;
1515   // not yet implemented.
1516 }
1517 
profile_jsr292(const methodHandle & m,int bci)1518 bool MethodData::profile_jsr292(const methodHandle& m, int bci) {
1519   if (m->is_compiled_lambda_form()) {
1520     return true;
1521   }
1522 
1523   Bytecode_invoke inv(m , bci);
1524   return inv.is_invokedynamic() || inv.is_invokehandle();
1525 }
1526 
profile_unsafe(const methodHandle & m,int bci)1527 bool MethodData::profile_unsafe(const methodHandle& m, int bci) {
1528   Bytecode_invoke inv(m , bci);
1529   if (inv.is_invokevirtual() && inv.klass() == vmSymbols::jdk_internal_misc_Unsafe()) {
1530     ResourceMark rm;
1531     char* name = inv.name()->as_C_string();
1532     if (!strncmp(name, "get", 3) || !strncmp(name, "put", 3)) {
1533       return true;
1534     }
1535   }
1536   return false;
1537 }
1538 
profile_arguments_flag()1539 int MethodData::profile_arguments_flag() {
1540   return TypeProfileLevel % 10;
1541 }
1542 
profile_arguments()1543 bool MethodData::profile_arguments() {
1544   return profile_arguments_flag() > no_type_profile && profile_arguments_flag() <= type_profile_all;
1545 }
1546 
profile_arguments_jsr292_only()1547 bool MethodData::profile_arguments_jsr292_only() {
1548   return profile_arguments_flag() == type_profile_jsr292;
1549 }
1550 
profile_all_arguments()1551 bool MethodData::profile_all_arguments() {
1552   return profile_arguments_flag() == type_profile_all;
1553 }
1554 
profile_arguments_for_invoke(const methodHandle & m,int bci)1555 bool MethodData::profile_arguments_for_invoke(const methodHandle& m, int bci) {
1556   if (!profile_arguments()) {
1557     return false;
1558   }
1559 
1560   if (profile_all_arguments()) {
1561     return true;
1562   }
1563 
1564   if (profile_unsafe(m, bci)) {
1565     return true;
1566   }
1567 
1568   assert(profile_arguments_jsr292_only(), "inconsistent");
1569   return profile_jsr292(m, bci);
1570 }
1571 
profile_return_flag()1572 int MethodData::profile_return_flag() {
1573   return (TypeProfileLevel % 100) / 10;
1574 }
1575 
profile_return()1576 bool MethodData::profile_return() {
1577   return profile_return_flag() > no_type_profile && profile_return_flag() <= type_profile_all;
1578 }
1579 
profile_return_jsr292_only()1580 bool MethodData::profile_return_jsr292_only() {
1581   return profile_return_flag() == type_profile_jsr292;
1582 }
1583 
profile_all_return()1584 bool MethodData::profile_all_return() {
1585   return profile_return_flag() == type_profile_all;
1586 }
1587 
profile_return_for_invoke(const methodHandle & m,int bci)1588 bool MethodData::profile_return_for_invoke(const methodHandle& m, int bci) {
1589   if (!profile_return()) {
1590     return false;
1591   }
1592 
1593   if (profile_all_return()) {
1594     return true;
1595   }
1596 
1597   assert(profile_return_jsr292_only(), "inconsistent");
1598   return profile_jsr292(m, bci);
1599 }
1600 
profile_parameters_flag()1601 int MethodData::profile_parameters_flag() {
1602   return TypeProfileLevel / 100;
1603 }
1604 
profile_parameters()1605 bool MethodData::profile_parameters() {
1606   return profile_parameters_flag() > no_type_profile && profile_parameters_flag() <= type_profile_all;
1607 }
1608 
profile_parameters_jsr292_only()1609 bool MethodData::profile_parameters_jsr292_only() {
1610   return profile_parameters_flag() == type_profile_jsr292;
1611 }
1612 
profile_all_parameters()1613 bool MethodData::profile_all_parameters() {
1614   return profile_parameters_flag() == type_profile_all;
1615 }
1616 
profile_parameters_for_method(const methodHandle & m)1617 bool MethodData::profile_parameters_for_method(const methodHandle& m) {
1618   if (!profile_parameters()) {
1619     return false;
1620   }
1621 
1622   if (profile_all_parameters()) {
1623     return true;
1624   }
1625 
1626   assert(profile_parameters_jsr292_only(), "inconsistent");
1627   return m->is_compiled_lambda_form();
1628 }
1629 
metaspace_pointers_do(MetaspaceClosure * it)1630 void MethodData::metaspace_pointers_do(MetaspaceClosure* it) {
1631   log_trace(cds)("Iter(MethodData): %p", this);
1632   it->push(&_method);
1633 }
1634 
clean_extra_data_helper(DataLayout * dp,int shift,bool reset)1635 void MethodData::clean_extra_data_helper(DataLayout* dp, int shift, bool reset) {
1636   if (shift == 0) {
1637     return;
1638   }
1639   if (!reset) {
1640     // Move all cells of trap entry at dp left by "shift" cells
1641     intptr_t* start = (intptr_t*)dp;
1642     intptr_t* end = (intptr_t*)next_extra(dp);
1643     for (intptr_t* ptr = start; ptr < end; ptr++) {
1644       *(ptr-shift) = *ptr;
1645     }
1646   } else {
1647     // Reset "shift" cells stopping at dp
1648     intptr_t* start = ((intptr_t*)dp) - shift;
1649     intptr_t* end = (intptr_t*)dp;
1650     for (intptr_t* ptr = start; ptr < end; ptr++) {
1651       *ptr = 0;
1652     }
1653   }
1654 }
1655 
1656 // Check for entries that reference an unloaded method
1657 class CleanExtraDataKlassClosure : public CleanExtraDataClosure {
1658   bool _always_clean;
1659 public:
CleanExtraDataKlassClosure(bool always_clean)1660   CleanExtraDataKlassClosure(bool always_clean) : _always_clean(always_clean) {}
is_live(Method * m)1661   bool is_live(Method* m) {
1662     return !(_always_clean) && m->method_holder()->is_loader_alive();
1663   }
1664 };
1665 
1666 // Check for entries that reference a redefined method
1667 class CleanExtraDataMethodClosure : public CleanExtraDataClosure {
1668 public:
CleanExtraDataMethodClosure()1669   CleanExtraDataMethodClosure() {}
is_live(Method * m)1670   bool is_live(Method* m) { return !m->is_old(); }
1671 };
1672 
1673 
1674 // Remove SpeculativeTrapData entries that reference an unloaded or
1675 // redefined method
clean_extra_data(CleanExtraDataClosure * cl)1676 void MethodData::clean_extra_data(CleanExtraDataClosure* cl) {
1677   DataLayout* dp  = extra_data_base();
1678   DataLayout* end = args_data_limit();
1679 
1680   int shift = 0;
1681   for (; dp < end; dp = next_extra(dp)) {
1682     switch(dp->tag()) {
1683     case DataLayout::speculative_trap_data_tag: {
1684       SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1685       Method* m = data->method();
1686       assert(m != NULL, "should have a method");
1687       if (!cl->is_live(m)) {
1688         // "shift" accumulates the number of cells for dead
1689         // SpeculativeTrapData entries that have been seen so
1690         // far. Following entries must be shifted left by that many
1691         // cells to remove the dead SpeculativeTrapData entries.
1692         shift += (int)((intptr_t*)next_extra(dp) - (intptr_t*)dp);
1693       } else {
1694         // Shift this entry left if it follows dead
1695         // SpeculativeTrapData entries
1696         clean_extra_data_helper(dp, shift);
1697       }
1698       break;
1699     }
1700     case DataLayout::bit_data_tag:
1701       // Shift this entry left if it follows dead SpeculativeTrapData
1702       // entries
1703       clean_extra_data_helper(dp, shift);
1704       continue;
1705     case DataLayout::no_tag:
1706     case DataLayout::arg_info_data_tag:
1707       // We are at end of the live trap entries. The previous "shift"
1708       // cells contain entries that are either dead or were shifted
1709       // left. They need to be reset to no_tag
1710       clean_extra_data_helper(dp, shift, true);
1711       return;
1712     default:
1713       fatal("unexpected tag %d", dp->tag());
1714     }
1715   }
1716 }
1717 
1718 // Verify there's no unloaded or redefined method referenced by a
1719 // SpeculativeTrapData entry
verify_extra_data_clean(CleanExtraDataClosure * cl)1720 void MethodData::verify_extra_data_clean(CleanExtraDataClosure* cl) {
1721 #ifdef ASSERT
1722   DataLayout* dp  = extra_data_base();
1723   DataLayout* end = args_data_limit();
1724 
1725   for (; dp < end; dp = next_extra(dp)) {
1726     switch(dp->tag()) {
1727     case DataLayout::speculative_trap_data_tag: {
1728       SpeculativeTrapData* data = new SpeculativeTrapData(dp);
1729       Method* m = data->method();
1730       assert(m != NULL && cl->is_live(m), "Method should exist");
1731       break;
1732     }
1733     case DataLayout::bit_data_tag:
1734       continue;
1735     case DataLayout::no_tag:
1736     case DataLayout::arg_info_data_tag:
1737       return;
1738     default:
1739       fatal("unexpected tag %d", dp->tag());
1740     }
1741   }
1742 #endif
1743 }
1744 
clean_method_data(bool always_clean)1745 void MethodData::clean_method_data(bool always_clean) {
1746   ResourceMark rm;
1747   for (ProfileData* data = first_data();
1748        is_valid(data);
1749        data = next_data(data)) {
1750     data->clean_weak_klass_links(always_clean);
1751   }
1752   ParametersTypeData* parameters = parameters_type_data();
1753   if (parameters != NULL) {
1754     parameters->clean_weak_klass_links(always_clean);
1755   }
1756 
1757   CleanExtraDataKlassClosure cl(always_clean);
1758   clean_extra_data(&cl);
1759   verify_extra_data_clean(&cl);
1760 }
1761 
1762 // This is called during redefinition to clean all "old" redefined
1763 // methods out of MethodData for all methods.
clean_weak_method_links()1764 void MethodData::clean_weak_method_links() {
1765   ResourceMark rm;
1766   for (ProfileData* data = first_data();
1767        is_valid(data);
1768        data = next_data(data)) {
1769     data->clean_weak_method_links();
1770   }
1771 
1772   CleanExtraDataMethodClosure cl;
1773   clean_extra_data(&cl);
1774   verify_extra_data_clean(&cl);
1775 }
1776 
1777 #ifdef ASSERT
verify_clean_weak_method_links()1778 void MethodData::verify_clean_weak_method_links() {
1779   ResourceMark rm;
1780   for (ProfileData* data = first_data();
1781        is_valid(data);
1782        data = next_data(data)) {
1783     data->verify_clean_weak_method_links();
1784   }
1785 
1786   CleanExtraDataMethodClosure cl;
1787   verify_extra_data_clean(&cl);
1788 }
1789 #endif // ASSERT
1790