1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef ART_LIBPROFILE_PROFILE_PROFILE_COMPILATION_INFO_H_
18 #define ART_LIBPROFILE_PROFILE_PROFILE_COMPILATION_INFO_H_
19
20 #include <array>
21 #include <list>
22 #include <set>
23 #include <string_view>
24 #include <vector>
25
26 #include "base/arena_containers.h"
27 #include "base/arena_object.h"
28 #include "base/array_ref.h"
29 #include "base/atomic.h"
30 #include "base/bit_memory_region.h"
31 #include "base/hash_map.h"
32 #include "base/hash_set.h"
33 #include "base/malloc_arena_pool.h"
34 #include "base/mem_map.h"
35 #include "base/safe_map.h"
36 #include "dex/dex_file.h"
37 #include "dex/dex_file_types.h"
38 #include "dex/method_reference.h"
39 #include "dex/type_reference.h"
40
41 namespace art {
42
43 /**
44 * Convenient class to pass around profile information (including inline caches)
45 * without the need to hold GC-able objects.
46 */
47 struct ProfileMethodInfo {
48 struct ProfileInlineCache {
49 ProfileInlineCache(uint32_t pc,
50 bool missing_types,
51 const std::vector<TypeReference>& profile_classes,
52 // Only used by profman for creating profiles from text
53 bool megamorphic = false)
dex_pcProfileMethodInfo::ProfileInlineCache54 : dex_pc(pc),
55 is_missing_types(missing_types),
56 classes(profile_classes),
57 is_megamorphic(megamorphic) {}
58
59 const uint32_t dex_pc;
60 const bool is_missing_types;
61 // TODO: Replace `TypeReference` with `dex::TypeIndex` and allow artificial
62 // type indexes for types without a `dex::TypeId` in any dex file processed
63 // by the profman. See `ProfileCompilationInfo::FindOrCreateTypeIndex()`.
64 const std::vector<TypeReference> classes;
65 const bool is_megamorphic;
66 };
67
ProfileMethodInfoProfileMethodInfo68 explicit ProfileMethodInfo(MethodReference reference) : ref(reference) {}
69
ProfileMethodInfoProfileMethodInfo70 ProfileMethodInfo(MethodReference reference, const std::vector<ProfileInlineCache>& caches)
71 : ref(reference),
72 inline_caches(caches) {}
73
74 MethodReference ref;
75 std::vector<ProfileInlineCache> inline_caches;
76 };
77
78 class FlattenProfileData;
79
80 /**
81 * Profile information in a format suitable to be queried by the compiler and
82 * performing profile guided compilation.
83 * It is a serialize-friendly format based on information collected by the
84 * interpreter (ProfileInfo).
85 * Currently it stores only the hot compiled methods.
86 */
87 class ProfileCompilationInfo {
88 public:
89 static const uint8_t kProfileMagic[];
90 static const uint8_t kProfileVersion[];
91 static const uint8_t kProfileVersionForBootImage[];
92 static const char kDexMetadataProfileEntry[];
93
94 static constexpr size_t kProfileVersionSize = 4;
95 static constexpr uint8_t kIndividualInlineCacheSize = 5;
96
97 // Data structures for encoding the offline representation of inline caches.
98 // This is exposed as public in order to make it available to dex2oat compilations
99 // (see compiler/optimizing/inliner.cc).
100
101 // The type used to manipulate the profile index of dex files.
102 // It sets an upper limit to how many dex files a given profile can record.
103 using ProfileIndexType = uint16_t;
104
105 // Encodes a class reference in the profile.
106 // The owning dex file is encoded as the index (dex_profile_index) it has in the
107 // profile rather than as a full reference (location, checksum).
108 // This avoids excessive string copying when managing the profile data.
109 // The dex_profile_index is an index in the `DexFileData::profile_index` (internal use)
110 // and a matching dex file can found with `FindDexFileForProfileIndex()`.
111 // Note that the dex_profile_index is not necessary the multidex index.
112 // We cannot rely on the actual multidex index because a single profile may store
113 // data from multiple splits. This means that a profile may contain a classes2.dex from split-A
114 // and one from split-B.
115 struct ClassReference : public ValueObject {
ClassReferenceClassReference116 ClassReference(ProfileIndexType dex_profile_idx, const dex::TypeIndex type_idx) :
117 dex_profile_index(dex_profile_idx), type_index(type_idx) {}
118
119 bool operator==(const ClassReference& other) const {
120 return dex_profile_index == other.dex_profile_index && type_index == other.type_index;
121 }
122 bool operator<(const ClassReference& other) const {
123 return dex_profile_index == other.dex_profile_index
124 ? type_index < other.type_index
125 : dex_profile_index < other.dex_profile_index;
126 }
127
128 ProfileIndexType dex_profile_index; // the index of the owning dex in the profile info
129 dex::TypeIndex type_index; // the type index of the class
130 };
131
132 // Encodes the actual inline cache for a given dex pc (whether or not the receiver is
133 // megamorphic and its possible types).
134 // If the receiver is megamorphic or is missing types the set of classes will be empty.
135 struct DexPcData : public ArenaObject<kArenaAllocProfile> {
DexPcDataDexPcData136 explicit DexPcData(ArenaAllocator* allocator)
137 : DexPcData(allocator->Adapter(kArenaAllocProfile)) {}
DexPcDataDexPcData138 explicit DexPcData(const ArenaAllocatorAdapter<void>& allocator)
139 : is_missing_types(false),
140 is_megamorphic(false),
141 classes(std::less<dex::TypeIndex>(), allocator) {}
142 void AddClass(const dex::TypeIndex& type_idx);
SetIsMegamorphicDexPcData143 void SetIsMegamorphic() {
144 if (is_missing_types) return;
145 is_megamorphic = true;
146 classes.clear();
147 }
SetIsMissingTypesDexPcData148 void SetIsMissingTypes() {
149 is_megamorphic = false;
150 is_missing_types = true;
151 classes.clear();
152 }
153 bool operator==(const DexPcData& other) const {
154 return is_megamorphic == other.is_megamorphic &&
155 is_missing_types == other.is_missing_types &&
156 classes == other.classes;
157 }
158
159 // Not all runtime types can be encoded in the profile. For example if the receiver
160 // type is in a dex file which is not tracked for profiling its type cannot be
161 // encoded. When types are missing this field will be set to true.
162 bool is_missing_types;
163 bool is_megamorphic;
164 ArenaSet<dex::TypeIndex> classes;
165 };
166
167 // The inline cache map: DexPc -> DexPcData.
168 using InlineCacheMap = ArenaSafeMap<uint16_t, DexPcData>;
169
170 // Maps a method dex index to its inline cache.
171 using MethodMap = ArenaSafeMap<uint16_t, InlineCacheMap>;
172
173 // Profile method hotness information for a single method. Also includes a pointer to the inline
174 // cache map.
175 class MethodHotness {
176 public:
177 enum Flag {
178 // Marker flag used to simplify iterations.
179 kFlagFirst = 1 << 0,
180 // The method is profile-hot (this is implementation specific, e.g. equivalent to JIT-warm)
181 kFlagHot = 1 << 0,
182 // Executed during the app startup as determined by the runtime.
183 kFlagStartup = 1 << 1,
184 // Executed after app startup as determined by the runtime.
185 kFlagPostStartup = 1 << 2,
186 // Marker flag used to simplify iterations.
187 kFlagLastRegular = 1 << 2,
188 // Executed by a 32bit process.
189 kFlag32bit = 1 << 3,
190 // Executed by a 64bit process.
191 kFlag64bit = 1 << 4,
192 // Executed on sensitive thread (e.g. UI).
193 kFlagSensitiveThread = 1 << 5,
194 // Executed during the app startup as determined by the framework (equivalent to am start).
195 kFlagAmStartup = 1 << 6,
196 // Executed after the app startup as determined by the framework (equivalent to am start).
197 kFlagAmPostStartup = 1 << 7,
198 // Executed during system boot.
199 kFlagBoot = 1 << 8,
200 // Executed after the system has booted.
201 kFlagPostBoot = 1 << 9,
202
203 // The startup bins captured the relative order of when a method become hot. There are 6
204 // total bins supported and each hot method will have at least one bit set. If the profile was
205 // merged multiple times more than one bit may be set as a given method may become hot at
206 // various times during subsequent executions.
207 // The granularity of the bins is unspecified (i.e. the runtime is free to change the
208 // values it uses - this may be 100ms, 200ms etc...).
209 kFlagStartupBin = 1 << 10,
210 kFlagStartupMaxBin = 1 << 15,
211 // Marker flag used to simplify iterations.
212 kFlagLastBoot = 1 << 15,
213 };
214
IsHot()215 bool IsHot() const {
216 return (flags_ & kFlagHot) != 0;
217 }
218
IsStartup()219 bool IsStartup() const {
220 return (flags_ & kFlagStartup) != 0;
221 }
222
IsPostStartup()223 bool IsPostStartup() const {
224 return (flags_ & kFlagPostStartup) != 0;
225 }
226
AddFlag(Flag flag)227 void AddFlag(Flag flag) {
228 flags_ |= flag;
229 }
230
GetFlags()231 uint32_t GetFlags() const {
232 return flags_;
233 }
234
HasFlagSet(MethodHotness::Flag flag)235 bool HasFlagSet(MethodHotness::Flag flag) {
236 return (flags_ & flag ) != 0;
237 }
238
IsInProfile()239 bool IsInProfile() const {
240 return flags_ != 0;
241 }
242
GetInlineCacheMap()243 const InlineCacheMap* GetInlineCacheMap() const {
244 return inline_cache_map_;
245 }
246
247 private:
248 const InlineCacheMap* inline_cache_map_ = nullptr;
249 uint32_t flags_ = 0;
250
SetInlineCacheMap(const InlineCacheMap * info)251 void SetInlineCacheMap(const InlineCacheMap* info) {
252 inline_cache_map_ = info;
253 }
254
255 friend class ProfileCompilationInfo;
256 };
257
258 // Encapsulates metadata that can be associated with the methods and classes added to the profile.
259 // The additional metadata is serialized in the profile and becomes part of the profile key
260 // representation. It can be used to differentiate the samples that are added to the profile
261 // based on the supported criteria (e.g. keep track of which app generated what sample when
262 // constructing a boot profile.).
263 class ProfileSampleAnnotation {
264 public:
ProfileSampleAnnotation(const std::string & package_name)265 explicit ProfileSampleAnnotation(const std::string& package_name) :
266 origin_package_name_(package_name) {}
267
GetOriginPackageName()268 const std::string& GetOriginPackageName() const { return origin_package_name_; }
269
270 bool operator==(const ProfileSampleAnnotation& other) const {
271 return origin_package_name_ == other.origin_package_name_;
272 }
273
274 bool operator<(const ProfileSampleAnnotation& other) const {
275 return origin_package_name_ < other.origin_package_name_;
276 }
277
278 // A convenient empty annotation object that can be used to denote that no annotation should
279 // be associated with the profile samples.
280 static const ProfileSampleAnnotation kNone;
281
282 private:
283 // The name of the package that generated the samples.
284 const std::string origin_package_name_;
285 };
286
287 // Helper class for printing referenced dex file information to a stream.
288 struct DexReferenceDumper;
289
290 // Public methods to create, extend or query the profile.
291 ProfileCompilationInfo();
292 explicit ProfileCompilationInfo(bool for_boot_image);
293 explicit ProfileCompilationInfo(ArenaPool* arena_pool);
294 ProfileCompilationInfo(ArenaPool* arena_pool, bool for_boot_image);
295
296 ~ProfileCompilationInfo();
297
298 // Returns the maximum value for the profile index.
MaxProfileIndex()299 static constexpr ProfileIndexType MaxProfileIndex() {
300 return std::numeric_limits<ProfileIndexType>::max();
301 }
302
303 // Find a tracked dex file. Returns `MaxProfileIndex()` on failure, whether due to no records
304 // for the dex location or profile key, or checksum/num_type_ids/num_method_ids mismatch.
305 ProfileIndexType FindDexFile(
306 const DexFile& dex_file,
307 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) const {
308 const DexFileData* data = FindDexDataUsingAnnotations(&dex_file, annotation);
309 return (data != nullptr) ? data->profile_index : MaxProfileIndex();
310 }
311
312 // Find or add a tracked dex file. Returns `MaxProfileIndex()` on failure, whether due to
313 // checksum/num_type_ids/num_method_ids mismatch or reaching the maximum number of dex files.
314 ProfileIndexType FindOrAddDexFile(
315 const DexFile& dex_file,
316 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) {
317 DexFileData* data = GetOrAddDexFileData(&dex_file, annotation);
318 return (data != nullptr) ? data->profile_index : MaxProfileIndex();
319 }
320
321 // Add the given methods to the current profile object.
322 //
323 // Note: if an annotation is provided, the methods/classes will be associated with the group
324 // (dex_file, sample_annotation). Each group keeps its unique set of methods/classes.
325 bool AddMethods(const std::vector<ProfileMethodInfo>& methods,
326 MethodHotness::Flag flags,
327 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone);
328
329 // Find a type index in the `dex_file` if there is a `TypeId` for it. Otherwise,
330 // find or insert the descriptor in "extra descriptors" and return an artificial
331 // type index beyond `dex_file.NumTypeIds()`. This fails if the artificial index
332 // would be kDexNoIndex16 (0xffffu) or higher, returning an invalid type index.
333 // The returned type index can be used, if valid, for `AddClass()` or (TODO) as
334 // a type index for inline caches.
335 dex::TypeIndex FindOrCreateTypeIndex(const DexFile& dex_file, TypeReference class_ref);
336 dex::TypeIndex FindOrCreateTypeIndex(const DexFile& dex_file, const char* descriptor);
337
338 // Add a class with the specified `type_index` to the profile. The `type_index`
339 // can be either a normal index for a `TypeId` in the dex file, or an artificial
340 // type index created by `FindOrCreateTypeIndex()`.
AddClass(ProfileIndexType profile_index,dex::TypeIndex type_index)341 void AddClass(ProfileIndexType profile_index, dex::TypeIndex type_index) {
342 DCHECK_LT(profile_index, info_.size());
343 DexFileData* const data = info_[profile_index].get();
344 DCHECK(type_index.IsValid());
345 DCHECK(type_index.index_ <= data->num_type_ids ||
346 type_index.index_ - data->num_type_ids < extra_descriptors_.size());
347 data->class_set.insert(type_index);
348 }
349
350 // Add a class with the specified `type_index` to the profile. The `type_index`
351 // can be either a normal index for a `TypeId` in the dex file, or an artificial
352 // type index created by `FindOrCreateTypeIndex()`.
353 // Returns `true` on success, `false` on failure.
354 bool AddClass(const DexFile& dex_file,
355 dex::TypeIndex type_index,
356 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) {
357 DCHECK(type_index.IsValid());
358 DCHECK(type_index.index_ <= dex_file.NumTypeIds() ||
359 type_index.index_ - dex_file.NumTypeIds() < extra_descriptors_.size());
360 DexFileData* const data = GetOrAddDexFileData(&dex_file, annotation);
361 if (data == nullptr) { // Checksum/num_type_ids/num_method_ids mismatch or too many dex files.
362 return false;
363 }
364 data->class_set.insert(type_index);
365 return true;
366 }
367
368 // Add a class with the specified `descriptor` to the profile.
369 // Returns `true` on success, `false` on failure.
370 bool AddClass(const DexFile& dex_file,
371 const char* descriptor,
372 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone);
373 bool AddClass(const DexFile& dex_file,
374 const std::string& descriptor,
375 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) {
376 return AddClass(dex_file, descriptor.c_str(), annotation);
377 }
378 bool AddClass(const DexFile& dex_file,
379 std::string_view descriptor,
380 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) {
381 return AddClass(dex_file, std::string(descriptor).c_str(), annotation);
382 }
383
384 // Add multiple type ids for classes in a single dex file. Iterator is for type_ids not
385 // class_defs.
386 //
387 // Note: see AddMethods docs for the handling of annotations.
388 template <class Iterator>
389 bool AddClassesForDex(
390 const DexFile* dex_file,
391 Iterator index_begin,
392 Iterator index_end,
393 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) {
394 DexFileData* data = GetOrAddDexFileData(dex_file, annotation);
395 if (data == nullptr) {
396 return false;
397 }
398 data->class_set.insert(index_begin, index_end);
399 return true;
400 }
401
AddMethod(ProfileIndexType profile_index,uint32_t method_index,MethodHotness::Flag flags)402 void AddMethod(ProfileIndexType profile_index, uint32_t method_index, MethodHotness::Flag flags) {
403 DCHECK_LT(profile_index, info_.size());
404 DexFileData* const data = info_[profile_index].get();
405 DCHECK_LT(method_index, data->num_method_ids);
406 data->AddMethod(flags, method_index);
407 }
408
409 // Add a method to the profile using its online representation (containing runtime structures).
410 //
411 // Note: see AddMethods docs for the handling of annotations.
412 bool AddMethod(const ProfileMethodInfo& pmi,
413 MethodHotness::Flag flags,
414 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone);
415
416 // Bulk add sampled methods and/or hot methods for a single dex, fast since it only has one
417 // GetOrAddDexFileData call.
418 //
419 // Note: see AddMethods docs for the handling of annotations.
420 template <class Iterator>
421 bool AddMethodsForDex(
422 MethodHotness::Flag flags,
423 const DexFile* dex_file,
424 Iterator index_begin,
425 Iterator index_end,
426 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) {
427 DexFileData* data = GetOrAddDexFileData(dex_file, annotation);
428 if (data == nullptr) {
429 return false;
430 }
431 for (Iterator it = index_begin; it != index_end; ++it) {
432 DCHECK_LT(*it, data->num_method_ids);
433 if (!data->AddMethod(flags, *it)) {
434 return false;
435 }
436 }
437 return true;
438 }
439
440 // Load or Merge profile information from the given file descriptor.
441 // If the current profile is non-empty the load will fail.
442 // If merge_classes is set to false, classes will not be merged/loaded.
443 // If filter_fn is present, it will be used to filter out profile data belonging
444 // to dex file which do not comply with the filter
445 // (i.e. for which filter_fn(dex_location, dex_checksum) is false).
446 using ProfileLoadFilterFn = std::function<bool(const std::string&, uint32_t)>;
447 // Profile filter method which accepts all dex locations.
448 // This is convenient to use when we need to accept all locations without repeating the same
449 // lambda.
450 static bool ProfileFilterFnAcceptAll(const std::string& dex_location, uint32_t checksum);
451
452 bool Load(
453 int fd,
454 bool merge_classes = true,
455 const ProfileLoadFilterFn& filter_fn = ProfileFilterFnAcceptAll);
456
457 // Verify integrity of the profile file with the provided dex files.
458 // If there exists a DexData object which maps to a dex_file, then it verifies that:
459 // - The checksums of the DexData and dex_file are equals.
460 // - No method id exceeds NumMethodIds corresponding to the dex_file.
461 // - No class id exceeds NumTypeIds corresponding to the dex_file.
462 // - For every inline_caches, class_ids does not exceed NumTypeIds corresponding to
463 // the dex_file they are in.
464 bool VerifyProfileData(const std::vector<const DexFile*>& dex_files);
465
466 // Load profile information from the given file
467 // If the current profile is non-empty the load will fail.
468 // If clear_if_invalid is true and the file is invalid the method clears the
469 // the file and returns true.
470 bool Load(const std::string& filename, bool clear_if_invalid);
471
472 // Merge the data from another ProfileCompilationInfo into the current object. Only merges
473 // classes if merge_classes is true. This is used for creating the boot profile since
474 // we don't want all of the classes to be image classes.
475 bool MergeWith(const ProfileCompilationInfo& info, bool merge_classes = true);
476
477 // Merge profile information from the given file descriptor.
478 bool MergeWith(const std::string& filename);
479
480 // Save the profile data to the given file descriptor.
481 bool Save(int fd);
482
483 // Save the current profile into the given file. The file will be cleared before saving.
484 bool Save(const std::string& filename, uint64_t* bytes_written);
485
486 // Return the number of dex files referenced in the profile.
GetNumberOfDexFiles()487 size_t GetNumberOfDexFiles() const {
488 return info_.size();
489 }
490
491 // Return the number of methods that were profiled.
492 uint32_t GetNumberOfMethods() const;
493
494 // Return the number of resolved classes that were profiled.
495 uint32_t GetNumberOfResolvedClasses() const;
496
497 // Returns whether the referenced method is a startup method.
IsStartupMethod(ProfileIndexType profile_index,uint32_t method_index)498 bool IsStartupMethod(ProfileIndexType profile_index, uint32_t method_index) const {
499 return info_[profile_index]->IsStartupMethod(method_index);
500 }
501
502 // Returns whether the referenced method is a post-startup method.
IsPostStartupMethod(ProfileIndexType profile_index,uint32_t method_index)503 bool IsPostStartupMethod(ProfileIndexType profile_index, uint32_t method_index) const {
504 return info_[profile_index]->IsPostStartupMethod(method_index);
505 }
506
507 // Returns whether the referenced method is hot.
IsHotMethod(ProfileIndexType profile_index,uint32_t method_index)508 bool IsHotMethod(ProfileIndexType profile_index, uint32_t method_index) const {
509 return info_[profile_index]->IsHotMethod(method_index);
510 }
511
512 // Returns whether the referenced method is in the profile (with any hotness flag).
IsMethodInProfile(ProfileIndexType profile_index,uint32_t method_index)513 bool IsMethodInProfile(ProfileIndexType profile_index, uint32_t method_index) const {
514 DCHECK_LT(profile_index, info_.size());
515 const DexFileData* const data = info_[profile_index].get();
516 return data->IsMethodInProfile(method_index);
517 }
518
519 // Returns the profile method info for a given method reference.
520 //
521 // Note that if the profile was built with annotations, the same dex file may be
522 // represented multiple times in the profile (due to different annotation associated with it).
523 // If so, and if no annotation is passed to this method, then only the first dex file is searched.
524 //
525 // Implementation details: It is suitable to pass kNone for regular profile guided compilation
526 // because during compilation we generally don't care about annotations. The metadata is
527 // useful for boot profiles which need the extra information.
528 MethodHotness GetMethodHotness(
529 const MethodReference& method_ref,
530 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) const;
531
532 // Return true if the class's type is present in the profiling info.
ContainsClass(ProfileIndexType profile_index,dex::TypeIndex type_index)533 bool ContainsClass(ProfileIndexType profile_index, dex::TypeIndex type_index) const {
534 DCHECK_LT(profile_index, info_.size());
535 const DexFileData* const data = info_[profile_index].get();
536 DCHECK(type_index.IsValid());
537 DCHECK(type_index.index_ <= data->num_type_ids ||
538 type_index.index_ - data->num_type_ids < extra_descriptors_.size());
539 return data->class_set.find(type_index) != data->class_set.end();
540 }
541
542 // Return true if the class's type is present in the profiling info.
543 //
544 // Note: see GetMethodHotness docs for the handling of annotations.
545 bool ContainsClass(
546 const DexFile& dex_file,
547 dex::TypeIndex type_idx,
548 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) const;
549
550 // Return the dex file for the given `profile_index`, or null if none of the provided
551 // dex files has a matching checksum and a location with the same base key.
552 template <typename Container>
FindDexFileForProfileIndex(ProfileIndexType profile_index,const Container & dex_files)553 const DexFile* FindDexFileForProfileIndex(ProfileIndexType profile_index,
554 const Container& dex_files) const {
555 static_assert(std::is_same_v<typename Container::value_type, const DexFile*> ||
556 std::is_same_v<typename Container::value_type, std::unique_ptr<const DexFile>>);
557 DCHECK_LE(profile_index, info_.size());
558 const DexFileData* dex_file_data = info_[profile_index].get();
559 DCHECK(dex_file_data != nullptr);
560 uint32_t dex_checksum = dex_file_data->checksum;
561 std::string_view base_key = GetBaseKeyViewFromAugmentedKey(dex_file_data->profile_key);
562 for (const auto& dex_file : dex_files) {
563 if (dex_checksum == dex_file->GetLocationChecksum() &&
564 base_key == GetProfileDexFileBaseKeyView(dex_file->GetLocation())) {
565 return std::addressof(*dex_file);
566 }
567 }
568 return nullptr;
569 }
570
571 DexReferenceDumper DumpDexReference(ProfileIndexType profile_index) const;
572
573 // Dump all the loaded profile info into a string and returns it.
574 // If dex_files is not empty then the method indices will be resolved to their
575 // names.
576 // This is intended for testing and debugging.
577 std::string DumpInfo(const std::vector<const DexFile*>& dex_files,
578 bool print_full_dex_location = true) const;
579
580 // Return the classes and methods for a given dex file through out args. The out args are the set
581 // of class as well as the methods and their associated inline caches. Returns true if the dex
582 // file is register and has a matching checksum, false otherwise.
583 //
584 // Note: see GetMethodHotness docs for the handling of annotations.
585 bool GetClassesAndMethods(
586 const DexFile& dex_file,
587 /*out*/std::set<dex::TypeIndex>* class_set,
588 /*out*/std::set<uint16_t>* hot_method_set,
589 /*out*/std::set<uint16_t>* startup_method_set,
590 /*out*/std::set<uint16_t>* post_startup_method_method_set,
591 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone) const;
592
593 // Returns true iff both profiles have the same version.
594 bool SameVersion(const ProfileCompilationInfo& other) const;
595
596 // Perform an equality test with the `other` profile information.
597 bool Equals(const ProfileCompilationInfo& other);
598
599 // Return the base profile key associated with the given dex location. The base profile key
600 // is solely constructed based on the dex location (as opposed to the one produced by
601 // GetProfileDexFileAugmentedKey which may include additional metadata like the origin
602 // package name)
603 static std::string GetProfileDexFileBaseKey(const std::string& dex_location);
604
605 // Returns a base key without the annotation information.
606 static std::string GetBaseKeyFromAugmentedKey(const std::string& profile_key);
607
608 // Returns the annotations from an augmented key.
609 // If the key is a base key it return ProfileSampleAnnotation::kNone.
610 static ProfileSampleAnnotation GetAnnotationFromKey(const std::string& augmented_key);
611
612 // Generate a test profile which will contain a percentage of the total maximum
613 // number of methods and classes (method_ratio and class_ratio).
614 static bool GenerateTestProfile(int fd,
615 uint16_t number_of_dex_files,
616 uint16_t method_ratio,
617 uint16_t class_ratio,
618 uint32_t random_seed);
619
620 // Generate a test profile which will randomly contain classes and methods from
621 // the provided list of dex files.
622 static bool GenerateTestProfile(int fd,
623 std::vector<std::unique_ptr<const DexFile>>& dex_files,
624 uint16_t method_percentage,
625 uint16_t class_percentage,
626 uint32_t random_seed);
627
GetAllocator()628 ArenaAllocator* GetAllocator() { return &allocator_; }
629
630 // Return all of the class descriptors in the profile for a set of dex files.
631 // Note: see GetMethodHotness docs for the handling of annotations..
632 HashSet<std::string> GetClassDescriptors(
633 const std::vector<const DexFile*>& dex_files,
634 const ProfileSampleAnnotation& annotation = ProfileSampleAnnotation::kNone);
635
636 // Return true if the fd points to a profile file.
637 bool IsProfileFile(int fd);
638
639 // Update the profile keys corresponding to the given dex files based on their current paths.
640 // This method allows fix-ups in the profile for dex files that might have been renamed.
641 // The new profile key will be constructed based on the current dex location.
642 //
643 // The matching [profile key <-> dex_file] is done based on the dex checksum and the number of
644 // methods ids. If neither is a match then the profile key is not updated.
645 //
646 // If the new profile key would collide with an existing key (for a different dex)
647 // the method returns false. Otherwise it returns true.
648 bool UpdateProfileKeys(const std::vector<std::unique_ptr<const DexFile>>& dex_files);
649
650 // Checks if the profile is empty.
651 bool IsEmpty() const;
652
653 // Clears all the data from the profile.
654 void ClearData();
655
656 // Clears all the data from the profile and adjust the object version.
657 void ClearDataAndAdjustVersion(bool for_boot_image);
658
659 // Prepare the profile to store aggregation counters.
660 // This will change the profile version and allocate extra storage for the counters.
661 // It allocates 2 bytes for every possible method and class, so do not use in performance
662 // critical code which needs to be memory efficient.
663 void PrepareForAggregationCounters();
664
665 // Returns true if the profile is configured to store aggregation counters.
666 bool IsForBootImage() const;
667
668 // Get type descriptor for a valid type index, whether a normal type index
669 // referencing a `dex::TypeId` in the dex file, or an artificial type index
670 // referencing an "extra descriptor".
GetTypeDescriptor(const DexFile * dex_file,dex::TypeIndex type_index)671 const char* GetTypeDescriptor(const DexFile* dex_file, dex::TypeIndex type_index) const {
672 DCHECK(type_index.IsValid());
673 uint32_t num_type_ids = dex_file->NumTypeIds();
674 if (type_index.index_ < num_type_ids) {
675 return dex_file->StringByTypeIdx(type_index);
676 } else {
677 return extra_descriptors_[type_index.index_ - num_type_ids].c_str();
678 }
679 }
680
681 // Return the version of this profile.
682 const uint8_t* GetVersion() const;
683
684 // Extracts the data that the profile has on the given dex files:
685 // - for each method and class, a list of the corresponding annotations and flags
686 // - the maximum number of aggregations for classes and classes across dex files with different
687 // annotations (essentially this sums up how many different packages used the corresponding
688 // method). This information is reconstructible from the other two pieces of info, but it's
689 // convenient to have it precomputed.
690 std::unique_ptr<FlattenProfileData> ExtractProfileData(
691 const std::vector<std::unique_ptr<const DexFile>>& dex_files) const;
692
693 private:
694 // Helper classes.
695 class FileHeader;
696 class FileSectionInfo;
697 enum class FileSectionType : uint32_t;
698 enum class ProfileLoadStatus : uint32_t;
699 class ProfileSource;
700 class SafeBuffer;
701
702 // Extra descriptors are used to reference classes with `TypeIndex` between the dex
703 // file's `NumTypeIds()` and the `DexFile::kDexNoIndex16`. The range of usable
704 // extra descriptor indexes is therefore also limited by `DexFile::kDexNoIndex16`.
705 using ExtraDescriptorIndex = uint16_t;
706 static constexpr ExtraDescriptorIndex kMaxExtraDescriptors = DexFile::kDexNoIndex16;
707
708 class ExtraDescriptorIndexEmpty {
709 public:
MakeEmpty(ExtraDescriptorIndex & index)710 void MakeEmpty(ExtraDescriptorIndex& index) const {
711 index = kMaxExtraDescriptors;
712 }
IsEmpty(const ExtraDescriptorIndex & index)713 bool IsEmpty(const ExtraDescriptorIndex& index) const {
714 return index == kMaxExtraDescriptors;
715 }
716 };
717
718 class ExtraDescriptorHash {
719 public:
ExtraDescriptorHash(const dchecked_vector<std::string> * extra_descriptors)720 explicit ExtraDescriptorHash(const dchecked_vector<std::string>* extra_descriptors)
721 : extra_descriptors_(extra_descriptors) {}
722
operator()723 size_t operator()(const ExtraDescriptorIndex& index) const {
724 std::string_view str = (*extra_descriptors_)[index];
725 return (*this)(str);
726 }
727
operator()728 size_t operator()(std::string_view str) const {
729 return DataHash()(str);
730 }
731
732 private:
733 const dchecked_vector<std::string>* extra_descriptors_;
734 };
735
736 class ExtraDescriptorEquals {
737 public:
ExtraDescriptorEquals(const dchecked_vector<std::string> * extra_descriptors)738 explicit ExtraDescriptorEquals(const dchecked_vector<std::string>* extra_descriptors)
739 : extra_descriptors_(extra_descriptors) {}
740
operator()741 size_t operator()(const ExtraDescriptorIndex& lhs, const ExtraDescriptorIndex& rhs) const {
742 DCHECK_EQ(lhs == rhs, (*this)(lhs, (*extra_descriptors_)[rhs]));
743 return lhs == rhs;
744 }
745
operator()746 size_t operator()(const ExtraDescriptorIndex& lhs, std::string_view rhs_str) const {
747 std::string_view lhs_str = (*extra_descriptors_)[lhs];
748 return lhs_str == rhs_str;
749 }
750
751 private:
752 const dchecked_vector<std::string>* extra_descriptors_;
753 };
754
755 using ExtraDescriptorHashSet = HashSet<ExtraDescriptorIndex,
756 ExtraDescriptorIndexEmpty,
757 ExtraDescriptorHash,
758 ExtraDescriptorEquals>;
759
760 // Internal representation of the profile information belonging to a dex file.
761 // Note that we could do without the profile_index (the index of the dex file
762 // in the profile) field in this struct because we can infer it from
763 // `profile_key_map_` and `info_`. However, it makes the profiles logic much
764 // simpler if we have the profile index here as well.
765 struct DexFileData : public DeletableArenaObject<kArenaAllocProfile> {
DexFileDataDexFileData766 DexFileData(ArenaAllocator* allocator,
767 const std::string& key,
768 uint32_t location_checksum,
769 uint16_t index,
770 uint32_t num_types,
771 uint32_t num_methods,
772 bool for_boot_image)
773 : allocator_(allocator),
774 profile_key(key),
775 profile_index(index),
776 checksum(location_checksum),
777 method_map(std::less<uint16_t>(), allocator->Adapter(kArenaAllocProfile)),
778 class_set(std::less<dex::TypeIndex>(), allocator->Adapter(kArenaAllocProfile)),
779 num_type_ids(num_types),
780 num_method_ids(num_methods),
781 bitmap_storage(allocator->Adapter(kArenaAllocProfile)),
782 is_for_boot_image(for_boot_image) {
783 bitmap_storage.resize(ComputeBitmapStorage(is_for_boot_image, num_method_ids));
784 if (!bitmap_storage.empty()) {
785 method_bitmap =
786 BitMemoryRegion(MemoryRegion(
787 &bitmap_storage[0],
788 bitmap_storage.size()),
789 0,
790 ComputeBitmapBits(is_for_boot_image, num_method_ids));
791 }
792 }
793
ComputeBitmapBitsDexFileData794 static size_t ComputeBitmapBits(bool is_for_boot_image, uint32_t num_method_ids) {
795 size_t flag_bitmap_index = FlagBitmapIndex(is_for_boot_image
796 ? MethodHotness::kFlagLastBoot
797 : MethodHotness::kFlagLastRegular);
798 return num_method_ids * (flag_bitmap_index + 1);
799 }
ComputeBitmapStorageDexFileData800 static size_t ComputeBitmapStorage(bool is_for_boot_image, uint32_t num_method_ids) {
801 return RoundUp(ComputeBitmapBits(is_for_boot_image, num_method_ids), kBitsPerByte) /
802 kBitsPerByte;
803 }
804
805 bool operator==(const DexFileData& other) const {
806 return checksum == other.checksum &&
807 num_method_ids == other.num_method_ids &&
808 method_map == other.method_map &&
809 class_set == other.class_set &&
810 BitMemoryRegion::Equals(method_bitmap, other.method_bitmap);
811 }
812
813 // Mark a method as executed at least once.
814 bool AddMethod(MethodHotness::Flag flags, size_t index);
815
MergeBitmapDexFileData816 void MergeBitmap(const DexFileData& other) {
817 DCHECK_EQ(bitmap_storage.size(), other.bitmap_storage.size());
818 for (size_t i = 0; i < bitmap_storage.size(); ++i) {
819 bitmap_storage[i] |= other.bitmap_storage[i];
820 }
821 }
822
823 void SetMethodHotness(size_t index, MethodHotness::Flag flags);
824 MethodHotness GetHotnessInfo(uint32_t dex_method_index) const;
825
IsStartupMethodDexFileData826 bool IsStartupMethod(uint32_t method_index) const {
827 DCHECK_LT(method_index, num_method_ids);
828 return method_bitmap.LoadBit(
829 MethodFlagBitmapIndex(MethodHotness::Flag::kFlagStartup, method_index));
830 }
831
IsPostStartupMethodDexFileData832 bool IsPostStartupMethod(uint32_t method_index) const {
833 DCHECK_LT(method_index, num_method_ids);
834 return method_bitmap.LoadBit(
835 MethodFlagBitmapIndex(MethodHotness::Flag::kFlagPostStartup, method_index));
836 }
837
IsHotMethodDexFileData838 bool IsHotMethod(uint32_t method_index) const {
839 DCHECK_LT(method_index, num_method_ids);
840 return method_map.find(method_index) != method_map.end();
841 }
842
IsMethodInProfileDexFileData843 bool IsMethodInProfile(uint32_t method_index) const {
844 DCHECK_LT(method_index, num_method_ids);
845 bool has_flag = false;
846 ForMethodBitmapHotnessFlags([&](MethodHotness::Flag flag) {
847 if (method_bitmap.LoadBit(MethodFlagBitmapIndex(
848 static_cast<MethodHotness::Flag>(flag), method_index))) {
849 has_flag = true;
850 return false;
851 }
852 return true;
853 });
854 return has_flag || IsHotMethod(method_index);
855 }
856
857 bool ContainsClass(dex::TypeIndex type_index) const;
858
859 uint32_t ClassesDataSize() const;
860 void WriteClasses(SafeBuffer& buffer) const;
861 ProfileLoadStatus ReadClasses(
862 SafeBuffer& buffer,
863 const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
864 std::string* error);
865 static ProfileLoadStatus SkipClasses(SafeBuffer& buffer, std::string* error);
866
867 uint32_t MethodsDataSize(/*out*/ uint16_t* method_flags = nullptr,
868 /*out*/ size_t* saved_bitmap_bit_size = nullptr) const;
869 void WriteMethods(SafeBuffer& buffer) const;
870 ProfileLoadStatus ReadMethods(
871 SafeBuffer& buffer,
872 const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
873 std::string* error);
874 static ProfileLoadStatus SkipMethods(SafeBuffer& buffer, std::string* error);
875
876 // The allocator used to allocate new inline cache maps.
877 ArenaAllocator* const allocator_;
878 // The profile key this data belongs to.
879 std::string profile_key;
880 // The profile index of this dex file (matches ClassReference#dex_profile_index).
881 ProfileIndexType profile_index;
882 // The dex checksum.
883 uint32_t checksum;
884 // The methods' profile information.
885 MethodMap method_map;
886 // The classes which have been profiled. Note that these don't necessarily include
887 // all the classes that can be found in the inline caches reference.
888 ArenaSet<dex::TypeIndex> class_set;
889 // Find the inline caches of the the given method index. Add an empty entry if
890 // no previous data is found.
891 InlineCacheMap* FindOrAddHotMethod(uint16_t method_index);
892 // Num type ids.
893 uint32_t num_type_ids;
894 // Num method ids.
895 uint32_t num_method_ids;
896 ArenaVector<uint8_t> bitmap_storage;
897 BitMemoryRegion method_bitmap;
898 bool is_for_boot_image;
899
900 private:
901 template <typename Fn>
ForMethodBitmapHotnessFlagsDexFileData902 void ForMethodBitmapHotnessFlags(Fn fn) const {
903 uint32_t lastFlag = is_for_boot_image
904 ? MethodHotness::kFlagLastBoot
905 : MethodHotness::kFlagLastRegular;
906 for (uint32_t flag = MethodHotness::kFlagFirst; flag <= lastFlag; flag = flag << 1) {
907 if (flag == MethodHotness::kFlagHot) {
908 // There's no bit for hotness in the bitmap.
909 // We store the hotness by recording the method in the method list.
910 continue;
911 }
912 bool cont = fn(enum_cast<MethodHotness::Flag>(flag));
913 if (!cont) {
914 break;
915 }
916 }
917 }
918
MethodFlagBitmapIndexDexFileData919 size_t MethodFlagBitmapIndex(MethodHotness::Flag flag, size_t method_index) const {
920 DCHECK_LT(method_index, num_method_ids);
921 // The format is [startup bitmap][post startup bitmap][AmStartup][...]
922 // This compresses better than ([startup bit][post startup bit])*
923 return method_index + FlagBitmapIndex(flag) * num_method_ids;
924 }
925
FlagBitmapIndexDexFileData926 static size_t FlagBitmapIndex(MethodHotness::Flag flag) {
927 DCHECK(flag != MethodHotness::kFlagHot);
928 DCHECK(IsPowerOfTwo(static_cast<uint32_t>(flag)));
929 // We arrange the method flags in order, starting with the startup flag.
930 // The kFlagHot is not encoded in the bitmap and thus not expected as an
931 // argument here. Since all the other flags start at 1 we have to subtract
932 // one from the power of 2.
933 return WhichPowerOf2(static_cast<uint32_t>(flag)) - 1;
934 }
935
936 static void WriteClassSet(SafeBuffer& buffer, const ArenaSet<dex::TypeIndex>& class_set);
937
938 uint16_t GetUsedBitmapFlags() const;
939 };
940
941 // Return the profile data for the given profile key or null if the dex location
942 // already exists but has a different checksum
943 DexFileData* GetOrAddDexFileData(const std::string& profile_key,
944 uint32_t checksum,
945 uint32_t num_type_ids,
946 uint32_t num_method_ids);
947
GetOrAddDexFileData(const DexFile * dex_file,const ProfileSampleAnnotation & annotation)948 DexFileData* GetOrAddDexFileData(const DexFile* dex_file,
949 const ProfileSampleAnnotation& annotation) {
950 return GetOrAddDexFileData(GetProfileDexFileAugmentedKey(dex_file->GetLocation(), annotation),
951 dex_file->GetLocationChecksum(),
952 dex_file->NumTypeIds(),
953 dex_file->NumMethodIds());
954 }
955
956 // Return the dex data associated with the given profile key or null if the profile
957 // doesn't contain the key.
958 const DexFileData* FindDexData(const std::string& profile_key,
959 uint32_t checksum,
960 bool verify_checksum = true) const;
961 // Same as FindDexData but performs the searching using the given annotation:
962 // - If the annotation is kNone then the search ignores it and only looks at the base keys.
963 // In this case only the first matching dex is searched.
964 // - If the annotation is not kNone, the augmented key is constructed and used to invoke
965 // the regular FindDexData.
966 const DexFileData* FindDexDataUsingAnnotations(
967 const DexFile* dex_file,
968 const ProfileSampleAnnotation& annotation) const;
969
970 // Same as FindDexDataUsingAnnotations but extracts the data for all annotations.
971 void FindAllDexData(
972 const DexFile* dex_file,
973 /*out*/ std::vector<const ProfileCompilationInfo::DexFileData*>* result) const;
974
975 // Add a new extra descriptor. Returns kMaxExtraDescriptors on failure.
976 ExtraDescriptorIndex AddExtraDescriptor(std::string_view extra_descriptor);
977
978 // Parsing functionality.
979
980 ProfileLoadStatus OpenSource(int32_t fd,
981 /*out*/ std::unique_ptr<ProfileSource>* source,
982 /*out*/ std::string* error);
983
984 ProfileLoadStatus ReadSectionData(ProfileSource& source,
985 const FileSectionInfo& section_info,
986 /*out*/ SafeBuffer* buffer,
987 /*out*/ std::string* error);
988
989 ProfileLoadStatus ReadDexFilesSection(
990 ProfileSource& source,
991 const FileSectionInfo& section_info,
992 const ProfileLoadFilterFn& filter_fn,
993 /*out*/ dchecked_vector<ProfileIndexType>* dex_profile_index_remap,
994 /*out*/ std::string* error);
995
996 ProfileLoadStatus ReadExtraDescriptorsSection(
997 ProfileSource& source,
998 const FileSectionInfo& section_info,
999 /*out*/ dchecked_vector<ExtraDescriptorIndex>* extra_descriptors_remap,
1000 /*out*/ std::string* error);
1001
1002 ProfileLoadStatus ReadClassesSection(
1003 ProfileSource& source,
1004 const FileSectionInfo& section_info,
1005 const dchecked_vector<ProfileIndexType>& dex_profile_index_remap,
1006 const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
1007 /*out*/ std::string* error);
1008
1009 ProfileLoadStatus ReadMethodsSection(
1010 ProfileSource& source,
1011 const FileSectionInfo& section_info,
1012 const dchecked_vector<ProfileIndexType>& dex_profile_index_remap,
1013 const dchecked_vector<ExtraDescriptorIndex>& extra_descriptors_remap,
1014 /*out*/ std::string* error);
1015
1016 // Entry point for profile loading functionality.
1017 ProfileLoadStatus LoadInternal(
1018 int32_t fd,
1019 std::string* error,
1020 bool merge_classes = true,
1021 const ProfileLoadFilterFn& filter_fn = ProfileFilterFnAcceptAll);
1022
1023 // Find the data for the dex_pc in the inline cache. Adds an empty entry
1024 // if no previous data exists.
1025 static DexPcData* FindOrAddDexPc(InlineCacheMap* inline_cache, uint32_t dex_pc);
1026
1027 // Initializes the profile version to the desired one.
1028 void InitProfileVersionInternal(const uint8_t version[]);
1029
1030 // Returns the threshold size (in bytes) which will trigger save/load warnings.
1031 size_t GetSizeWarningThresholdBytes() const;
1032 // Returns the threshold size (in bytes) which will cause save/load failures.
1033 size_t GetSizeErrorThresholdBytes() const;
1034
1035 // Implementation of `GetProfileDexFileBaseKey()` but returning a subview
1036 // referencing the same underlying data to avoid excessive heap allocations.
1037 static std::string_view GetProfileDexFileBaseKeyView(std::string_view dex_location);
1038
1039 // Implementation of `GetBaseKeyFromAugmentedKey()` but returning a subview
1040 // referencing the same underlying data to avoid excessive heap allocations.
1041 static std::string_view GetBaseKeyViewFromAugmentedKey(std::string_view dex_location);
1042
1043 // Returns the augmented profile key associated with the given dex location.
1044 // The return key will contain a serialized form of the information from the provided
1045 // annotation. If the annotation is ProfileSampleAnnotation::kNone then no extra info is
1046 // added to the key and this method is equivalent to GetProfileDexFileBaseKey.
1047 static std::string GetProfileDexFileAugmentedKey(const std::string& dex_location,
1048 const ProfileSampleAnnotation& annotation);
1049
1050 // Migrates the annotation from an augmented key to a base key.
1051 static std::string MigrateAnnotationInfo(const std::string& base_key,
1052 const std::string& augmented_key);
1053
1054 friend class ProfileCompilationInfoTest;
1055 friend class CompilerDriverProfileTest;
1056 friend class ProfileAssistantTest;
1057 friend class Dex2oatLayoutTest;
1058
1059 MallocArenaPool default_arena_pool_;
1060 ArenaAllocator allocator_;
1061
1062 // Vector containing the actual profile info.
1063 // The vector index is the profile index of the dex data and
1064 // matched DexFileData::profile_index.
1065 ArenaVector<std::unique_ptr<DexFileData>> info_;
1066
1067 // Cache mapping profile keys to profile index.
1068 // This is used to speed up searches since it avoids iterating
1069 // over the info_ vector when searching by profile key.
1070 // The backing storage for the `string_view` is the associated `DexFileData`.
1071 ArenaSafeMap<const std::string_view, ProfileIndexType> profile_key_map_;
1072
1073 // Additional descriptors for referencing types not present in a dex files's `TypeId`s.
1074 dchecked_vector<std::string> extra_descriptors_;
1075 ExtraDescriptorHashSet extra_descriptors_indexes_;
1076
1077 // The version of the profile.
1078 uint8_t version_[kProfileVersionSize];
1079 };
1080
1081 /**
1082 * Flatten profile data that list all methods and type references together
1083 * with their metadata (such as flags or annotation list).
1084 */
1085 class FlattenProfileData {
1086 public:
1087 class ItemMetadata {
1088 public:
1089 ItemMetadata();
1090 ItemMetadata(const ItemMetadata& other);
1091
GetFlags()1092 uint16_t GetFlags() const {
1093 return flags_;
1094 }
1095
GetAnnotations()1096 const std::list<ProfileCompilationInfo::ProfileSampleAnnotation>& GetAnnotations() const {
1097 return annotations_;
1098 }
1099
AddFlag(ProfileCompilationInfo::MethodHotness::Flag flag)1100 void AddFlag(ProfileCompilationInfo::MethodHotness::Flag flag) {
1101 flags_ |= flag;
1102 }
1103
HasFlagSet(ProfileCompilationInfo::MethodHotness::Flag flag)1104 bool HasFlagSet(ProfileCompilationInfo::MethodHotness::Flag flag) const {
1105 return (flags_ & flag) != 0;
1106 }
1107
1108 private:
1109 // will be 0 for classes and MethodHotness::Flags for methods.
1110 uint16_t flags_;
1111 // This is a list that may contain duplicates after a merge operation.
1112 // It represents that a method was used multiple times across different devices.
1113 std::list<ProfileCompilationInfo::ProfileSampleAnnotation> annotations_;
1114
1115 friend class ProfileCompilationInfo;
1116 friend class FlattenProfileData;
1117 };
1118
1119 FlattenProfileData();
1120
GetMethodData()1121 const SafeMap<MethodReference, ItemMetadata>& GetMethodData() const {
1122 return method_metadata_;
1123 }
1124
GetClassData()1125 const SafeMap<TypeReference, ItemMetadata>& GetClassData() const {
1126 return class_metadata_;
1127 }
1128
GetMaxAggregationForMethods()1129 uint32_t GetMaxAggregationForMethods() const {
1130 return max_aggregation_for_methods_;
1131 }
1132
GetMaxAggregationForClasses()1133 uint32_t GetMaxAggregationForClasses() const {
1134 return max_aggregation_for_classes_;
1135 }
1136
1137 void MergeData(const FlattenProfileData& other);
1138
1139 private:
1140 // Method data.
1141 SafeMap<MethodReference, ItemMetadata> method_metadata_;
1142 // Class data.
1143 SafeMap<TypeReference, ItemMetadata> class_metadata_;
1144 // Maximum aggregation counter for all methods.
1145 // This is essentially a cache equal to the max size of any method's annotation set.
1146 // It avoids the traversal of all the methods which can be quite expensive.
1147 uint32_t max_aggregation_for_methods_;
1148 // Maximum aggregation counter for all classes.
1149 // Simillar to max_aggregation_for_methods_.
1150 uint32_t max_aggregation_for_classes_;
1151
1152 friend class ProfileCompilationInfo;
1153 };
1154
1155 struct ProfileCompilationInfo::DexReferenceDumper {
GetProfileKeyDexReferenceDumper1156 const std::string& GetProfileKey() {
1157 return dex_file_data->profile_key;
1158 }
1159
GetDexChecksumDexReferenceDumper1160 uint32_t GetDexChecksum() const {
1161 return dex_file_data->checksum;
1162 }
1163
GetNumTypeIdsDexReferenceDumper1164 uint32_t GetNumTypeIds() const {
1165 return dex_file_data->num_type_ids;
1166 }
1167
GetNumMethodIdsDexReferenceDumper1168 uint32_t GetNumMethodIds() const {
1169 return dex_file_data->num_method_ids;
1170 }
1171
1172 const DexFileData* dex_file_data;
1173 };
1174
DumpDexReference(ProfileIndexType profile_index)1175 inline ProfileCompilationInfo::DexReferenceDumper ProfileCompilationInfo::DumpDexReference(
1176 ProfileIndexType profile_index) const {
1177 return DexReferenceDumper{info_[profile_index].get()};
1178 }
1179
1180 std::ostream& operator<<(std::ostream& stream, ProfileCompilationInfo::DexReferenceDumper dumper);
1181
1182 } // namespace art
1183
1184 #endif // ART_LIBPROFILE_PROFILE_PROFILE_COMPILATION_INFO_H_
1185