1 /*
  2  * Copyright (c) 2001, 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 "ci/ciMetadata.hpp"
 26 #include "ci/ciMethodData.hpp"
 27 #include "ci/ciReplay.hpp"
 28 #include "ci/ciUtilities.inline.hpp"
 29 #include "compiler/compiler_globals.hpp"
 30 #include "memory/allocation.inline.hpp"
 31 #include "memory/resourceArea.hpp"
 32 #include "oops/klass.inline.hpp"
 33 #include "oops/methodData.inline.hpp"
 34 #include "runtime/deoptimization.hpp"
 35 #include "utilities/copy.hpp"
 36 
 37 // ciMethodData
 38 
 39 // ------------------------------------------------------------------
 40 // ciMethodData::ciMethodData
 41 //
 42 ciMethodData::ciMethodData(MethodData* md)
 43 : ciMetadata(md),
 44   _data_size(0), _extra_data_size(0), _data(nullptr),
 45   _parameters_data_offset(0),
 46   _exception_handlers_data_offset(0),
 47   // Set an initial hint. Don't use set_hint_di() because
 48   // first_di() may be out of bounds if data_size is 0.
 49   _hint_di(first_di()),
 50   _state(empty_state),
 51   _saw_free_extra_data(false),
 52   // Initialize the escape information (to "don't know.");
 53   _eflags(0), _arg_local(0), _arg_stack(0), _arg_returned(0),
 54   _invocation_counter(0),
 55   _orig() {}
 56 
 57 // Check for entries that reference an unloaded method
 58 class PrepareExtraDataClosure : public CleanExtraDataClosure {
 59   MethodData*            _mdo;
 60   SafepointStateTracker  _safepoint_tracker;
 61   GrowableArray<Method*> _uncached_methods;
 62 
 63 public:
 64   PrepareExtraDataClosure(MethodData* mdo)
 65     : _mdo(mdo),
 66       _safepoint_tracker(SafepointSynchronize::safepoint_state_tracker()),
 67       _uncached_methods()
 68   { }
 69 
 70   bool is_live(Method* m) {
 71     Klass* holder = m->method_holder();
 72     if (holder == nullptr || // premain: not yet loaded
 73         holder->class_loader_data() == nullptr ||
 74         !holder->is_loader_alive() ||
 75         (holder->is_instance_klass() && !InstanceKlass::cast(holder)->is_loaded())) {
 76       return false;
 77     }
 78     if (CURRENT_ENV->cached_metadata(m) == nullptr) {
 79       // Uncached entries need to be pre-populated.
 80       _uncached_methods.append(m);
 81     }
 82     return true;
 83   }
 84 
 85   bool has_safepointed() {
 86     return _safepoint_tracker.safepoint_state_changed();
 87   }
 88 
 89   bool finish() {
 90     if (_uncached_methods.length() == 0) {
 91       // Preparation finished iff all Methods* were already cached.
 92       return true;
 93     }
 94     // We are currently holding the extra_data_lock and ensuring
 95     // no safepoint breaks the lock.
 96     _mdo->check_extra_data_locked();
 97 
 98     // We now want to cache some method data. This could cause a safepoint.
 99     // We temporarily release the lock and allow safepoints, and revert that
100     // at the end of the scope. This is safe, since we currently do not hold
101     // any extra_method_data: finish is called only after clean_extra_data,
102     // and the outer scope that first aquired the lock should not hold any
103     // extra_method_data while cleaning is performed, as the offsets can change.
104     MutexUnlocker mu(_mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
105 
106     for (int i = 0; i < _uncached_methods.length(); ++i) {
107       if (has_safepointed()) {
108         // The metadata in the growable array might contain stale
109         // entries after a safepoint.
110         return false;
111       }
112       Method* method = _uncached_methods.at(i);
113       // Populating ciEnv caches may cause safepoints due
114       // to taking the Compile_lock with safepoint checks.
115       (void)CURRENT_ENV->get_method(method);
116     }
117     return false;
118   }
119 };
120 
121 void ciMethodData::prepare_metadata() {
122   MethodData* mdo = get_MethodData();
123 
124   for (;;) {
125     ResourceMark rm;
126     PrepareExtraDataClosure cl(mdo);
127     mdo->clean_extra_data(&cl);
128     if (cl.finish()) {
129       // When encountering uncached metadata, the Compile_lock might be
130       // acquired when creating ciMetadata handles, causing safepoints
131       // which requires a new round of preparation to clean out potentially
132       // new unloading metadata.
133       return;
134     }
135   }
136 }
137 
138 void ciMethodData::load_remaining_extra_data() {
139   MethodData* mdo = get_MethodData();
140 
141   // Lock to read ProfileData, and ensure lock is not unintentionally broken by a safepoint
142   MutexLocker ml(mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
143 
144   // Deferred metadata cleaning due to concurrent class unloading.
145   prepare_metadata();
146   // After metadata preparation, there is no stale metadata,
147   // and no safepoints can introduce more stale metadata.
148   NoSafepointVerifier no_safepoint;
149 
150   assert((mdo->data_size() == _data_size) && (mdo->extra_data_size() == _extra_data_size), "sanity, unchanged");
151   assert(extra_data_base() == (DataLayout*)((address) _data + _data_size), "sanity");
152 
153   // Copy the extra data once it is prepared (i.e. cache populated, no release of extra data lock anymore)
154   Copy::disjoint_words_atomic((HeapWord*) mdo->extra_data_base(),
155                               (HeapWord*) extra_data_base(),
156                               // copy everything from extra_data_base() up to parameters_data_base()
157                               pointer_delta(parameters_data_base(), extra_data_base(), HeapWordSize));
158 
159   // skip parameter data copying. Already done in 'load_data'
160 
161   // copy exception handler data
162   Copy::disjoint_words_atomic((HeapWord*) mdo->exception_handler_data_base(),
163                               (HeapWord*) exception_handler_data_base(),
164                               exception_handler_data_size() / HeapWordSize);
165 
166   // speculative trap entries also hold a pointer to a Method so need to be translated
167   DataLayout* dp_src  = mdo->extra_data_base();
168   DataLayout* end_src = mdo->args_data_limit();
169   DataLayout* dp_dst  = extra_data_base();
170   for (;; dp_src = MethodData::next_extra(dp_src), dp_dst = MethodData::next_extra(dp_dst)) {
171     assert(dp_src < end_src, "moved past end of extra data");
172     assert(((intptr_t)dp_dst) - ((intptr_t)extra_data_base()) == ((intptr_t)dp_src) - ((intptr_t)mdo->extra_data_base()), "source and destination don't match");
173 
174     int tag = dp_src->tag();
175     switch(tag) {
176     case DataLayout::speculative_trap_data_tag: {
177       ciSpeculativeTrapData data_dst(dp_dst);
178       SpeculativeTrapData   data_src(dp_src);
179       data_dst.translate_from(&data_src);
180       break;
181     }
182     case DataLayout::bit_data_tag:
183       break;
184     case DataLayout::no_tag:
185     case DataLayout::arg_info_data_tag:
186       // An empty slot or ArgInfoData entry marks the end of the trap data
187       {
188         return; // Need a block to avoid SS compiler bug
189       }
190     default:
191       fatal("bad tag = %d", tag);
192     }
193   }
194 }
195 
196 bool ciMethodData::load_data() {
197   MethodData* mdo = get_MethodData();
198   if (mdo == nullptr) {
199     return false;
200   }
201 
202   // To do: don't copy the data if it is not "ripe" -- require a minimum #
203   // of invocations.
204 
205   // Snapshot the data and extra parameter data first without the extra trap and arg info data.
206   // Those are copied in a second step. Actually, an approximate snapshot of the data is taken.
207   // Any concurrently executing threads may be changing the data as we copy it.
208   //
209   // The first snapshot step requires two copies (data entries and parameter data entries) since
210   // the MDO is laid out as follows:
211   //
212   //  data_base:        ---------------------------
213   //                    |       data entries      |
214   //                    |           ...           |
215   //  extra_data_base:  ---------------------------
216   //                    |    trap data entries    |
217   //                    |           ...           |
218   //                    | one arg info data entry |
219   //                    |    data for each arg    |
220   //                    |           ...           |
221   //  args_data_limit:  ---------------------------
222   //                    |  parameter data entries |
223   //                    |           ...           |
224   //  param_data_limit: ---------------------------
225   //                    | ex handler data entries |
226   //                    |           ...           |
227   //  extra_data_limit: ---------------------------
228   //
229   // _data_size = extra_data_base - data_base
230   // _extra_data_size = extra_data_limit - extra_data_base
231   // total_size = _data_size + _extra_data_size
232   // args_data_limit = param_data_base
233   // param_data_limit = exception_handler_data_base
234   // extra_data_limit = extra_data_limit
235 
236 #ifndef ZERO
237   // Some Zero platforms do not have expected alignment, and do not use
238   // this code. static_assert would still fire and fail for them.
239   static_assert(sizeof(_orig) % HeapWordSize == 0, "align");
240 #endif
241   Copy::disjoint_words_atomic((HeapWord*) &mdo->_compiler_counters,
242                               (HeapWord*) &_orig,
243                               sizeof(_orig) / HeapWordSize);
244   Arena* arena = CURRENT_ENV->arena();
245   _data_size = mdo->data_size();
246   _extra_data_size = mdo->extra_data_size();
247   int total_size = _data_size + _extra_data_size;
248   _data = (intptr_t *) arena->Amalloc(total_size);
249   Copy::disjoint_words_atomic((HeapWord*) mdo->data_base(),
250                               (HeapWord*) _data,
251                               _data_size / HeapWordSize);
252   // Copy offsets. This is used below
253   _parameters_data_offset = mdo->parameters_type_data_di();
254   _exception_handlers_data_offset = mdo->exception_handlers_data_di();
255 
256   int parameters_data_size = mdo->parameters_size_in_bytes();
257   if (parameters_data_size > 0) {
258     // Snapshot the parameter data
259     Copy::disjoint_words_atomic((HeapWord*) mdo->parameters_data_base(),
260                                 (HeapWord*) parameters_data_base(),
261                                 parameters_data_size / HeapWordSize);
262   }
263   // Traverse the profile data, translating any oops into their
264   // ci equivalents.
265   ResourceMark rm;
266   ciProfileData* ci_data = first_data();
267   ProfileData* data = mdo->first_data();
268   while (is_valid(ci_data)) {
269     ci_data->translate_from(data);
270     ci_data = next_data(ci_data);
271     data = mdo->next_data(data);
272   }
273   if (mdo->parameters_type_data() != nullptr) {
274     DataLayout* parameters_data = data_layout_at(_parameters_data_offset);
275     ciParametersTypeData* parameters = new ciParametersTypeData(parameters_data);
276     parameters->translate_from(mdo->parameters_type_data());
277   }
278 
279   assert((DataLayout*) ((address)_data + total_size - parameters_data_size - exception_handler_data_size()) == args_data_limit(),
280       "sanity - parameter data starts after the argument data of the single ArgInfoData entry");
281   load_remaining_extra_data();
282 
283   // Note:  Extra data are all BitData, and do not need translation.
284   _invocation_counter = mdo->invocation_count();
285   if (_invocation_counter == 0 && mdo->backedge_count() > 0) {
286     // Avoid skewing counter data during OSR compilation.
287     // Sometimes, MDO is allocated during the very first invocation and OSR compilation is triggered
288     // solely by backedge counter while invocation counter stays zero. In such case, it's important
289     // to observe non-zero invocation count to properly scale profile counts (see ciMethod::scale_count()).
290     _invocation_counter = 1;
291   }
292 
293   _state = mdo->is_mature() ? mature_state : immature_state;
294   _eflags = mdo->eflags();
295   _arg_local = mdo->arg_local();
296   _arg_stack = mdo->arg_stack();
297   _arg_returned  = mdo->arg_returned();
298   if (ReplayCompiles) {
299     ciReplay::initialize(this);
300     if (is_empty()) {
301       return false;
302     }
303   }
304   return true;
305 }
306 
307 void ciReceiverTypeData::translate_receiver_data_from(const ProfileData* data) {
308   for (uint row = 0; row < row_limit(); row++) {
309     Klass* k = data->as_ReceiverTypeData()->receiver(row);
310     if (k != nullptr && k->class_loader_data() != nullptr &&
311         (!k->is_instance_klass() || InstanceKlass::cast(k)->is_loaded())) {
312       if (k->is_loader_alive()) {
313         ciKlass* klass = CURRENT_ENV->get_klass(k);
314         set_receiver(row, klass);
315       } else {
316         // With concurrent class unloading, the MDO could have stale metadata; override it
317         clear_row(row);
318       }
319     } else {
320       set_receiver(row, nullptr);
321     }
322   }
323 }
324 
325 void ciTypeStackSlotEntries::translate_type_data_from(const TypeStackSlotEntries* entries) {
326   for (int i = 0; i < number_of_entries(); i++) {
327     intptr_t k = entries->type(i);
328     Klass* klass = (Klass*)klass_part(k);
329     if (klass != nullptr &&
330         ((klass->is_instance_klass() && !InstanceKlass::cast(klass)->is_loaded()) ||
331          (klass->class_loader_data() == nullptr || !klass->is_loader_alive()))) {
332       // With concurrent class unloading, the MDO could have stale metadata; override it
333       TypeStackSlotEntries::set_type(i, TypeStackSlotEntries::with_status((Klass*)nullptr, k));
334     } else {
335       TypeStackSlotEntries::set_type(i, translate_klass(k));
336     }
337   }
338 }
339 
340 void ciReturnTypeEntry::translate_type_data_from(const ReturnTypeEntry* ret) {
341   intptr_t k = ret->type();
342   Klass* klass = (Klass*)klass_part(k);
343   if (klass != nullptr &&
344       ((klass->is_instance_klass() && !InstanceKlass::cast(klass)->is_loaded()) ||
345        (klass->class_loader_data() == nullptr || !klass->is_loader_alive()))) {
346     // With concurrent class unloading, the MDO could have stale metadata; override it
347     set_type(ReturnTypeEntry::with_status((Klass*)nullptr, k));
348   } else {
349     set_type(translate_klass(k));
350   }
351 }
352 
353 void ciSpeculativeTrapData::translate_from(const ProfileData* data) {
354   Method* m = data->as_SpeculativeTrapData()->method();
355   ciMethod* ci_m = CURRENT_ENV->get_method(m);
356   set_method(ci_m);
357 }
358 
359 // Get the data at an arbitrary (sort of) data index.
360 ciProfileData* ciMethodData::data_at(int data_index) {
361   if (out_of_bounds(data_index)) {
362     return nullptr;
363   }
364   DataLayout* data_layout = data_layout_at(data_index);
365   return data_from(data_layout);
366 }
367 
368 ciProfileData* ciMethodData::data_from(DataLayout* data_layout) {
369   switch (data_layout->tag()) {
370   case DataLayout::no_tag:
371   default:
372     ShouldNotReachHere();
373     return nullptr;
374   case DataLayout::bit_data_tag:
375     return new ciBitData(data_layout);
376   case DataLayout::counter_data_tag:
377     return new ciCounterData(data_layout);
378   case DataLayout::jump_data_tag:
379     return new ciJumpData(data_layout);
380   case DataLayout::receiver_type_data_tag:
381     return new ciReceiverTypeData(data_layout);
382   case DataLayout::virtual_call_data_tag:
383     return new ciVirtualCallData(data_layout);
384   case DataLayout::ret_data_tag:
385     return new ciRetData(data_layout);
386   case DataLayout::branch_data_tag:
387     return new ciBranchData(data_layout);
388   case DataLayout::multi_branch_data_tag:
389     return new ciMultiBranchData(data_layout);
390   case DataLayout::arg_info_data_tag:
391     return new ciArgInfoData(data_layout);
392   case DataLayout::call_type_data_tag:
393     return new ciCallTypeData(data_layout);
394   case DataLayout::virtual_call_type_data_tag:
395     return new ciVirtualCallTypeData(data_layout);
396   case DataLayout::parameters_type_data_tag:
397     return new ciParametersTypeData(data_layout);
398   };
399 }
400 
401 // Iteration over data.
402 ciProfileData* ciMethodData::next_data(ciProfileData* current) {
403   int current_index = dp_to_di(current->dp());
404   int next_index = current_index + current->size_in_bytes();
405   ciProfileData* next = data_at(next_index);
406   return next;
407 }
408 
409 DataLayout* ciMethodData::next_data_layout_helper(DataLayout* current, bool extra) {
410   int current_index = dp_to_di((address)current);
411   int next_index = current_index + current->size_in_bytes();
412   if (extra ? out_of_bounds_extra(next_index) : out_of_bounds(next_index)) {
413     return nullptr;
414   }
415   DataLayout* next = data_layout_at(next_index);
416   return next;
417 }
418 
419 DataLayout* ciMethodData::next_data_layout(DataLayout* current) {
420   return next_data_layout_helper(current, false);
421 }
422 
423 DataLayout* ciMethodData::next_extra_data_layout(DataLayout* current) {
424   return next_data_layout_helper(current, true);
425 }
426 
427 ciProfileData* ciMethodData::bci_to_extra_data(int bci, ciMethod* m, bool& two_free_slots) {
428   DataLayout* dp  = extra_data_base();
429   DataLayout* end = args_data_limit();
430   two_free_slots = false;
431   for (;dp < end; dp = MethodData::next_extra(dp)) {
432     switch(dp->tag()) {
433     case DataLayout::no_tag:
434       _saw_free_extra_data = true;  // observed an empty slot (common case)
435       two_free_slots = (MethodData::next_extra(dp)->tag() == DataLayout::no_tag);
436       return nullptr;
437     case DataLayout::arg_info_data_tag:
438       return nullptr; // ArgInfoData is after the trap data right before the parameter data.
439     case DataLayout::bit_data_tag:
440       if (m == nullptr && dp->bci() == bci) {
441         return new ciBitData(dp);
442       }
443       break;
444     case DataLayout::speculative_trap_data_tag: {
445       ciSpeculativeTrapData* data = new ciSpeculativeTrapData(dp);
446       // data->method() might be null if the MDO is snapshotted
447       // concurrently with a trap
448       if (m != nullptr && data->method() == m && dp->bci() == bci) {
449         return data;
450       }
451       break;
452     }
453     default:
454       fatal("bad tag = %d", dp->tag());
455     }
456   }
457   return nullptr;
458 }
459 
460 // Translate a bci to its corresponding data, or nullptr.
461 ciProfileData* ciMethodData::bci_to_data(int bci, ciMethod* m) {
462   // If m is not nullptr we look for a SpeculativeTrapData entry
463   if (m == nullptr) {
464     DataLayout* data_layout = data_layout_before(bci);
465     for ( ; is_valid(data_layout); data_layout = next_data_layout(data_layout)) {
466       if (data_layout->bci() == bci) {
467         set_hint_di(dp_to_di((address)data_layout));
468         return data_from(data_layout);
469       } else if (data_layout->bci() > bci) {
470         break;
471       }
472     }
473   }
474   bool two_free_slots = false;
475   ciProfileData* result = bci_to_extra_data(bci, m, two_free_slots);
476   if (result != nullptr) {
477     return result;
478   }
479   if (m != nullptr && !two_free_slots) {
480     // We were looking for a SpeculativeTrapData entry we didn't
481     // find. Room is not available for more SpeculativeTrapData
482     // entries, look in the non SpeculativeTrapData entries.
483     return bci_to_data(bci, nullptr);
484   }
485   return nullptr;
486 }
487 
488 ciBitData ciMethodData::exception_handler_bci_to_data(int bci) {
489   assert(ProfileExceptionHandlers, "not profiling");
490   assert(_data != nullptr, "must be initialized");
491   for (DataLayout* data = exception_handler_data_base(); data < exception_handler_data_limit(); data = next_extra_data_layout(data)) {
492     assert(data != nullptr, "out of bounds?");
493     if (data->bci() == bci) {
494       return ciBitData(data);
495     }
496   }
497   // called with invalid bci or wrong Method/MethodData
498   ShouldNotReachHere();
499   return ciBitData(nullptr);
500 }
501 
502 // Conservatively decode the trap_state of a ciProfileData.
503 int ciMethodData::has_trap_at(ciProfileData* data, int reason) {
504   typedef Deoptimization::DeoptReason DR_t;
505   int per_bc_reason
506     = Deoptimization::reason_recorded_per_bytecode_if_any((DR_t) reason);
507   if (trap_count(reason) == 0) {
508     // Impossible for this trap to have occurred, regardless of trap_state.
509     // Note:  This happens if the MDO is empty.
510     return 0;
511   } else if (per_bc_reason == Deoptimization::Reason_none) {
512     // We cannot conclude anything; a trap happened somewhere, maybe here.
513     return -1;
514   } else if (data == nullptr) {
515     // No profile here, not even an extra_data record allocated on the fly.
516     // If there are empty extra_data records, and there had been a trap,
517     // there would have been a non-null data pointer.  If there are no
518     // free extra_data records, we must return a conservative -1.
519     if (_saw_free_extra_data)
520       return 0;                 // Q.E.D.
521     else
522       return -1;                // bail with a conservative answer
523   } else {
524     return Deoptimization::trap_state_has_reason(data->trap_state(), per_bc_reason);
525   }
526 }
527 
528 int ciMethodData::trap_recompiled_at(ciProfileData* data) {
529   if (data == nullptr) {
530     return (_saw_free_extra_data? 0: -1);  // (see previous method)
531   } else {
532     return Deoptimization::trap_state_is_recompiled(data->trap_state())? 1: 0;
533   }
534 }
535 
536 void ciMethodData::clear_escape_info() {
537   VM_ENTRY_MARK;
538   MethodData* mdo = get_MethodData();
539   if (mdo != nullptr) {
540     mdo->clear_escape_info();
541     ArgInfoData *aid = arg_info();
542     int arg_count = (aid == nullptr) ? 0 : aid->number_of_args();
543     for (int i = 0; i < arg_count; i++) {
544       set_arg_modified(i, 0);
545     }
546   }
547   _eflags = _arg_local = _arg_stack = _arg_returned = 0;
548 }
549 
550 // copy our escape info to the MethodData* if it exists
551 void ciMethodData::update_escape_info() {
552   VM_ENTRY_MARK;
553   MethodData* mdo = get_MethodData();
554   if ( mdo != nullptr) {
555     mdo->set_eflags(_eflags);
556     mdo->set_arg_local(_arg_local);
557     mdo->set_arg_stack(_arg_stack);
558     mdo->set_arg_returned(_arg_returned);
559     int arg_count = mdo->method()->size_of_parameters();
560     for (int i = 0; i < arg_count; i++) {
561       mdo->set_arg_modified(i, arg_modified(i));
562     }
563   }
564 }
565 
566 void ciMethodData::set_compilation_stats(short loops, short blocks) {
567   VM_ENTRY_MARK;
568   MethodData* mdo = get_MethodData();
569   if (mdo != nullptr) {
570     mdo->set_num_loops(loops);
571     mdo->set_num_blocks(blocks);
572   }
573 }
574 
575 void ciMethodData::set_would_profile(bool p) {
576   VM_ENTRY_MARK;
577   MethodData* mdo = get_MethodData();
578   if (mdo != nullptr) {
579     mdo->set_would_profile(p);
580   }
581 }
582 
583 void ciMethodData::set_argument_type(int bci, int i, ciKlass* k) {
584   VM_ENTRY_MARK;
585   MethodData* mdo = get_MethodData();
586   if (mdo != nullptr) {
587     // Lock to read ProfileData, and ensure lock is not broken by a safepoint
588     MutexLocker ml(mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
589 
590     ProfileData* data = mdo->bci_to_data(bci);
591     if (data != nullptr) {
592       if (data->is_CallTypeData()) {
593         data->as_CallTypeData()->set_argument_type(i, k->get_Klass());
594       } else {
595         assert(data->is_VirtualCallTypeData(), "no arguments!");
596         data->as_VirtualCallTypeData()->set_argument_type(i, k->get_Klass());
597       }
598     }
599   }
600 }
601 
602 void ciMethodData::set_parameter_type(int i, ciKlass* k) {
603   VM_ENTRY_MARK;
604   MethodData* mdo = get_MethodData();
605   if (mdo != nullptr) {
606     mdo->parameters_type_data()->set_type(i, k->get_Klass());
607   }
608 }
609 
610 void ciMethodData::set_return_type(int bci, ciKlass* k) {
611   VM_ENTRY_MARK;
612   MethodData* mdo = get_MethodData();
613   if (mdo != nullptr) {
614     // Lock to read ProfileData, and ensure lock is not broken by a safepoint
615     MutexLocker ml(mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
616 
617     ProfileData* data = mdo->bci_to_data(bci);
618     if (data != nullptr) {
619       if (data->is_CallTypeData()) {
620         data->as_CallTypeData()->set_return_type(k->get_Klass());
621       } else {
622         assert(data->is_VirtualCallTypeData(), "no arguments!");
623         data->as_VirtualCallTypeData()->set_return_type(k->get_Klass());
624       }
625     }
626   }
627 }
628 
629 bool ciMethodData::has_escape_info() {
630   return eflag_set(MethodData::estimated);
631 }
632 
633 void ciMethodData::set_eflag(MethodData::EscapeFlag f) {
634   set_bits(_eflags, f);
635 }
636 
637 bool ciMethodData::eflag_set(MethodData::EscapeFlag f) const {
638   return mask_bits(_eflags, f) != 0;
639 }
640 
641 void ciMethodData::set_arg_local(int i) {
642   set_nth_bit(_arg_local, i);
643 }
644 
645 void ciMethodData::set_arg_stack(int i) {
646   set_nth_bit(_arg_stack, i);
647 }
648 
649 void ciMethodData::set_arg_returned(int i) {
650   set_nth_bit(_arg_returned, i);
651 }
652 
653 void ciMethodData::set_arg_modified(int arg, uint val) {
654   ArgInfoData *aid = arg_info();
655   if (aid == nullptr)
656     return;
657   assert(arg >= 0 && arg < aid->number_of_args(), "valid argument number");
658   aid->set_arg_modified(arg, val);
659 }
660 
661 bool ciMethodData::is_arg_local(int i) const {
662   return is_set_nth_bit(_arg_local, i);
663 }
664 
665 bool ciMethodData::is_arg_stack(int i) const {
666   return is_set_nth_bit(_arg_stack, i);
667 }
668 
669 bool ciMethodData::is_arg_returned(int i) const {
670   return is_set_nth_bit(_arg_returned, i);
671 }
672 
673 uint ciMethodData::arg_modified(int arg) const {
674   ArgInfoData *aid = arg_info();
675   if (aid == nullptr)
676     return 0;
677   assert(arg >= 0 && arg < aid->number_of_args(), "valid argument number");
678   return aid->arg_modified(arg);
679 }
680 
681 ciParametersTypeData* ciMethodData::parameters_type_data() const {
682   return parameter_data_size() != 0 ? new ciParametersTypeData(data_layout_at(_parameters_data_offset)) : nullptr;
683 }
684 
685 ByteSize ciMethodData::offset_of_slot(ciProfileData* data, ByteSize slot_offset_in_data) {
686   // Get offset within MethodData* of the data array
687   ByteSize data_offset = MethodData::data_offset();
688 
689   // Get cell offset of the ProfileData within data array
690   int cell_offset = dp_to_di(data->dp());
691 
692   // Add in counter_offset, the # of bytes into the ProfileData of counter or flag
693   int offset = in_bytes(data_offset) + cell_offset + in_bytes(slot_offset_in_data);
694 
695   return in_ByteSize(offset);
696 }
697 
698 ciArgInfoData *ciMethodData::arg_info() const {
699   // Should be last, have to skip all traps.
700   DataLayout* dp  = extra_data_base();
701   DataLayout* end = args_data_limit();
702   for (; dp < end; dp = MethodData::next_extra(dp)) {
703     if (dp->tag() == DataLayout::arg_info_data_tag)
704       return new ciArgInfoData(dp);
705   }
706   return nullptr;
707 }
708 
709 
710 // Implementation of the print method.
711 void ciMethodData::print_impl(outputStream* st) {
712   ciMetadata::print_impl(st);
713 }
714 
715 void ciMethodData::dump_replay_data_type_helper(outputStream* out, int round, int& count, ProfileData* pdata, ByteSize offset, ciKlass* k) {
716   if (k != nullptr) {
717     if (round == 0) {
718       count++;
719     } else {
720       out->print(" %d %s", (int)(dp_to_di(pdata->dp() + in_bytes(offset)) / sizeof(intptr_t)),
721                            CURRENT_ENV->replay_name(k));
722     }
723   }
724 }
725 
726 template<class T> void ciMethodData::dump_replay_data_receiver_type_helper(outputStream* out, int round, int& count, T* vdata) {
727   for (uint i = 0; i < vdata->row_limit(); i++) {
728     dump_replay_data_type_helper(out, round, count, vdata, vdata->receiver_offset(i), vdata->receiver(i));
729   }
730 }
731 
732 template<class T> void ciMethodData::dump_replay_data_call_type_helper(outputStream* out, int round, int& count, T* call_type_data) {
733   if (call_type_data->has_arguments()) {
734     for (int i = 0; i < call_type_data->number_of_arguments(); i++) {
735       dump_replay_data_type_helper(out, round, count, call_type_data, call_type_data->argument_type_offset(i), call_type_data->valid_argument_type(i));
736     }
737   }
738   if (call_type_data->has_return()) {
739     dump_replay_data_type_helper(out, round, count, call_type_data, call_type_data->return_type_offset(), call_type_data->valid_return_type());
740   }
741 }
742 
743 void ciMethodData::dump_replay_data_extra_data_helper(outputStream* out, int round, int& count) {
744   DataLayout* dp  = extra_data_base();
745   DataLayout* end = args_data_limit();
746 
747   for (;dp < end; dp = MethodData::next_extra(dp)) {
748     switch(dp->tag()) {
749     case DataLayout::no_tag:
750     case DataLayout::arg_info_data_tag:
751       return;
752     case DataLayout::bit_data_tag:
753       break;
754     case DataLayout::speculative_trap_data_tag: {
755       ciSpeculativeTrapData* data = new ciSpeculativeTrapData(dp);
756       ciMethod* m = data->method();
757       if (m != nullptr) {
758         if (round == 0) {
759           count++;
760         } else {
761           out->print(" %d ", (int)(dp_to_di(((address)dp) + in_bytes(ciSpeculativeTrapData::method_offset())) / sizeof(intptr_t)));
762           m->dump_name_as_ascii(out);
763         }
764       }
765       break;
766     }
767     default:
768       fatal("bad tag = %d", dp->tag());
769     }
770   }
771 }
772 
773 void ciMethodData::dump_replay_data(outputStream* out) {
774   ResourceMark rm;
775   MethodData* mdo = get_MethodData();
776   Method* method = mdo->method();
777   out->print("ciMethodData ");
778   ciMethod::dump_name_as_ascii(out, method);
779   out->print(" %d %d", _state, _invocation_counter);
780 
781   // dump the contents of the MDO header as raw data
782   unsigned char* orig = (unsigned char*)&_orig;
783   int length = sizeof(_orig);
784   out->print(" orig %d", length);
785   for (int i = 0; i < length; i++) {
786     out->print(" %d", orig[i]);
787   }
788 
789   // dump the MDO data as raw data
790   int elements = (data_size() + extra_data_size()) / sizeof(intptr_t);
791   out->print(" data %d", elements);
792   for (int i = 0; i < elements; i++) {
793     // We could use INTPTR_FORMAT here but that's zero justified
794     // which makes comparing it with the SA version of this output
795     // harder. data()'s element type is intptr_t.
796     out->print(" 0x%zx", data()[i]);
797   }
798 
799   // The MDO contained oop references as ciObjects, so scan for those
800   // and emit pairs of offset and klass name so that they can be
801   // reconstructed at runtime.  The first round counts the number of
802   // oop references and the second actually emits them.
803   ciParametersTypeData* parameters = parameters_type_data();
804   for (int count = 0, round = 0; round < 2; round++) {
805     if (round == 1) out->print(" oops %d", count);
806     ProfileData* pdata = first_data();
807     for ( ; is_valid(pdata); pdata = next_data(pdata)) {
808       if (pdata->is_VirtualCallData()) {
809         ciVirtualCallData* vdata = (ciVirtualCallData*)pdata;
810         dump_replay_data_receiver_type_helper<ciVirtualCallData>(out, round, count, vdata);
811         if (pdata->is_VirtualCallTypeData()) {
812           ciVirtualCallTypeData* call_type_data = (ciVirtualCallTypeData*)pdata;
813           dump_replay_data_call_type_helper<ciVirtualCallTypeData>(out, round, count, call_type_data);
814         }
815       } else if (pdata->is_ReceiverTypeData()) {
816         ciReceiverTypeData* vdata = (ciReceiverTypeData*)pdata;
817         dump_replay_data_receiver_type_helper<ciReceiverTypeData>(out, round, count, vdata);
818       } else if (pdata->is_CallTypeData()) {
819           ciCallTypeData* call_type_data = (ciCallTypeData*)pdata;
820           dump_replay_data_call_type_helper<ciCallTypeData>(out, round, count, call_type_data);
821       }
822     }
823     if (parameters != nullptr) {
824       for (int i = 0; i < parameters->number_of_parameters(); i++) {
825         dump_replay_data_type_helper(out, round, count, parameters, ParametersTypeData::type_offset(i), parameters->valid_parameter_type(i));
826       }
827     }
828   }
829   for (int count = 0, round = 0; round < 2; round++) {
830     if (round == 1) out->print(" methods %d", count);
831     dump_replay_data_extra_data_helper(out, round, count);
832   }
833   out->cr();
834 }
835 
836 #ifndef PRODUCT
837 void ciMethodData::print() {
838   print_data_on(tty);
839 }
840 
841 void ciMethodData::print_data_on(outputStream* st) {
842   ResourceMark rm;
843   ciParametersTypeData* parameters = parameters_type_data();
844   if (parameters != nullptr) {
845     parameters->print_data_on(st);
846   }
847   ciProfileData* data;
848   for (data = first_data(); is_valid(data); data = next_data(data)) {
849     st->print("%d", dp_to_di(data->dp()));
850     st->fill_to(6);
851     data->print_data_on(st);
852   }
853   st->print_cr("--- Extra data:");
854   DataLayout* dp  = extra_data_base();
855   DataLayout* end = args_data_limit();
856   for (;; dp = MethodData::next_extra(dp)) {
857     assert(dp < end, "moved past end of extra data");
858     switch (dp->tag()) {
859     case DataLayout::no_tag:
860       continue;
861     case DataLayout::bit_data_tag:
862       data = new BitData(dp);
863       break;
864     case DataLayout::arg_info_data_tag:
865       data = new ciArgInfoData(dp);
866       dp = end; // ArgInfoData is after the trap data right before the parameter data.
867       break;
868     case DataLayout::speculative_trap_data_tag:
869       data = new ciSpeculativeTrapData(dp);
870       break;
871     default:
872       fatal("unexpected tag %d", dp->tag());
873     }
874     st->print("%d", dp_to_di(data->dp()));
875     st->fill_to(6);
876     data->print_data_on(st);
877     if (dp >= end) return;
878   }
879 }
880 
881 void ciTypeEntries::print_ciklass(outputStream* st, intptr_t k) {
882   if (TypeEntries::is_type_none(k)) {
883     st->print("none");
884   } else if (TypeEntries::is_type_unknown(k)) {
885     st->print("unknown");
886   } else {
887     valid_ciklass(k)->print_name_on(st);
888   }
889   if (TypeEntries::was_null_seen(k)) {
890     st->print(" (null seen)");
891   }
892 }
893 
894 void ciTypeStackSlotEntries::print_data_on(outputStream* st) const {
895   for (int i = 0; i < number_of_entries(); i++) {
896     _pd->tab(st);
897     st->print("%d: stack (%u) ", i, stack_slot(i));
898     print_ciklass(st, type(i));
899     st->cr();
900   }
901 }
902 
903 void ciReturnTypeEntry::print_data_on(outputStream* st) const {
904   _pd->tab(st);
905   st->print("ret ");
906   print_ciklass(st, type());
907   st->cr();
908 }
909 
910 void ciCallTypeData::print_data_on(outputStream* st, const char* extra) const {
911   print_shared(st, "ciCallTypeData", extra);
912   if (has_arguments()) {
913     tab(st, true);
914     st->print_cr("argument types");
915     args()->print_data_on(st);
916   }
917   if (has_return()) {
918     tab(st, true);
919     st->print_cr("return type");
920     ret()->print_data_on(st);
921   }
922 }
923 
924 void ciReceiverTypeData::print_receiver_data_on(outputStream* st) const {
925   uint row;
926   int entries = 0;
927   for (row = 0; row < row_limit(); row++) {
928     if (receiver(row) != nullptr)  entries++;
929   }
930   st->print_cr("count(%u) entries(%u)", count(), entries);
931   for (row = 0; row < row_limit(); row++) {
932     if (receiver(row) != nullptr) {
933       tab(st);
934       receiver(row)->print_name_on(st);
935       st->print_cr("(%u)", receiver_count(row));
936     }
937   }
938 }
939 
940 void ciReceiverTypeData::print_data_on(outputStream* st, const char* extra) const {
941   print_shared(st, "ciReceiverTypeData", extra);
942   print_receiver_data_on(st);
943 }
944 
945 void ciVirtualCallData::print_data_on(outputStream* st, const char* extra) const {
946   print_shared(st, "ciVirtualCallData", extra);
947   rtd_super()->print_receiver_data_on(st);
948 }
949 
950 void ciVirtualCallTypeData::print_data_on(outputStream* st, const char* extra) const {
951   print_shared(st, "ciVirtualCallTypeData", extra);
952   rtd_super()->print_receiver_data_on(st);
953   if (has_arguments()) {
954     tab(st, true);
955     st->print("argument types");
956     args()->print_data_on(st);
957   }
958   if (has_return()) {
959     tab(st, true);
960     st->print("return type");
961     ret()->print_data_on(st);
962   }
963 }
964 
965 void ciParametersTypeData::print_data_on(outputStream* st, const char* extra) const {
966   st->print_cr("ciParametersTypeData");
967   parameters()->print_data_on(st);
968 }
969 
970 void ciSpeculativeTrapData::print_data_on(outputStream* st, const char* extra) const {
971   st->print_cr("ciSpeculativeTrapData");
972   tab(st);
973   method()->print_short_name(st);
974   st->cr();
975 }
976 #endif