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