blob: 9ea1b9bd2fe3f47f836ed970de8bfe0bb57e5536 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- InstrProf.h - Instrumented profiling format support ------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
7//===----------------------------------------------------------------------===//
8//
9// Instrumentation-based profiling data is generated by instrumented
10// binaries through library functions in compiler-rt, and read by the clang
11// frontend to feed PGO.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_PROFILEDATA_INSTRPROF_H
16#define LLVM_PROFILEDATA_INSTRPROF_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/StringSet.h"
22#include "llvm/ADT/Triple.h"
23#include "llvm/IR/GlobalValue.h"
24#include "llvm/IR/ProfileSummary.h"
25#include "llvm/ProfileData/InstrProfData.inc"
26#include "llvm/Support/Compiler.h"
27#include "llvm/Support/Endian.h"
28#include "llvm/Support/Error.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/Host.h"
31#include "llvm/Support/MD5.h"
32#include "llvm/Support/MathExtras.h"
33#include "llvm/Support/raw_ostream.h"
34#include <algorithm>
35#include <cassert>
36#include <cstddef>
37#include <cstdint>
38#include <cstring>
39#include <list>
40#include <memory>
41#include <string>
42#include <system_error>
43#include <utility>
44#include <vector>
45
46namespace llvm {
47
48class Function;
49class GlobalVariable;
50struct InstrProfRecord;
51class InstrProfSymtab;
52class Instruction;
53class MDNode;
54class Module;
55
56enum InstrProfSectKind {
57#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) Kind,
58#include "llvm/ProfileData/InstrProfData.inc"
59};
60
61/// Return the name of the profile section corresponding to \p IPSK.
62///
63/// The name of the section depends on the object format type \p OF. If
64/// \p AddSegmentInfo is true, a segment prefix and additional linker hints may
65/// be added to the section name (this is the default).
66std::string getInstrProfSectionName(InstrProfSectKind IPSK,
67 Triple::ObjectFormatType OF,
68 bool AddSegmentInfo = true);
69
70/// Return the name profile runtime entry point to do value profiling
71/// for a given site.
72inline StringRef getInstrProfValueProfFuncName() {
73 return INSTR_PROF_VALUE_PROF_FUNC_STR;
74}
75
76/// Return the name profile runtime entry point to do value range profiling.
77inline StringRef getInstrProfValueRangeProfFuncName() {
78 return INSTR_PROF_VALUE_RANGE_PROF_FUNC_STR;
79}
80
81/// Return the name prefix of variables containing instrumented function names.
82inline StringRef getInstrProfNameVarPrefix() { return "__profn_"; }
83
84/// Return the name prefix of variables containing per-function control data.
85inline StringRef getInstrProfDataVarPrefix() { return "__profd_"; }
86
87/// Return the name prefix of profile counter variables.
88inline StringRef getInstrProfCountersVarPrefix() { return "__profc_"; }
89
90/// Return the name prefix of value profile variables.
91inline StringRef getInstrProfValuesVarPrefix() { return "__profvp_"; }
92
93/// Return the name of value profile node array variables:
94inline StringRef getInstrProfVNodesVarName() { return "__llvm_prf_vnodes"; }
95
96/// Return the name prefix of the COMDAT group for instrumentation variables
97/// associated with a COMDAT function.
98inline StringRef getInstrProfComdatPrefix() { return "__profv_"; }
99
100/// Return the name of the variable holding the strings (possibly compressed)
101/// of all function's PGO names.
102inline StringRef getInstrProfNamesVarName() {
103 return "__llvm_prf_nm";
104}
105
106/// Return the name of a covarage mapping variable (internal linkage)
107/// for each instrumented source module. Such variables are allocated
108/// in the __llvm_covmap section.
109inline StringRef getCoverageMappingVarName() {
110 return "__llvm_coverage_mapping";
111}
112
113/// Return the name of the internal variable recording the array
114/// of PGO name vars referenced by the coverage mapping. The owning
115/// functions of those names are not emitted by FE (e.g, unused inline
116/// functions.)
117inline StringRef getCoverageUnusedNamesVarName() {
118 return "__llvm_coverage_names";
119}
120
121/// Return the name of function that registers all the per-function control
122/// data at program startup time by calling __llvm_register_function. This
123/// function has internal linkage and is called by __llvm_profile_init
124/// runtime method. This function is not generated for these platforms:
125/// Darwin, Linux, and FreeBSD.
126inline StringRef getInstrProfRegFuncsName() {
127 return "__llvm_profile_register_functions";
128}
129
130/// Return the name of the runtime interface that registers per-function control
131/// data for one instrumented function.
132inline StringRef getInstrProfRegFuncName() {
133 return "__llvm_profile_register_function";
134}
135
136/// Return the name of the runtime interface that registers the PGO name strings.
137inline StringRef getInstrProfNamesRegFuncName() {
138 return "__llvm_profile_register_names_function";
139}
140
141/// Return the name of the runtime initialization method that is generated by
142/// the compiler. The function calls __llvm_profile_register_functions and
143/// __llvm_profile_override_default_filename functions if needed. This function
144/// has internal linkage and invoked at startup time via init_array.
145inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
146
147/// Return the name of the hook variable defined in profile runtime library.
148/// A reference to the variable causes the linker to link in the runtime
149/// initialization module (which defines the hook variable).
150inline StringRef getInstrProfRuntimeHookVarName() {
151 return INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_RUNTIME_VAR);
152}
153
154/// Return the name of the compiler generated function that references the
155/// runtime hook variable. The function is a weak global.
156inline StringRef getInstrProfRuntimeHookVarUseFuncName() {
157 return "__llvm_profile_runtime_user";
158}
159
160/// Return the marker used to separate PGO names during serialization.
161inline StringRef getInstrProfNameSeparator() { return "\01"; }
162
163/// Return the modified name for function \c F suitable to be
164/// used the key for profile lookup. Variable \c InLTO indicates if this
165/// is called in LTO optimization passes.
166std::string getPGOFuncName(const Function &F, bool InLTO = false,
167 uint64_t Version = INSTR_PROF_INDEX_VERSION);
168
169/// Return the modified name for a function suitable to be
170/// used the key for profile lookup. The function's original
171/// name is \c RawFuncName and has linkage of type \c Linkage.
172/// The function is defined in module \c FileName.
173std::string getPGOFuncName(StringRef RawFuncName,
174 GlobalValue::LinkageTypes Linkage,
175 StringRef FileName,
176 uint64_t Version = INSTR_PROF_INDEX_VERSION);
177
178/// Return the name of the global variable used to store a function
179/// name in PGO instrumentation. \c FuncName is the name of the function
180/// returned by the \c getPGOFuncName call.
181std::string getPGOFuncNameVarName(StringRef FuncName,
182 GlobalValue::LinkageTypes Linkage);
183
184/// Create and return the global variable for function name used in PGO
185/// instrumentation. \c FuncName is the name of the function returned
186/// by \c getPGOFuncName call.
187GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName);
188
189/// Create and return the global variable for function name used in PGO
190/// instrumentation. /// \c FuncName is the name of the function
191/// returned by \c getPGOFuncName call, \c M is the owning module,
192/// and \c Linkage is the linkage of the instrumented function.
193GlobalVariable *createPGOFuncNameVar(Module &M,
194 GlobalValue::LinkageTypes Linkage,
195 StringRef PGOFuncName);
196
197/// Return the initializer in string of the PGO name var \c NameVar.
198StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar);
199
200/// Given a PGO function name, remove the filename prefix and return
201/// the original (static) function name.
202StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName,
203 StringRef FileName = "<unknown>");
204
205/// Given a vector of strings (function PGO names) \c NameStrs, the
206/// method generates a combined string \c Result thatis ready to be
207/// serialized. The \c Result string is comprised of three fields:
208/// The first field is the legnth of the uncompressed strings, and the
209/// the second field is the length of the zlib-compressed string.
210/// Both fields are encoded in ULEB128. If \c doCompress is false, the
211/// third field is the uncompressed strings; otherwise it is the
212/// compressed string. When the string compression is off, the
213/// second field will have value zero.
214Error collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs,
215 bool doCompression, std::string &Result);
216
217/// Produce \c Result string with the same format described above. The input
218/// is vector of PGO function name variables that are referenced.
219Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
220 std::string &Result, bool doCompression = true);
221
222/// \c NameStrings is a string composed of one of more sub-strings encoded in
223/// the format described above. The substrings are separated by 0 or more zero
224/// bytes. This method decodes the string and populates the \c Symtab.
225Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab);
226
227/// Check if INSTR_PROF_RAW_VERSION_VAR is defined. This global is only being
228/// set in IR PGO compilation.
229bool isIRPGOFlagSet(const Module *M);
230
231/// Check if we can safely rename this Comdat function. Instances of the same
232/// comdat function may have different control flows thus can not share the
233/// same counter variable.
234bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken = false);
235
236enum InstrProfValueKind : uint32_t {
237#define VALUE_PROF_KIND(Enumerator, Value) Enumerator = Value,
238#include "llvm/ProfileData/InstrProfData.inc"
239};
240
241/// Get the value profile data for value site \p SiteIdx from \p InstrProfR
242/// and annotate the instruction \p Inst with the value profile meta data.
243/// Annotate up to \p MaxMDCount (default 3) number of records per value site.
244void annotateValueSite(Module &M, Instruction &Inst,
245 const InstrProfRecord &InstrProfR,
246 InstrProfValueKind ValueKind, uint32_t SiteIndx,
247 uint32_t MaxMDCount = 3);
248
249/// Same as the above interface but using an ArrayRef, as well as \p Sum.
250void annotateValueSite(Module &M, Instruction &Inst,
251 ArrayRef<InstrProfValueData> VDs, uint64_t Sum,
252 InstrProfValueKind ValueKind, uint32_t MaxMDCount);
253
254/// Extract the value profile data from \p Inst which is annotated with
255/// value profile meta data. Return false if there is no value data annotated,
256/// otherwise return true.
257bool getValueProfDataFromInst(const Instruction &Inst,
258 InstrProfValueKind ValueKind,
259 uint32_t MaxNumValueData,
260 InstrProfValueData ValueData[],
261 uint32_t &ActualNumValueData, uint64_t &TotalC);
262
263inline StringRef getPGOFuncNameMetadataName() { return "PGOFuncName"; }
264
265/// Return the PGOFuncName meta data associated with a function.
266MDNode *getPGOFuncNameMetadata(const Function &F);
267
268/// Create the PGOFuncName meta data if PGOFuncName is different from
269/// function's raw name. This should only apply to internal linkage functions
270/// declared by users only.
271void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName);
272
273/// Check if we can use Comdat for profile variables. This will eliminate
274/// the duplicated profile variables for Comdat functions.
275bool needsComdatForCounter(const Function &F, const Module &M);
276
277const std::error_category &instrprof_category();
278
279enum class instrprof_error {
280 success = 0,
281 eof,
282 unrecognized_format,
283 bad_magic,
284 bad_header,
285 unsupported_version,
286 unsupported_hash_type,
287 too_large,
288 truncated,
289 malformed,
290 unknown_function,
291 hash_mismatch,
292 count_mismatch,
293 counter_overflow,
294 value_site_count_mismatch,
295 compress_failed,
296 uncompress_failed,
297 empty_raw_profile,
298 zlib_unavailable
299};
300
301inline std::error_code make_error_code(instrprof_error E) {
302 return std::error_code(static_cast<int>(E), instrprof_category());
303}
304
305class InstrProfError : public ErrorInfo<InstrProfError> {
306public:
307 InstrProfError(instrprof_error Err) : Err(Err) {
308 assert(Err != instrprof_error::success && "Not an error");
309 }
310
311 std::string message() const override;
312
313 void log(raw_ostream &OS) const override { OS << message(); }
314
315 std::error_code convertToErrorCode() const override {
316 return make_error_code(Err);
317 }
318
319 instrprof_error get() const { return Err; }
320
321 /// Consume an Error and return the raw enum value contained within it. The
322 /// Error must either be a success value, or contain a single InstrProfError.
323 static instrprof_error take(Error E) {
324 auto Err = instrprof_error::success;
325 handleAllErrors(std::move(E), [&Err](const InstrProfError &IPE) {
326 assert(Err == instrprof_error::success && "Multiple errors encountered");
327 Err = IPE.get();
328 });
329 return Err;
330 }
331
332 static char ID;
333
334private:
335 instrprof_error Err;
336};
337
338class SoftInstrProfErrors {
339 /// Count the number of soft instrprof_errors encountered and keep track of
340 /// the first such error for reporting purposes.
341
342 /// The first soft error encountered.
343 instrprof_error FirstError = instrprof_error::success;
344
345 /// The number of hash mismatches.
346 unsigned NumHashMismatches = 0;
347
348 /// The number of count mismatches.
349 unsigned NumCountMismatches = 0;
350
351 /// The number of counter overflows.
352 unsigned NumCounterOverflows = 0;
353
354 /// The number of value site count mismatches.
355 unsigned NumValueSiteCountMismatches = 0;
356
357public:
358 SoftInstrProfErrors() = default;
359
360 ~SoftInstrProfErrors() {
361 assert(FirstError == instrprof_error::success &&
362 "Unchecked soft error encountered");
363 }
364
365 /// Track a soft error (\p IE) and increment its associated counter.
366 void addError(instrprof_error IE);
367
368 /// Get the number of hash mismatches.
369 unsigned getNumHashMismatches() const { return NumHashMismatches; }
370
371 /// Get the number of count mismatches.
372 unsigned getNumCountMismatches() const { return NumCountMismatches; }
373
374 /// Get the number of counter overflows.
375 unsigned getNumCounterOverflows() const { return NumCounterOverflows; }
376
377 /// Get the number of value site count mismatches.
378 unsigned getNumValueSiteCountMismatches() const {
379 return NumValueSiteCountMismatches;
380 }
381
382 /// Return the first encountered error and reset FirstError to a success
383 /// value.
384 Error takeError() {
385 if (FirstError == instrprof_error::success)
386 return Error::success();
387 auto E = make_error<InstrProfError>(FirstError);
388 FirstError = instrprof_error::success;
389 return E;
390 }
391};
392
393namespace object {
394
395class SectionRef;
396
397} // end namespace object
398
399namespace IndexedInstrProf {
400
401uint64_t ComputeHash(StringRef K);
402
403} // end namespace IndexedInstrProf
404
405/// A symbol table used for function PGO name look-up with keys
406/// (such as pointers, md5hash values) to the function. A function's
407/// PGO name or name's md5hash are used in retrieving the profile
408/// data of the function. See \c getPGOFuncName() method for details
409/// on how PGO name is formed.
410class InstrProfSymtab {
411public:
412 using AddrHashMap = std::vector<std::pair<uint64_t, uint64_t>>;
413
414private:
415 StringRef Data;
416 uint64_t Address = 0;
417 // Unique name strings.
418 StringSet<> NameTab;
419 // A map from MD5 keys to function name strings.
420 std::vector<std::pair<uint64_t, StringRef>> MD5NameMap;
421 // A map from MD5 keys to function define. We only populate this map
422 // when build the Symtab from a Module.
423 std::vector<std::pair<uint64_t, Function *>> MD5FuncMap;
424 // A map from function runtime address to function name MD5 hash.
425 // This map is only populated and used by raw instr profile reader.
426 AddrHashMap AddrToMD5Map;
427 bool Sorted = false;
428
429 static StringRef getExternalSymbol() {
430 return "** External Symbol **";
431 }
432
433 // If the symtab is created by a series of calls to \c addFuncName, \c
434 // finalizeSymtab needs to be called before looking up function names.
435 // This is required because the underlying map is a vector (for space
436 // efficiency) which needs to be sorted.
437 inline void finalizeSymtab();
438
439public:
440 InstrProfSymtab() = default;
441
442 /// Create InstrProfSymtab from an object file section which
443 /// contains function PGO names. When section may contain raw
444 /// string data or string data in compressed form. This method
445 /// only initialize the symtab with reference to the data and
446 /// the section base address. The decompression will be delayed
447 /// until before it is used. See also \c create(StringRef) method.
448 Error create(object::SectionRef &Section);
449
450 /// This interface is used by reader of CoverageMapping test
451 /// format.
452 inline Error create(StringRef D, uint64_t BaseAddr);
453
454 /// \c NameStrings is a string composed of one of more sub-strings
455 /// encoded in the format described in \c collectPGOFuncNameStrings.
456 /// This method is a wrapper to \c readPGOFuncNameStrings method.
457 inline Error create(StringRef NameStrings);
458
459 /// A wrapper interface to populate the PGO symtab with functions
460 /// decls from module \c M. This interface is used by transformation
461 /// passes such as indirect function call promotion. Variable \c InLTO
462 /// indicates if this is called from LTO optimization passes.
463 Error create(Module &M, bool InLTO = false);
464
465 /// Create InstrProfSymtab from a set of names iteratable from
466 /// \p IterRange. This interface is used by IndexedProfReader.
467 template <typename NameIterRange> Error create(const NameIterRange &IterRange);
468
469 /// Update the symtab by adding \p FuncName to the table. This interface
470 /// is used by the raw and text profile readers.
471 Error addFuncName(StringRef FuncName) {
472 if (FuncName.empty())
473 return make_error<InstrProfError>(instrprof_error::malformed);
474 auto Ins = NameTab.insert(FuncName);
475 if (Ins.second) {
476 MD5NameMap.push_back(std::make_pair(
477 IndexedInstrProf::ComputeHash(FuncName), Ins.first->getKey()));
478 Sorted = false;
479 }
480 return Error::success();
481 }
482
483 /// Map a function address to its name's MD5 hash. This interface
484 /// is only used by the raw profiler reader.
485 void mapAddress(uint64_t Addr, uint64_t MD5Val) {
486 AddrToMD5Map.push_back(std::make_pair(Addr, MD5Val));
487 }
488
489 /// Return a function's hash, or 0, if the function isn't in this SymTab.
490 uint64_t getFunctionHashFromAddress(uint64_t Address);
491
492 /// Return function's PGO name from the function name's symbol
493 /// address in the object file. If an error occurs, return
494 /// an empty string.
495 StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize);
496
497 /// Return function's PGO name from the name's md5 hash value.
498 /// If not found, return an empty string.
499 inline StringRef getFuncName(uint64_t FuncMD5Hash);
500
501 /// Just like getFuncName, except that it will return a non-empty StringRef
502 /// if the function is external to this symbol table. All such cases
503 /// will be represented using the same StringRef value.
504 inline StringRef getFuncNameOrExternalSymbol(uint64_t FuncMD5Hash);
505
506 /// True if Symbol is the value used to represent external symbols.
507 static bool isExternalSymbol(const StringRef &Symbol) {
508 return Symbol == InstrProfSymtab::getExternalSymbol();
509 }
510
511 /// Return function from the name's md5 hash. Return nullptr if not found.
512 inline Function *getFunction(uint64_t FuncMD5Hash);
513
514 /// Return the function's original assembly name by stripping off
515 /// the prefix attached (to symbols with priviate linkage). For
516 /// global functions, it returns the same string as getFuncName.
517 inline StringRef getOrigFuncName(uint64_t FuncMD5Hash);
518
519 /// Return the name section data.
520 inline StringRef getNameData() const { return Data; }
521};
522
523Error InstrProfSymtab::create(StringRef D, uint64_t BaseAddr) {
524 Data = D;
525 Address = BaseAddr;
526 return Error::success();
527}
528
529Error InstrProfSymtab::create(StringRef NameStrings) {
530 return readPGOFuncNameStrings(NameStrings, *this);
531}
532
533template <typename NameIterRange>
534Error InstrProfSymtab::create(const NameIterRange &IterRange) {
535 for (auto Name : IterRange)
536 if (Error E = addFuncName(Name))
537 return E;
538
539 finalizeSymtab();
540 return Error::success();
541}
542
543void InstrProfSymtab::finalizeSymtab() {
544 if (Sorted)
545 return;
Andrew Scull0372a572018-11-16 15:47:06 +0000546 llvm::sort(MD5NameMap, less_first());
547 llvm::sort(MD5FuncMap, less_first());
548 llvm::sort(AddrToMD5Map, less_first());
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100549 AddrToMD5Map.erase(std::unique(AddrToMD5Map.begin(), AddrToMD5Map.end()),
550 AddrToMD5Map.end());
551 Sorted = true;
552}
553
554StringRef InstrProfSymtab::getFuncNameOrExternalSymbol(uint64_t FuncMD5Hash) {
555 StringRef ret = getFuncName(FuncMD5Hash);
556 if (ret.empty())
557 return InstrProfSymtab::getExternalSymbol();
558 return ret;
559}
560
561StringRef InstrProfSymtab::getFuncName(uint64_t FuncMD5Hash) {
562 finalizeSymtab();
563 auto Result =
564 std::lower_bound(MD5NameMap.begin(), MD5NameMap.end(), FuncMD5Hash,
565 [](const std::pair<uint64_t, std::string> &LHS,
566 uint64_t RHS) { return LHS.first < RHS; });
567 if (Result != MD5NameMap.end() && Result->first == FuncMD5Hash)
568 return Result->second;
569 return StringRef();
570}
571
572Function* InstrProfSymtab::getFunction(uint64_t FuncMD5Hash) {
573 finalizeSymtab();
574 auto Result =
575 std::lower_bound(MD5FuncMap.begin(), MD5FuncMap.end(), FuncMD5Hash,
576 [](const std::pair<uint64_t, Function*> &LHS,
577 uint64_t RHS) { return LHS.first < RHS; });
578 if (Result != MD5FuncMap.end() && Result->first == FuncMD5Hash)
579 return Result->second;
580 return nullptr;
581}
582
583// See also getPGOFuncName implementation. These two need to be
584// matched.
585StringRef InstrProfSymtab::getOrigFuncName(uint64_t FuncMD5Hash) {
586 StringRef PGOName = getFuncName(FuncMD5Hash);
587 size_t S = PGOName.find_first_of(':');
588 if (S == StringRef::npos)
589 return PGOName;
590 return PGOName.drop_front(S + 1);
591}
592
593struct InstrProfValueSiteRecord {
594 /// Value profiling data pairs at a given value site.
595 std::list<InstrProfValueData> ValueData;
596
597 InstrProfValueSiteRecord() { ValueData.clear(); }
598 template <class InputIterator>
599 InstrProfValueSiteRecord(InputIterator F, InputIterator L)
600 : ValueData(F, L) {}
601
602 /// Sort ValueData ascending by Value
603 void sortByTargetValues() {
604 ValueData.sort(
605 [](const InstrProfValueData &left, const InstrProfValueData &right) {
606 return left.Value < right.Value;
607 });
608 }
609 /// Sort ValueData Descending by Count
610 inline void sortByCount();
611
612 /// Merge data from another InstrProfValueSiteRecord
613 /// Optionally scale merged counts by \p Weight.
614 void merge(InstrProfValueSiteRecord &Input, uint64_t Weight,
615 function_ref<void(instrprof_error)> Warn);
616 /// Scale up value profile data counts.
617 void scale(uint64_t Weight, function_ref<void(instrprof_error)> Warn);
618};
619
620/// Profiling information for a single function.
621struct InstrProfRecord {
622 std::vector<uint64_t> Counts;
623
624 InstrProfRecord() = default;
625 InstrProfRecord(std::vector<uint64_t> Counts) : Counts(std::move(Counts)) {}
626 InstrProfRecord(InstrProfRecord &&) = default;
627 InstrProfRecord(const InstrProfRecord &RHS)
628 : Counts(RHS.Counts),
629 ValueData(RHS.ValueData
630 ? llvm::make_unique<ValueProfData>(*RHS.ValueData)
631 : nullptr) {}
632 InstrProfRecord &operator=(InstrProfRecord &&) = default;
633 InstrProfRecord &operator=(const InstrProfRecord &RHS) {
634 Counts = RHS.Counts;
635 if (!RHS.ValueData) {
636 ValueData = nullptr;
637 return *this;
638 }
639 if (!ValueData)
640 ValueData = llvm::make_unique<ValueProfData>(*RHS.ValueData);
641 else
642 *ValueData = *RHS.ValueData;
643 return *this;
644 }
645
646 /// Return the number of value profile kinds with non-zero number
647 /// of profile sites.
648 inline uint32_t getNumValueKinds() const;
649 /// Return the number of instrumented sites for ValueKind.
650 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
651
652 /// Return the total number of ValueData for ValueKind.
653 inline uint32_t getNumValueData(uint32_t ValueKind) const;
654
655 /// Return the number of value data collected for ValueKind at profiling
656 /// site: Site.
657 inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
658 uint32_t Site) const;
659
660 /// Return the array of profiled values at \p Site. If \p TotalC
661 /// is not null, the total count of all target values at this site
662 /// will be stored in \c *TotalC.
663 inline std::unique_ptr<InstrProfValueData[]>
664 getValueForSite(uint32_t ValueKind, uint32_t Site,
665 uint64_t *TotalC = nullptr) const;
666
667 /// Get the target value/counts of kind \p ValueKind collected at site
668 /// \p Site and store the result in array \p Dest. Return the total
669 /// counts of all target values at this site.
670 inline uint64_t getValueForSite(InstrProfValueData Dest[], uint32_t ValueKind,
671 uint32_t Site) const;
672
673 /// Reserve space for NumValueSites sites.
674 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
675
676 /// Add ValueData for ValueKind at value Site.
677 void addValueData(uint32_t ValueKind, uint32_t Site,
678 InstrProfValueData *VData, uint32_t N,
679 InstrProfSymtab *SymTab);
680
681 /// Merge the counts in \p Other into this one.
682 /// Optionally scale merged counts by \p Weight.
683 void merge(InstrProfRecord &Other, uint64_t Weight,
684 function_ref<void(instrprof_error)> Warn);
685
686 /// Scale up profile counts (including value profile data) by
687 /// \p Weight.
688 void scale(uint64_t Weight, function_ref<void(instrprof_error)> Warn);
689
690 /// Sort value profile data (per site) by count.
691 void sortValueData() {
692 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
693 for (auto &SR : getValueSitesForKind(Kind))
694 SR.sortByCount();
695 }
696
697 /// Clear value data entries and edge counters.
698 void Clear() {
699 Counts.clear();
700 clearValueData();
701 }
702
703 /// Clear value data entries
704 void clearValueData() { ValueData = nullptr; }
705
706private:
707 struct ValueProfData {
708 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
709 std::vector<InstrProfValueSiteRecord> MemOPSizes;
710 };
711 std::unique_ptr<ValueProfData> ValueData;
712
713 MutableArrayRef<InstrProfValueSiteRecord>
714 getValueSitesForKind(uint32_t ValueKind) {
715 // Cast to /add/ const (should be an implicit_cast, ideally, if that's ever
716 // implemented in LLVM) to call the const overload of this function, then
717 // cast away the constness from the result.
718 auto AR = const_cast<const InstrProfRecord *>(this)->getValueSitesForKind(
719 ValueKind);
720 return makeMutableArrayRef(
721 const_cast<InstrProfValueSiteRecord *>(AR.data()), AR.size());
722 }
723 ArrayRef<InstrProfValueSiteRecord>
724 getValueSitesForKind(uint32_t ValueKind) const {
725 if (!ValueData)
726 return None;
727 switch (ValueKind) {
728 case IPVK_IndirectCallTarget:
729 return ValueData->IndirectCallSites;
730 case IPVK_MemOPSize:
731 return ValueData->MemOPSizes;
732 default:
733 llvm_unreachable("Unknown value kind!");
734 }
735 }
736
737 std::vector<InstrProfValueSiteRecord> &
738 getOrCreateValueSitesForKind(uint32_t ValueKind) {
739 if (!ValueData)
740 ValueData = llvm::make_unique<ValueProfData>();
741 switch (ValueKind) {
742 case IPVK_IndirectCallTarget:
743 return ValueData->IndirectCallSites;
744 case IPVK_MemOPSize:
745 return ValueData->MemOPSizes;
746 default:
747 llvm_unreachable("Unknown value kind!");
748 }
749 }
750
751 // Map indirect call target name hash to name string.
752 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
753 InstrProfSymtab *SymTab);
754
755 // Merge Value Profile data from Src record to this record for ValueKind.
756 // Scale merged value counts by \p Weight.
757 void mergeValueProfData(uint32_t ValkeKind, InstrProfRecord &Src,
758 uint64_t Weight,
759 function_ref<void(instrprof_error)> Warn);
760
761 // Scale up value profile data count.
762 void scaleValueProfData(uint32_t ValueKind, uint64_t Weight,
763 function_ref<void(instrprof_error)> Warn);
764};
765
766struct NamedInstrProfRecord : InstrProfRecord {
767 StringRef Name;
768 uint64_t Hash;
769
770 NamedInstrProfRecord() = default;
771 NamedInstrProfRecord(StringRef Name, uint64_t Hash,
772 std::vector<uint64_t> Counts)
773 : InstrProfRecord(std::move(Counts)), Name(Name), Hash(Hash) {}
774};
775
776uint32_t InstrProfRecord::getNumValueKinds() const {
777 uint32_t NumValueKinds = 0;
778 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
779 NumValueKinds += !(getValueSitesForKind(Kind).empty());
780 return NumValueKinds;
781}
782
783uint32_t InstrProfRecord::getNumValueData(uint32_t ValueKind) const {
784 uint32_t N = 0;
785 for (auto &SR : getValueSitesForKind(ValueKind))
786 N += SR.ValueData.size();
787 return N;
788}
789
790uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
791 return getValueSitesForKind(ValueKind).size();
792}
793
794uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
795 uint32_t Site) const {
796 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
797}
798
799std::unique_ptr<InstrProfValueData[]>
800InstrProfRecord::getValueForSite(uint32_t ValueKind, uint32_t Site,
801 uint64_t *TotalC) const {
802 uint64_t Dummy;
803 uint64_t &TotalCount = (TotalC == nullptr ? Dummy : *TotalC);
804 uint32_t N = getNumValueDataForSite(ValueKind, Site);
805 if (N == 0) {
806 TotalCount = 0;
807 return std::unique_ptr<InstrProfValueData[]>(nullptr);
808 }
809
810 auto VD = llvm::make_unique<InstrProfValueData[]>(N);
811 TotalCount = getValueForSite(VD.get(), ValueKind, Site);
812
813 return VD;
814}
815
816uint64_t InstrProfRecord::getValueForSite(InstrProfValueData Dest[],
817 uint32_t ValueKind,
818 uint32_t Site) const {
819 uint32_t I = 0;
820 uint64_t TotalCount = 0;
821 for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
822 Dest[I].Value = V.Value;
823 Dest[I].Count = V.Count;
824 TotalCount = SaturatingAdd(TotalCount, V.Count);
825 I++;
826 }
827 return TotalCount;
828}
829
830void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
831 if (!NumValueSites)
832 return;
833 getOrCreateValueSitesForKind(ValueKind).reserve(NumValueSites);
834}
835
836inline support::endianness getHostEndianness() {
837 return sys::IsLittleEndianHost ? support::little : support::big;
838}
839
840// Include definitions for value profile data
841#define INSTR_PROF_VALUE_PROF_DATA
842#include "llvm/ProfileData/InstrProfData.inc"
843
844void InstrProfValueSiteRecord::sortByCount() {
845 ValueData.sort(
846 [](const InstrProfValueData &left, const InstrProfValueData &right) {
847 return left.Count > right.Count;
848 });
849 // Now truncate
850 size_t max_s = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
851 if (ValueData.size() > max_s)
852 ValueData.resize(max_s);
853}
854
855namespace IndexedInstrProf {
856
857enum class HashT : uint32_t {
858 MD5,
859 Last = MD5
860};
861
862inline uint64_t ComputeHash(HashT Type, StringRef K) {
863 switch (Type) {
864 case HashT::MD5:
865 return MD5Hash(K);
866 }
867 llvm_unreachable("Unhandled hash type");
868}
869
870const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
871
872enum ProfVersion {
873 // Version 1 is the first version. In this version, the value of
874 // a key/value pair can only include profile data of a single function.
875 // Due to this restriction, the number of block counters for a given
876 // function is not recorded but derived from the length of the value.
877 Version1 = 1,
878 // The version 2 format supports recording profile data of multiple
879 // functions which share the same key in one value field. To support this,
880 // the number block counters is recorded as an uint64_t field right after the
881 // function structural hash.
882 Version2 = 2,
883 // Version 3 supports value profile data. The value profile data is expected
884 // to follow the block counter profile data.
885 Version3 = 3,
886 // In this version, profile summary data \c IndexedInstrProf::Summary is
887 // stored after the profile header.
888 Version4 = 4,
889 // In this version, the frontend PGO stable hash algorithm defaults to V2.
890 Version5 = 5,
891 // The current version is 5.
892 CurrentVersion = INSTR_PROF_INDEX_VERSION
893};
894const uint64_t Version = ProfVersion::CurrentVersion;
895
896const HashT HashType = HashT::MD5;
897
898inline uint64_t ComputeHash(StringRef K) { return ComputeHash(HashType, K); }
899
900// This structure defines the file header of the LLVM profile
901// data file in indexed-format.
902struct Header {
903 uint64_t Magic;
904 uint64_t Version;
905 uint64_t Unused; // Becomes unused since version 4
906 uint64_t HashType;
907 uint64_t HashOffset;
908};
909
910// Profile summary data recorded in the profile data file in indexed
911// format. It is introduced in version 4. The summary data follows
912// right after the profile file header.
913struct Summary {
914 struct Entry {
915 uint64_t Cutoff; ///< The required percentile of total execution count.
916 uint64_t
917 MinBlockCount; ///< The minimum execution count for this percentile.
918 uint64_t NumBlocks; ///< Number of blocks >= the minumum execution count.
919 };
920 // The field kind enumerator to assigned value mapping should remain
921 // unchanged when a new kind is added or an old kind gets deleted in
922 // the future.
923 enum SummaryFieldKind {
924 /// The total number of functions instrumented.
925 TotalNumFunctions = 0,
926 /// Total number of instrumented blocks/edges.
927 TotalNumBlocks = 1,
928 /// The maximal execution count among all functions.
929 /// This field does not exist for profile data from IR based
930 /// instrumentation.
931 MaxFunctionCount = 2,
932 /// Max block count of the program.
933 MaxBlockCount = 3,
934 /// Max internal block count of the program (excluding entry blocks).
935 MaxInternalBlockCount = 4,
936 /// The sum of all instrumented block counts.
937 TotalBlockCount = 5,
938 NumKinds = TotalBlockCount + 1
939 };
940
941 // The number of summmary fields following the summary header.
942 uint64_t NumSummaryFields;
943 // The number of Cutoff Entries (Summary::Entry) following summary fields.
944 uint64_t NumCutoffEntries;
945
946 Summary() = delete;
947 Summary(uint32_t Size) { memset(this, 0, Size); }
948
949 void operator delete(void *ptr) { ::operator delete(ptr); }
950
951 static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries) {
952 return sizeof(Summary) + NumCutoffEntries * sizeof(Entry) +
953 NumSumFields * sizeof(uint64_t);
954 }
955
956 const uint64_t *getSummaryDataBase() const {
957 return reinterpret_cast<const uint64_t *>(this + 1);
958 }
959
960 uint64_t *getSummaryDataBase() {
961 return reinterpret_cast<uint64_t *>(this + 1);
962 }
963
964 const Entry *getCutoffEntryBase() const {
965 return reinterpret_cast<const Entry *>(
966 &getSummaryDataBase()[NumSummaryFields]);
967 }
968
969 Entry *getCutoffEntryBase() {
970 return reinterpret_cast<Entry *>(&getSummaryDataBase()[NumSummaryFields]);
971 }
972
973 uint64_t get(SummaryFieldKind K) const {
974 return getSummaryDataBase()[K];
975 }
976
977 void set(SummaryFieldKind K, uint64_t V) {
978 getSummaryDataBase()[K] = V;
979 }
980
981 const Entry &getEntry(uint32_t I) const { return getCutoffEntryBase()[I]; }
982
983 void setEntry(uint32_t I, const ProfileSummaryEntry &E) {
984 Entry &ER = getCutoffEntryBase()[I];
985 ER.Cutoff = E.Cutoff;
986 ER.MinBlockCount = E.MinCount;
987 ER.NumBlocks = E.NumCounts;
988 }
989};
990
991inline std::unique_ptr<Summary> allocSummary(uint32_t TotalSize) {
992 return std::unique_ptr<Summary>(new (::operator new(TotalSize))
993 Summary(TotalSize));
994}
995
996} // end namespace IndexedInstrProf
997
998namespace RawInstrProf {
999
1000// Version 1: First version
1001// Version 2: Added value profile data section. Per-function control data
1002// struct has more fields to describe value profile information.
1003// Version 3: Compressed name section support. Function PGO name reference
1004// from control data struct is changed from raw pointer to Name's MD5 value.
1005// Version 4: ValueDataBegin and ValueDataSizes fields are removed from the
1006// raw header.
1007const uint64_t Version = INSTR_PROF_RAW_VERSION;
1008
1009template <class IntPtrT> inline uint64_t getMagic();
1010template <> inline uint64_t getMagic<uint64_t>() {
1011 return INSTR_PROF_RAW_MAGIC_64;
1012}
1013
1014template <> inline uint64_t getMagic<uint32_t>() {
1015 return INSTR_PROF_RAW_MAGIC_32;
1016}
1017
1018// Per-function profile data header/control structure.
1019// The definition should match the structure defined in
1020// compiler-rt/lib/profile/InstrProfiling.h.
1021// It should also match the synthesized type in
1022// Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001023template <class IntPtrT> struct alignas(8) ProfileData {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001024 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
1025 #include "llvm/ProfileData/InstrProfData.inc"
1026};
1027
1028// File header structure of the LLVM profile data in raw format.
1029// The definition should match the header referenced in
1030// compiler-rt/lib/profile/InstrProfilingFile.c and
1031// InstrProfilingBuffer.c.
1032struct Header {
1033#define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
1034#include "llvm/ProfileData/InstrProfData.inc"
1035};
1036
1037} // end namespace RawInstrProf
1038
1039// Parse MemOP Size range option.
1040void getMemOPSizeRangeFromOption(StringRef Str, int64_t &RangeStart,
1041 int64_t &RangeLast);
1042
Andrew Walbran16937d02019-10-22 13:54:20 +01001043// Create the variable for the profile file name.
1044void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput);
1045
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001046} // end namespace llvm
1047
1048#endif // LLVM_PROFILEDATA_INSTRPROF_H