1 /*
  2  * Copyright (c) 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 #ifndef SHARE_OOPS_TRAININGDATA_HPP
 26 #define SHARE_OOPS_TRAININGDATA_HPP
 27 
 28 #include "cds/cdsConfig.hpp"
 29 #include "classfile/compactHashtable.hpp"
 30 #include "compiler/compiler_globals.hpp"
 31 #include "compiler/compilerDefinitions.hpp"
 32 #include "memory/allocation.hpp"
 33 #include "memory/metaspaceClosure.hpp"
 34 #include "oops/instanceKlass.hpp"
 35 #include "oops/method.hpp"
 36 #include "oops/objArrayKlass.hpp"
 37 #include "runtime/handles.hpp"
 38 #include "runtime/mutexLocker.hpp"
 39 #include "utilities/count_leading_zeros.hpp"
 40 #include "utilities/resizableHashTable.hpp"
 41 
 42 class ciEnv;
 43 class ciBaseObject;
 44 class CompileTask;
 45 class CompileTrainingData;
 46 class KlassTrainingData;
 47 class MethodTrainingData;
 48 
 49 // Base class for all the training data varieties
 50 class TrainingData : public Metadata {
 51   friend KlassTrainingData;
 52   friend MethodTrainingData;
 53   friend CompileTrainingData;
 54 public:
 55   // Key is used to insert any TrainingData (TD) object into a hash tables. The key is currently a
 56   // pointer to a metaspace object the TD is associated with. For example,
 57   // for KlassTrainingData it's an InstanceKlass, for MethodTrainingData it's a Method.
 58   // The utility of the these hash tables is to be able to find a TD object for a given metaspace
 59   // metaspace object.
 60   class Key {
 61     mutable Metadata* _meta;
 62     // These guys can get to my constructors:
 63     friend TrainingData;
 64     friend KlassTrainingData;
 65     friend MethodTrainingData;
 66     friend CompileTrainingData;
 67 
 68     // The empty key
 69     Key() : _meta(nullptr) { }
 70     bool is_empty() const { return _meta == nullptr; }
 71   public:
 72     Key(Metadata* meta) : _meta(meta) { }
 73 
 74     static bool can_compute_cds_hash(const Key* const& k);
 75     static uint cds_hash(const Key* const& k);
 76     static unsigned hash(const Key* const& k) {
 77       return primitive_hash(k->meta());
 78     }
 79     static bool equals(const Key* const& k1, const Key* const& k2) {
 80       return k1->meta() == k2->meta();
 81     }
 82     static inline bool equals(TrainingData* value, const TrainingData::Key* key, int unused) {
 83       return equals(value->key(), key);
 84     }
 85     int cmp(const Key* that) const {
 86       auto m1 = this->meta();
 87       auto m2 = that->meta();
 88       if (m1 < m2) return -1;
 89       if (m1 > m2) return +1;
 90       return 0;
 91     }
 92     Metadata* meta() const { return _meta; }
 93     void metaspace_pointers_do(MetaspaceClosure *iter);
 94     void make_empty() const { _meta = nullptr; }
 95   };
 96 
 97   // TrainingDataLocker is used to guard read/write operations on non-MT-safe data structures.
 98   // It supports recursive locking and a read-only mode (in which case no locks are taken).
 99   // It is also a part of the TD collection termination protocol (see the "snapshot" field).
100   class TrainingDataLocker {
101 #if INCLUDE_CDS
102     static volatile bool _snapshot; // If true we're not allocating new training data
103 #endif
104     static int _lock_mode;
105     const bool _recursive;
106     static void lock() {
107 #if INCLUDE_CDS
108       assert(_lock_mode != 0, "Forgot to call TrainingDataLocker::initialize()");
109       if (_lock_mode > 0) {
110         TrainingData_lock->lock_without_safepoint_check();
111       }
112 #endif
113     }
114     static void unlock() {
115 #if INCLUDE_CDS
116       if (_lock_mode > 0) {
117         TrainingData_lock->unlock();
118       }
119 #endif
120     }
121     static bool safely_locked() {
122 #if INCLUDE_CDS
123       assert(_lock_mode != 0, "Forgot to call TrainingDataLocker::initialize()");
124       if (_lock_mode > 0) {
125         return is_self_locked();
126       } else {
127         return true;
128       }
129 #else
130       return true;
131 #endif
132     }
133     static bool is_self_locked() {
134       return CDS_ONLY(TrainingData_lock->owned_by_self()) NOT_CDS(false);
135     }
136 
137   public:
138     static void snapshot() {
139 #if INCLUDE_CDS
140       assert_locked();
141       _snapshot = true;
142 #endif
143     }
144     static bool can_add() {
145 #if INCLUDE_CDS
146       assert_locked();
147       return !_snapshot;
148 #else
149       return false;
150 #endif
151     }
152     static void initialize() {
153 #if INCLUDE_CDS
154       _lock_mode = need_data() ? +1 : -1;   // if -1, we go lock-free
155 #endif
156     }
157     static void assert_locked_or_snapshotted() {
158 #if INCLUDE_CDS
159       assert(safely_locked() || _snapshot, "use under TrainingDataLocker or after snapshot");
160 #endif
161     }
162     static void assert_locked() {
163       assert(safely_locked(), "use under TrainingDataLocker");
164     }
165     static void assert_can_add() {
166       assert(can_add(), "Cannot add TrainingData objects");
167     }
168     TrainingDataLocker() : _recursive(is_self_locked()) {
169       if (!_recursive) {
170         lock();
171       }
172     }
173     ~TrainingDataLocker() {
174       if (!_recursive) {
175         unlock();
176       }
177     }
178   };
179 
180   // A set of TD objects that we collect during the training run.
181   class TrainingDataSet {
182     friend TrainingData;
183     ResizeableHashTable<const Key*, TrainingData*,
184                                 AnyObj::C_HEAP, MemTag::mtCompiler,
185                                 &TrainingData::Key::hash,
186                                 &TrainingData::Key::equals>
187       _table;
188 
189   public:
190     template<typename... Arg>
191     TrainingDataSet(Arg... arg)
192       : _table(arg...) {
193     }
194     TrainingData* find(const Key* key) const {
195       TrainingDataLocker::assert_locked();
196       if (TrainingDataLocker::can_add()) {
197         auto res = _table.get(key);
198         return res == nullptr ? nullptr : *res;
199       }
200       return nullptr;
201     }
202     bool remove(const Key* key) {
203       return _table.remove(key);
204     }
205     TrainingData* install(TrainingData* td) {
206       TrainingDataLocker::assert_locked();
207       TrainingDataLocker::assert_can_add();
208       auto key = td->key();
209       if (key->is_empty()) {
210         return td;  // unkeyed TD not installed
211       }
212       bool created = false;
213       auto prior = _table.put_if_absent(key, td, &created);
214       if (prior == nullptr || *prior == td) {
215         return td;
216       }
217       assert(false, "no pre-existing elements allowed");
218       return *prior;
219     }
220     template<typename Function>
221     void iterate(const Function& fn) const { // lambda enabled API
222       iterate(const_cast<Function&>(fn));
223     }
224     template<typename Function>
225     void iterate(Function& fn) const { // lambda enabled API
226       return _table.iterate_all([&](const TrainingData::Key* k, TrainingData* td) { fn(td); });
227     }
228     int size() const { return _table.number_of_entries(); }
229 
230     void verify() const {
231       TrainingDataLocker::assert_locked();
232       iterate([&](TrainingData* td) { td->verify(); });
233     }
234   };
235 
236   // A widget to ensure that we visit TD object only once (TD objects can have pointer to
237   // other TD object that are sometimes circular).
238   class Visitor {
239     ResizeableHashTable<TrainingData*, bool> _visited;
240   public:
241     Visitor(unsigned size) : _visited(size, 0x3fffffff) { }
242     bool is_visited(TrainingData* td) {
243       return _visited.contains(td);
244     }
245     void visit(TrainingData* td) {
246       bool created;
247       _visited.put_if_absent(td, &created);
248     }
249   };
250 
251   typedef OffsetCompactHashtable<const TrainingData::Key*, TrainingData*, TrainingData::Key::equals> TrainingDataDictionary;
252 private:
253   Key _key;
254 
255   // just forward all constructor arguments to the embedded key
256   template<typename... Arg>
257   TrainingData(Arg... arg)
258     : _key(arg...) { }
259 
260   // Container for recording TD during training run
261   static TrainingDataSet _training_data_set;
262   // Containter for replaying the training data (read-only, populated from the AOT image)
263   static TrainingDataDictionary _archived_training_data_dictionary;
264   // Container used for writing the AOT image
265   static TrainingDataDictionary _archived_training_data_dictionary_for_dumping;
266   class DumpTimeTrainingDataInfo {
267     TrainingData* _training_data;
268   public:
269     DumpTimeTrainingDataInfo() : DumpTimeTrainingDataInfo(nullptr) {}
270     DumpTimeTrainingDataInfo(TrainingData* training_data) : _training_data(training_data) {}
271     void metaspace_pointers_do(MetaspaceClosure* it) {
272       it->push(&_training_data);
273     }
274     TrainingData* training_data() {
275       return _training_data;
276     }
277   };
278   typedef GrowableArrayCHeap<DumpTimeTrainingDataInfo, mtClassShared> DumptimeTrainingDataDictionary;
279   // A temporary container that is used to accumulate and filter TD during dumping
280   static DumptimeTrainingDataDictionary* _dumptime_training_data_dictionary;
281 
282   static TrainingDataSet* training_data_set() { return &_training_data_set; }
283   static TrainingDataDictionary* archived_training_data_dictionary() { return &_archived_training_data_dictionary; }
284 
285  public:
286   // Returns the key under which this TD is installed, or else
287   // Key::EMPTY if it is not installed.
288   const Key* key() const { return &_key; }
289 
290   static bool have_data() { return AOTReplayTraining;  } // Going to read
291   static bool need_data() { return AOTRecordTraining;  } // Going to write
292   static bool assembling_data() { return have_data() && CDSConfig::is_dumping_final_static_archive() && CDSConfig::is_dumping_aot_linked_classes(); }
293 
294   static bool is_klass_loaded(Klass* k) {
295     if (have_data()) {
296       // If we're running in AOT mode some classes may not be loaded yet
297       if (k->is_objArray_klass()) {
298         k = ObjArrayKlass::cast(k)->bottom_klass();
299       }
300       if (k->is_instance_klass()) {
301         return InstanceKlass::cast(k)->is_loaded();
302       }
303     }
304     return true;
305   }
306 
307   template<typename Function>
308   static void iterate(const Function& fn) { iterate(const_cast<Function&>(fn)); }
309 
310   template<typename Function>
311   static void iterate(Function& fn) { // lambda enabled API
312     TrainingDataLocker l;
313     if (have_data()) {
314       archived_training_data_dictionary()->iterate(fn);
315     }
316     if (need_data()) {
317       training_data_set()->iterate(fn);
318     }
319   }
320 
321   virtual MethodTrainingData*   as_MethodTrainingData()  const { return nullptr; }
322   virtual KlassTrainingData*    as_KlassTrainingData()   const { return nullptr; }
323   virtual CompileTrainingData*  as_CompileTrainingData() const { return nullptr; }
324   bool is_MethodTrainingData()  const { return as_MethodTrainingData()  != nullptr; }
325   bool is_KlassTrainingData()   const { return as_KlassTrainingData()   != nullptr; }
326   bool is_CompileTrainingData() const { return as_CompileTrainingData() != nullptr; }
327 
328   virtual void prepare(Visitor& visitor) = 0;
329   virtual void cleanup(Visitor& visitor) = 0;
330 
331   static void initialize() NOT_CDS_RETURN;
332 
333   static void verify() NOT_CDS_RETURN;
334 
335   // Widget for recording dependencies, as an N-to-M graph relation,
336   // possibly cyclic.
337   template<typename E>
338   class DepList : public StackObj {
339     GrowableArrayCHeap<E, mtCompiler>* _deps_dyn;
340     Array<E>*                          _deps;
341   public:
342     DepList() {
343       _deps_dyn = nullptr;
344       _deps = nullptr;
345     }
346 
347     int length() const {
348       TrainingDataLocker::assert_locked_or_snapshotted();
349       return (_deps_dyn != nullptr ? _deps_dyn->length()
350               : _deps   != nullptr ? _deps->length()
351               : 0);
352     }
353     E* adr_at(int i) const {
354       TrainingDataLocker::assert_locked_or_snapshotted();
355       return (_deps_dyn != nullptr ? _deps_dyn->adr_at(i)
356               : _deps   != nullptr ? _deps->adr_at(i)
357               : nullptr);
358     }
359     E at(int i) const {
360       TrainingDataLocker::assert_locked_or_snapshotted();
361       assert(i >= 0 && i < length(), "oob");
362       return *adr_at(i);
363     }
364     bool append_if_missing(E dep) {
365       TrainingDataLocker::assert_can_add();
366       if (_deps_dyn == nullptr) {
367         _deps_dyn = new GrowableArrayCHeap<E, mtCompiler>(10);
368         _deps_dyn->append(dep);
369         return true;
370       } else {
371         return _deps_dyn->append_if_missing(dep);
372       }
373     }
374     bool remove_if_existing(E dep) {
375       TrainingDataLocker::assert_can_add();
376       if (_deps_dyn != nullptr) {
377         return _deps_dyn->remove_if_existing(dep);
378       }
379       return false;
380     }
381     void clear() {
382       TrainingDataLocker::assert_can_add();
383       if (_deps_dyn != nullptr)  {
384         _deps_dyn->clear();
385       }
386     }
387     void append(E dep) {
388       TrainingDataLocker::assert_can_add();
389       if (_deps_dyn == nullptr) {
390         _deps_dyn = new GrowableArrayCHeap<E, mtCompiler>(10);
391       }
392       _deps_dyn->append(dep);
393     }
394     bool contains(E dep) {
395       TrainingDataLocker::assert_locked();
396       for (int i = 0; i < length(); i++) {
397         if (dep == at(i)) {
398           return true; // found
399         }
400       }
401       return false; // not found
402     }
403 
404 #if INCLUDE_CDS
405     void remove_unshareable_info() {
406       _deps_dyn = nullptr;
407     }
408 #endif
409     void prepare();
410     void metaspace_pointers_do(MetaspaceClosure *iter);
411   };
412 
413   virtual void metaspace_pointers_do(MetaspaceClosure *iter);
414 
415   static void init_dumptime_table(TRAPS);
416 
417 #if INCLUDE_CDS
418   virtual void remove_unshareable_info() {}
419   static void iterate_roots(MetaspaceClosure* it);
420   static void dump_training_data();
421   static void cleanup_training_data();
422   static void serialize(SerializeClosure* soc);
423   static void print_archived_training_data_on(outputStream* st);
424   static TrainingData* lookup_archived_training_data(const Key* k);
425 #endif
426 
427   template<typename TrainingDataType, typename... ArgTypes>
428   static TrainingDataType* allocate(ArgTypes... args) {
429     assert(need_data() || have_data(), "");
430     if (TrainingDataLocker::can_add()) {
431       return new (mtClassShared) TrainingDataType(args...);
432     }
433     return nullptr;
434   }
435 };
436 
437 // Training data that is associated with an InstanceKlass
438 class KlassTrainingData : public TrainingData {
439   friend TrainingData;
440   friend CompileTrainingData;
441 
442   // Used by CDS. These classes need to access the private default constructor.
443   template <class T> friend class CppVtableTesterA;
444   template <class T> friend class CppVtableTesterB;
445   template <class T> friend class CppVtableCloner;
446 
447   // cross-link to live klass, or null if not loaded or encountered yet
448   InstanceKlass* _holder;
449 
450   DepList<CompileTrainingData*> _comp_deps; // compiles that depend on me
451 
452   KlassTrainingData();
453   KlassTrainingData(InstanceKlass* klass);
454 
455   int comp_dep_count() const {
456     TrainingDataLocker::assert_locked();
457     return _comp_deps.length();
458   }
459   CompileTrainingData* comp_dep(int i) const {
460     TrainingDataLocker::assert_locked();
461     return _comp_deps.at(i);
462   }
463   void add_comp_dep(CompileTrainingData* ctd) {
464     TrainingDataLocker::assert_locked();
465      _comp_deps.append_if_missing(ctd);
466   }
467   void remove_comp_dep(CompileTrainingData* ctd) {
468     TrainingDataLocker::assert_locked();
469      _comp_deps.remove_if_existing(ctd);
470   }
471  public:
472   Symbol* name() const {
473     precond(has_holder());
474     return holder()->name();
475   }
476   bool has_holder()       const { return _holder != nullptr; }
477   InstanceKlass* holder() const { return _holder; }
478 
479   static KlassTrainingData* make(InstanceKlass* holder,
480                                  bool null_if_not_found = false) NOT_CDS_RETURN_(nullptr);
481   static KlassTrainingData* find(InstanceKlass* holder) {
482     return make(holder, true);
483   }
484   virtual KlassTrainingData* as_KlassTrainingData() const { return const_cast<KlassTrainingData*>(this); };
485 
486   void notice_fully_initialized() NOT_CDS_RETURN;
487 
488   void print_on(outputStream* st, bool name_only) const;
489   virtual void print_on(outputStream* st) const { print_on(st, false); }
490   virtual void print_value_on(outputStream* st) const { print_on(st, true); }
491 
492   virtual void prepare(Visitor& visitor);
493   virtual void cleanup(Visitor& visitor) NOT_CDS_RETURN;
494 
495   MetaspaceObj::Type type() const {
496     return KlassTrainingDataType;
497   }
498 
499 #if INCLUDE_CDS
500   virtual void remove_unshareable_info();
501 #endif
502 
503   void metaspace_pointers_do(MetaspaceClosure *iter);
504 
505   int size() const {
506     return (int)align_metadata_size(align_up(sizeof(KlassTrainingData), BytesPerWord)/BytesPerWord);
507   }
508 
509   const char* internal_name() const {
510     return "{ klass training data }";
511   };
512 
513   void verify();
514 
515   static KlassTrainingData* allocate(InstanceKlass* holder) {
516     return TrainingData::allocate<KlassTrainingData>(holder);
517   }
518 
519   template<typename Function>
520   void iterate_comp_deps(Function fn) const { // lambda enabled API
521     TrainingDataLocker l;
522     for (int i = 0; i < comp_dep_count(); i++) {
523       fn(comp_dep(i));
524     }
525   }
526 };
527 
528 // Information about particular JIT tasks.
529 class CompileTrainingData : public TrainingData {
530   friend TrainingData;
531   friend KlassTrainingData;
532 
533   // Used by CDS. These classes need to access the private default constructor.
534   template <class T> friend class CppVtableTesterA;
535   template <class T> friend class CppVtableTesterB;
536   template <class T> friend class CppVtableCloner;
537 
538   MethodTrainingData* _method;
539   const short _level;
540   const int _compile_id;
541 
542   // classes that should be initialized before this JIT task runs
543   DepList<KlassTrainingData*> _init_deps;
544   // Number of uninitialized classes left, when it's 0, all deps are satisfied
545   volatile int _init_deps_left;
546 
547 public:
548   // ciRecords is a generic meachanism to memoize CI responses to arbitary queries. For each function we're interested in we record
549   // (return_value, argument_values) tuples in a list. Arguments are allowed to have Metaspace pointers in them.
550   class ciRecords {
551     template <typename... Ts> class Arguments {
552     public:
553       bool operator==(const Arguments<>&) const { return true; }
554       void metaspace_pointers_do(MetaspaceClosure *iter) { }
555     };
556     template <typename T, typename... Ts> class Arguments<T, Ts...> {
557     private:
558       T _first;
559       Arguments<Ts...> _remaining;
560 
561     public:
562       constexpr Arguments(const T& first, const Ts&... remaining) noexcept
563         : _first(first), _remaining(remaining...) {}
564       constexpr Arguments() noexcept : _first(), _remaining() {}
565       bool operator==(const Arguments<T, Ts...>& that) const {
566         return _first == that._first && _remaining == that._remaining;
567       }
568       template<typename U = T, ENABLE_IF(std::is_pointer<U>::value && std::is_base_of<MetaspaceObj, typename std::remove_pointer<U>::type>::value)>
569       void metaspace_pointers_do(MetaspaceClosure *iter) {
570         iter->push(&_first);
571         _remaining.metaspace_pointers_do(iter);
572       }
573       template<typename U = T, ENABLE_IF(!(std::is_pointer<U>::value && std::is_base_of<MetaspaceObj, typename std::remove_pointer<U>::type>::value))>
574       void metaspace_pointers_do(MetaspaceClosure *iter) {
575         _remaining.metaspace_pointers_do(iter);
576       }
577     };
578 
579     template <typename ReturnType, typename... Args> class ciMemoizedFunction : public StackObj {
580     public:
581       class OptionalReturnType {
582         bool _valid;
583         ReturnType _result;
584       public:
585         OptionalReturnType(bool valid, const ReturnType& result) : _valid(valid), _result(result) {}
586         bool is_valid() const { return _valid; }
587         ReturnType result() const { return _result; }
588       };
589     private:
590       typedef Arguments<Args...> ArgumentsType;
591       class Record : public MetaspaceObj {
592         ReturnType    _result;
593         ArgumentsType _arguments;
594       public:
595         Record(const ReturnType& result, const ArgumentsType& arguments) : _result(result), _arguments(arguments) {}
596         Record() { }
597         ReturnType result() const { return _result; }
598         ArgumentsType arguments() const { return _arguments; }
599         bool operator==(const Record& that) { return _arguments == that._arguments; }
600         void metaspace_pointers_do(MetaspaceClosure *iter) { _arguments.metaspace_pointers_do(iter); }
601       };
602       DepList<Record> _data;
603     public:
604       OptionalReturnType find(const Args&... args) {
605         TrainingDataLocker l;
606         ArgumentsType a(args...);
607         for (int i = 0; i < _data.length(); i++) {
608           if (_data.at(i).arguments() == a) {
609             return OptionalReturnType(true, _data.at(i).result());
610           }
611         }
612         return OptionalReturnType(false, ReturnType());
613       }
614       void append_if_missing(const ReturnType& result, const Args&... args) {
615         TrainingDataLocker l;
616         if (l.can_add()) {
617           _data.append_if_missing(Record(result, ArgumentsType(args...)));
618         }
619       }
620 #if INCLUDE_CDS
621       void remove_unshareable_info() { _data.remove_unshareable_info(); }
622 #endif
623       void prepare() {
624         _data.prepare();
625       }
626       void metaspace_pointers_do(MetaspaceClosure *iter) {
627         _data.metaspace_pointers_do(iter);
628       }
629     };
630 
631 
632 public:
633     // Record CI answers for the InlineSmallCode heuristic. It is importance since the heuristic is non-commutative and we may want to
634     // compile methods in a different order than in the training run.
635     typedef ciMemoizedFunction<int, MethodTrainingData*> ciMethod__inline_instructions_size_type;
636     ciMethod__inline_instructions_size_type ciMethod__inline_instructions_size;
637 #if INCLUDE_CDS
638     void remove_unshareable_info() {
639       ciMethod__inline_instructions_size.remove_unshareable_info();
640     }
641 #endif
642     void prepare() {
643       ciMethod__inline_instructions_size.prepare();
644     }
645     void metaspace_pointers_do(MetaspaceClosure *iter) {
646       ciMethod__inline_instructions_size.metaspace_pointers_do(iter);
647     }
648   };
649 
650 private:
651   ciRecords _ci_records;
652 
653   CompileTrainingData();
654   CompileTrainingData(MethodTrainingData* mtd,
655                       int level,
656                       int compile_id)
657       : TrainingData(),  // empty key
658         _method(mtd), _level(level), _compile_id(compile_id), _init_deps_left(0) { }
659 public:
660   ciRecords& ci_records() { return _ci_records; }
661   static CompileTrainingData* make(CompileTask* task) NOT_CDS_RETURN_(nullptr);
662 
663   virtual CompileTrainingData* as_CompileTrainingData() const { return const_cast<CompileTrainingData*>(this); };
664 
665   MethodTrainingData* method() const { return _method; }
666 
667   int level() const { return _level; }
668 
669   int compile_id() const { return _compile_id; }
670 
671   int init_dep_count() const {
672     TrainingDataLocker::assert_locked();
673     return _init_deps.length();
674   }
675   KlassTrainingData* init_dep(int i) const {
676     TrainingDataLocker::assert_locked();
677     return _init_deps.at(i);
678   }
679   void add_init_dep(KlassTrainingData* ktd) {
680     TrainingDataLocker::assert_locked();
681     ktd->add_comp_dep(this);
682     _init_deps.append_if_missing(ktd);
683   }
684   void clear_init_deps() {
685     TrainingDataLocker::assert_locked();
686     for (int i = 0; i < _init_deps.length(); i++) {
687       _init_deps.at(i)->remove_comp_dep(this);
688     }
689     _init_deps.clear();
690   }
691   void dec_init_deps_left_release(KlassTrainingData* ktd);
692   int init_deps_left_acquire() const {
693     return AtomicAccess::load_acquire(&_init_deps_left);
694   }
695   uint compute_init_deps_left(bool count_initialized = false);
696 
697   void notice_inlined_method(CompileTask* task, const methodHandle& method) NOT_CDS_RETURN;
698 
699   // The JIT looks at classes and objects too and can depend on their state.
700   // These simple calls just report the *possibility* of an observation.
701   void notice_jit_observation(ciEnv* env, ciBaseObject* what) NOT_CDS_RETURN;
702 
703   virtual void prepare(Visitor& visitor);
704   virtual void cleanup(Visitor& visitor) NOT_CDS_RETURN;
705 
706   void print_on(outputStream* st, bool name_only) const;
707   virtual void print_on(outputStream* st) const { print_on(st, false); }
708   virtual void print_value_on(outputStream* st) const { print_on(st, true); }
709 
710 #if INCLUDE_CDS
711   virtual void remove_unshareable_info();
712 #endif
713 
714   virtual void metaspace_pointers_do(MetaspaceClosure* iter);
715   virtual MetaspaceObj::Type type() const { return CompileTrainingDataType; }
716 
717   virtual const char* internal_name() const {
718     return "{ compile training data }";
719   };
720 
721   virtual int size() const {
722     return (int)align_metadata_size(align_up(sizeof(CompileTrainingData), BytesPerWord)/BytesPerWord);
723   }
724 
725   void verify(bool verify_dep_counter);
726 
727   static CompileTrainingData* allocate(MethodTrainingData* mtd, int level, int compile_id) {
728     return TrainingData::allocate<CompileTrainingData>(mtd, level, compile_id);
729   }
730 };
731 
732 // Record information about a method at the time compilation is requested.
733 class MethodTrainingData : public TrainingData {
734   friend TrainingData;
735   friend CompileTrainingData;
736 
737   // Used by CDS. These classes need to access the private default constructor.
738   template <class T> friend class CppVtableTesterA;
739   template <class T> friend class CppVtableTesterB;
740   template <class T> friend class CppVtableCloner;
741 
742   KlassTrainingData* _klass;
743   Method* _holder;
744   CompileTrainingData* _last_toplevel_compiles[CompLevel_count - 1];
745   int _highest_top_level;
746   int _level_mask;  // bit-set of all possible levels
747   bool _was_toplevel;
748   // metadata snapshots of final state:
749   MethodCounters* _final_counters;
750   MethodData*     _final_profile;
751 
752   int _invocation_count;
753   int _backedge_count;
754 
755   MethodTrainingData();
756   MethodTrainingData(Method* method, KlassTrainingData* ktd) : TrainingData(method) {
757     _klass = ktd;
758     _holder = method;
759     for (int i = 0; i < CompLevel_count - 1; i++) {
760       _last_toplevel_compiles[i] = nullptr;
761     }
762     _highest_top_level = CompLevel_none;
763     _level_mask = 0;
764     _was_toplevel = false;
765     _invocation_count = 0;
766     _backedge_count = 0;
767   }
768 
769   static int level_mask(int level) {
770     return ((level & 0xF) != level ? 0 : 1 << level);
771   }
772   static CompLevel highest_level(int mask) {
773     if (mask == 0)  return (CompLevel) 0;
774     int diff = (count_leading_zeros(level_mask(0)) - count_leading_zeros(mask));
775     return (CompLevel) diff;
776   }
777 
778  public:
779   KlassTrainingData* klass()  const { return _klass; }
780   bool has_holder()           const { return _holder != nullptr; }
781   Method* holder()            const { return _holder; }
782   bool only_inlined()         const { return !_was_toplevel; }
783   bool saw_level(CompLevel l) const { return (_level_mask & level_mask(l)) != 0; }
784   int highest_level()         const { return highest_level(_level_mask); }
785   int highest_top_level()     const { return _highest_top_level; }
786   MethodData* final_profile() const { return _final_profile; }
787   int invocation_count() const { return _invocation_count; }
788   int backedge_count() const { return _backedge_count; }
789 
790   Symbol* name() const {
791     precond(has_holder());
792     return holder()->name();
793   }
794   Symbol* signature() const {
795     precond(has_holder());
796     return holder()->signature();
797   }
798 
799   CompileTrainingData* last_toplevel_compile(int level) const {
800     if (level > CompLevel_none) {
801       return _last_toplevel_compiles[level - 1];
802     }
803     return nullptr;
804   }
805 
806   void notice_compilation(int level, bool inlined = false) {
807     if (!inlined) {
808       _was_toplevel = true;
809     }
810     _level_mask |= level_mask(level);
811   }
812 
813   void notice_toplevel_compilation(int level) {
814     _highest_top_level = MAX2(_highest_top_level, level);
815   }
816 
817   static MethodTrainingData* make(const methodHandle& method,
818                                   bool null_if_not_found = false,
819                                   bool use_cache = true) NOT_CDS_RETURN_(nullptr);
820   static MethodTrainingData* find_fast(const methodHandle& method) { return make(method, true, true); }
821   static MethodTrainingData* find(const methodHandle& method) { return make(method, true, false); }
822 
823   virtual MethodTrainingData* as_MethodTrainingData() const {
824     return const_cast<MethodTrainingData*>(this);
825   };
826 
827   void print_on(outputStream* st, bool name_only) const;
828   virtual void print_on(outputStream* st) const { print_on(st, false); }
829   virtual void print_value_on(outputStream* st) const { print_on(st, true); }
830 
831   virtual void prepare(Visitor& visitor);
832   virtual void cleanup(Visitor& visitor) NOT_CDS_RETURN;
833 
834   template<typename Function>
835   void iterate_compiles(Function fn) const { // lambda enabled API
836     for (int i = 0; i < CompLevel_count - 1; i++) {
837       CompileTrainingData* ctd = _last_toplevel_compiles[i];
838       if (ctd != nullptr) {
839         fn(ctd);
840       }
841     }
842   }
843 
844   virtual void metaspace_pointers_do(MetaspaceClosure* iter);
845   virtual MetaspaceObj::Type type() const { return MethodTrainingDataType; }
846 
847 #if INCLUDE_CDS
848   virtual void remove_unshareable_info();
849 #endif
850 
851   virtual int size() const {
852     return (int)align_metadata_size(align_up(sizeof(MethodTrainingData), BytesPerWord)/BytesPerWord);
853   }
854 
855   virtual const char* internal_name() const {
856     return "{ method training data }";
857   };
858 
859   void verify(bool verify_dep_counter);
860 
861   static MethodTrainingData* allocate(Method* m, KlassTrainingData* ktd) {
862     return TrainingData::allocate<MethodTrainingData>(m, ktd);
863   }
864 };
865 #endif // SHARE_OOPS_TRAININGDATA_HPP