1 //===- InstrProf.h - Instrumented profiling format support ------*- C++ -*-===//
2 //
3 // 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
6 //
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/BitmaskEnum.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/IntervalMap.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSet.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/ProfileSummary.h"
27 #include "llvm/ProfileData/InstrProfData.inc"
28 #include "llvm/Support/BalancedPartitioning.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/Error.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MD5.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/TargetParser/Host.h"
37 #include "llvm/TargetParser/Triple.h"
38 #include <algorithm>
39 #include <cassert>
40 #include <cstddef>
41 #include <cstdint>
42 #include <cstring>
43 #include <list>
44 #include <memory>
45 #include <string>
46 #include <system_error>
47 #include <utility>
48 #include <vector>
49
50 namespace llvm {
51
52 class Function;
53 class GlobalVariable;
54 struct InstrProfRecord;
55 class InstrProfSymtab;
56 class Instruction;
57 class MDNode;
58 class Module;
59
60 enum InstrProfSectKind {
61 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) Kind,
62 #include "llvm/ProfileData/InstrProfData.inc"
63 };
64
65 /// Return the max count value. We reserver a few large values for special use.
getInstrMaxCountValue()66 inline uint64_t getInstrMaxCountValue() {
67 return std::numeric_limits<uint64_t>::max() - 2;
68 }
69
70 /// Return the name of the profile section corresponding to \p IPSK.
71 ///
72 /// The name of the section depends on the object format type \p OF. If
73 /// \p AddSegmentInfo is true, a segment prefix and additional linker hints may
74 /// be added to the section name (this is the default).
75 std::string getInstrProfSectionName(InstrProfSectKind IPSK,
76 Triple::ObjectFormatType OF,
77 bool AddSegmentInfo = true);
78
79 /// Return the name profile runtime entry point to do value profiling
80 /// for a given site.
getInstrProfValueProfFuncName()81 inline StringRef getInstrProfValueProfFuncName() {
82 return INSTR_PROF_VALUE_PROF_FUNC_STR;
83 }
84
85 /// Return the name profile runtime entry point to do memop size value
86 /// profiling.
getInstrProfValueProfMemOpFuncName()87 inline StringRef getInstrProfValueProfMemOpFuncName() {
88 return INSTR_PROF_VALUE_PROF_MEMOP_FUNC_STR;
89 }
90
91 /// Return the name prefix of variables containing instrumented function names.
getInstrProfNameVarPrefix()92 inline StringRef getInstrProfNameVarPrefix() { return "__profn_"; }
93
94 /// Return the name prefix of variables containing virtual table profile data.
getInstrProfVTableVarPrefix()95 inline StringRef getInstrProfVTableVarPrefix() { return "__profvt_"; }
96
97 /// Return the name prefix of variables containing per-function control data.
getInstrProfDataVarPrefix()98 inline StringRef getInstrProfDataVarPrefix() { return "__profd_"; }
99
100 /// Return the name prefix of profile counter variables.
getInstrProfCountersVarPrefix()101 inline StringRef getInstrProfCountersVarPrefix() { return "__profc_"; }
102
103 /// Return the name prefix of profile bitmap variables.
getInstrProfBitmapVarPrefix()104 inline StringRef getInstrProfBitmapVarPrefix() { return "__profbm_"; }
105
106 /// Return the name prefix of value profile variables.
getInstrProfValuesVarPrefix()107 inline StringRef getInstrProfValuesVarPrefix() { return "__profvp_"; }
108
109 /// Return the name of value profile node array variables:
getInstrProfVNodesVarName()110 inline StringRef getInstrProfVNodesVarName() { return "__llvm_prf_vnodes"; }
111
112 /// Return the name of the variable holding the strings (possibly compressed)
113 /// of all function's PGO names.
getInstrProfNamesVarName()114 inline StringRef getInstrProfNamesVarName() { return "__llvm_prf_nm"; }
115
getInstrProfVTableNamesVarName()116 inline StringRef getInstrProfVTableNamesVarName() { return "__llvm_prf_vnm"; }
117
118 /// Return the name of a covarage mapping variable (internal linkage)
119 /// for each instrumented source module. Such variables are allocated
120 /// in the __llvm_covmap section.
getCoverageMappingVarName()121 inline StringRef getCoverageMappingVarName() {
122 return "__llvm_coverage_mapping";
123 }
124
125 /// Return the name of the internal variable recording the array
126 /// of PGO name vars referenced by the coverage mapping. The owning
127 /// functions of those names are not emitted by FE (e.g, unused inline
128 /// functions.)
getCoverageUnusedNamesVarName()129 inline StringRef getCoverageUnusedNamesVarName() {
130 return "__llvm_coverage_names";
131 }
132
133 /// Return the name of function that registers all the per-function control
134 /// data at program startup time by calling __llvm_register_function. This
135 /// function has internal linkage and is called by __llvm_profile_init
136 /// runtime method. This function is not generated for these platforms:
137 /// Darwin, Linux, and FreeBSD.
getInstrProfRegFuncsName()138 inline StringRef getInstrProfRegFuncsName() {
139 return "__llvm_profile_register_functions";
140 }
141
142 /// Return the name of the runtime interface that registers per-function control
143 /// data for one instrumented function.
getInstrProfRegFuncName()144 inline StringRef getInstrProfRegFuncName() {
145 return "__llvm_profile_register_function";
146 }
147
148 /// Return the name of the runtime interface that registers the PGO name
149 /// strings.
getInstrProfNamesRegFuncName()150 inline StringRef getInstrProfNamesRegFuncName() {
151 return "__llvm_profile_register_names_function";
152 }
153
154 /// Return the name of the runtime initialization method that is generated by
155 /// the compiler. The function calls __llvm_profile_register_functions and
156 /// __llvm_profile_override_default_filename functions if needed. This function
157 /// has internal linkage and invoked at startup time via init_array.
getInstrProfInitFuncName()158 inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
159
160 /// Return the name of the hook variable defined in profile runtime library.
161 /// A reference to the variable causes the linker to link in the runtime
162 /// initialization module (which defines the hook variable).
getInstrProfRuntimeHookVarName()163 inline StringRef getInstrProfRuntimeHookVarName() {
164 return INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_RUNTIME_VAR);
165 }
166
167 /// Return the name of the compiler generated function that references the
168 /// runtime hook variable. The function is a weak global.
getInstrProfRuntimeHookVarUseFuncName()169 inline StringRef getInstrProfRuntimeHookVarUseFuncName() {
170 return "__llvm_profile_runtime_user";
171 }
172
getInstrProfCounterBiasVarName()173 inline StringRef getInstrProfCounterBiasVarName() {
174 return INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_COUNTER_BIAS_VAR);
175 }
176
177 /// Return the marker used to separate PGO names during serialization.
getInstrProfNameSeparator()178 inline StringRef getInstrProfNameSeparator() { return "\01"; }
179
180 /// Please use getIRPGOFuncName for LLVM IR instrumentation. This function is
181 /// for front-end (Clang, etc) instrumentation.
182 /// Return the modified name for function \c F suitable to be
183 /// used the key for profile lookup. Variable \c InLTO indicates if this
184 /// is called in LTO optimization passes.
185 std::string getPGOFuncName(const Function &F, bool InLTO = false,
186 uint64_t Version = INSTR_PROF_INDEX_VERSION);
187
188 /// Return the modified name for a function suitable to be
189 /// used the key for profile lookup. The function's original
190 /// name is \c RawFuncName and has linkage of type \c Linkage.
191 /// The function is defined in module \c FileName.
192 std::string getPGOFuncName(StringRef RawFuncName,
193 GlobalValue::LinkageTypes Linkage,
194 StringRef FileName,
195 uint64_t Version = INSTR_PROF_INDEX_VERSION);
196
197 /// \return the modified name for function \c F suitable to be
198 /// used as the key for IRPGO profile lookup. \c InLTO indicates if this is
199 /// called from LTO optimization passes.
200 std::string getIRPGOFuncName(const Function &F, bool InLTO = false);
201
202 /// \return the filename and the function name parsed from the output of
203 /// \c getIRPGOFuncName()
204 std::pair<StringRef, StringRef> getParsedIRPGOName(StringRef IRPGOName);
205
206 /// Return the name of the global variable used to store a function
207 /// name in PGO instrumentation. \c FuncName is the IRPGO function name
208 /// (returned by \c getIRPGOFuncName) for LLVM IR instrumentation and PGO
209 /// function name (returned by \c getPGOFuncName) for front-end instrumentation.
210 std::string getPGOFuncNameVarName(StringRef FuncName,
211 GlobalValue::LinkageTypes Linkage);
212
213 /// Create and return the global variable for function name used in PGO
214 /// instrumentation. \c FuncName is the IRPGO function name (returned by
215 /// \c getIRPGOFuncName) for LLVM IR instrumentation and PGO function name
216 /// (returned by \c getPGOFuncName) for front-end instrumentation.
217 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName);
218
219 /// Create and return the global variable for function name used in PGO
220 /// instrumentation. \c FuncName is the IRPGO function name (returned by
221 /// \c getIRPGOFuncName) for LLVM IR instrumentation and PGO function name
222 /// (returned by \c getPGOFuncName) for front-end instrumentation.
223 GlobalVariable *createPGOFuncNameVar(Module &M,
224 GlobalValue::LinkageTypes Linkage,
225 StringRef PGOFuncName);
226
227 /// Return the initializer in string of the PGO name var \c NameVar.
228 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar);
229
230 /// Given a PGO function name, remove the filename prefix and return
231 /// the original (static) function name.
232 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName,
233 StringRef FileName = "<unknown>");
234
235 /// Given a vector of strings (names of global objects like functions or,
236 /// virtual tables) \c NameStrs, the method generates a combined string \c
237 /// Result that is ready to be serialized. The \c Result string is comprised of
238 /// three fields: The first field is the length of the uncompressed strings, and
239 /// the the second field is the length of the zlib-compressed string. Both
240 /// fields are encoded in ULEB128. If \c doCompress is false, the
241 /// third field is the uncompressed strings; otherwise it is the
242 /// compressed string. When the string compression is off, the
243 /// second field will have value zero.
244 Error collectGlobalObjectNameStrings(ArrayRef<std::string> NameStrs,
245 bool doCompression, std::string &Result);
246
247 /// Produce \c Result string with the same format described above. The input
248 /// is vector of PGO function name variables that are referenced.
249 /// The global variable element in 'NameVars' is a string containing the pgo
250 /// name of a function. See `createPGOFuncNameVar` that creates these global
251 /// variables.
252 Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
253 std::string &Result, bool doCompression = true);
254
255 Error collectVTableStrings(ArrayRef<GlobalVariable *> VTables,
256 std::string &Result, bool doCompression);
257
258 /// Check if INSTR_PROF_RAW_VERSION_VAR is defined. This global is only being
259 /// set in IR PGO compilation.
260 bool isIRPGOFlagSet(const Module *M);
261
262 /// Check if we can safely rename this Comdat function. Instances of the same
263 /// comdat function may have different control flows thus can not share the
264 /// same counter variable.
265 bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken = false);
266
267 enum InstrProfValueKind : uint32_t {
268 #define VALUE_PROF_KIND(Enumerator, Value, Descr) Enumerator = Value,
269 #include "llvm/ProfileData/InstrProfData.inc"
270 };
271
272 /// Get the value profile data for value site \p SiteIdx from \p InstrProfR
273 /// and annotate the instruction \p Inst with the value profile meta data.
274 /// Annotate up to \p MaxMDCount (default 3) number of records per value site.
275 void annotateValueSite(Module &M, Instruction &Inst,
276 const InstrProfRecord &InstrProfR,
277 InstrProfValueKind ValueKind, uint32_t SiteIndx,
278 uint32_t MaxMDCount = 3);
279
280 /// Same as the above interface but using an ArrayRef, as well as \p Sum.
281 /// This function will not annotate !prof metadata on the instruction if the
282 /// referenced array is empty.
283 void annotateValueSite(Module &M, Instruction &Inst,
284 ArrayRef<InstrProfValueData> VDs, uint64_t Sum,
285 InstrProfValueKind ValueKind, uint32_t MaxMDCount);
286
287 /// Extract the value profile data from \p Inst which is annotated with
288 /// value profile meta data. Return false if there is no value data annotated,
289 /// otherwise return true.
290 bool getValueProfDataFromInst(const Instruction &Inst,
291 InstrProfValueKind ValueKind,
292 uint32_t MaxNumValueData,
293 InstrProfValueData ValueData[],
294 uint32_t &ActualNumValueData, uint64_t &TotalC,
295 bool GetNoICPValue = false);
296
297 /// Extract the value profile data from \p Inst and returns them if \p Inst is
298 /// annotated with value profile data. Returns nullptr otherwise. It's similar
299 /// to `getValueProfDataFromInst` above except that an array is allocated only
300 /// after a preliminary checking that the value profiles of kind `ValueKind`
301 /// exist.
302 std::unique_ptr<InstrProfValueData[]>
303 getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind,
304 uint32_t MaxNumValueData, uint32_t &ActualNumValueData,
305 uint64_t &TotalC, bool GetNoICPValue = false);
306
getPGOFuncNameMetadataName()307 inline StringRef getPGOFuncNameMetadataName() { return "PGOFuncName"; }
308
309 /// Return the PGOFuncName meta data associated with a function.
310 MDNode *getPGOFuncNameMetadata(const Function &F);
311
312 std::string getPGOName(const GlobalVariable &V, bool InLTO = false);
313
314 /// Create the PGOFuncName meta data if PGOFuncName is different from
315 /// function's raw name. This should only apply to internal linkage functions
316 /// declared by users only.
317 void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName);
318
319 /// Check if we can use Comdat for profile variables. This will eliminate
320 /// the duplicated profile variables for Comdat functions.
321 bool needsComdatForCounter(const GlobalObject &GV, const Module &M);
322
323 /// An enum describing the attributes of an instrumented profile.
324 enum class InstrProfKind {
325 Unknown = 0x0,
326 // A frontend clang profile, incompatible with other attrs.
327 FrontendInstrumentation = 0x1,
328 // An IR-level profile (default when -fprofile-generate is used).
329 IRInstrumentation = 0x2,
330 // A profile with entry basic block instrumentation.
331 FunctionEntryInstrumentation = 0x4,
332 // A context sensitive IR-level profile.
333 ContextSensitive = 0x8,
334 // Use single byte probes for coverage.
335 SingleByteCoverage = 0x10,
336 // Only instrument the function entry basic block.
337 FunctionEntryOnly = 0x20,
338 // A memory profile collected using -fprofile=memory.
339 MemProf = 0x40,
340 // A temporal profile.
341 TemporalProfile = 0x80,
342 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/TemporalProfile)
343 };
344
345 const std::error_category &instrprof_category();
346
347 enum class instrprof_error {
348 success = 0,
349 eof,
350 unrecognized_format,
351 bad_magic,
352 bad_header,
353 unsupported_version,
354 unsupported_hash_type,
355 too_large,
356 truncated,
357 malformed,
358 missing_correlation_info,
359 unexpected_correlation_info,
360 unable_to_correlate_profile,
361 unknown_function,
362 invalid_prof,
363 hash_mismatch,
364 count_mismatch,
365 bitmap_mismatch,
366 counter_overflow,
367 value_site_count_mismatch,
368 compress_failed,
369 uncompress_failed,
370 empty_raw_profile,
371 zlib_unavailable,
372 raw_profile_version_mismatch,
373 counter_value_too_large,
374 };
375
376 /// An ordered list of functions identified by their NameRef found in
377 /// INSTR_PROF_DATA
378 struct TemporalProfTraceTy {
379 std::vector<uint64_t> FunctionNameRefs;
380 uint64_t Weight;
381 TemporalProfTraceTy(std::initializer_list<uint64_t> Trace = {},
382 uint64_t Weight = 1)
FunctionNameRefsTemporalProfTraceTy383 : FunctionNameRefs(Trace), Weight(Weight) {}
384
385 /// Use a set of temporal profile traces to create a list of balanced
386 /// partitioning function nodes used by BalancedPartitioning to generate a
387 /// function order that reduces page faults during startup
388 static std::vector<BPFunctionNode>
389 createBPFunctionNodes(ArrayRef<TemporalProfTraceTy> Traces);
390 };
391
make_error_code(instrprof_error E)392 inline std::error_code make_error_code(instrprof_error E) {
393 return std::error_code(static_cast<int>(E), instrprof_category());
394 }
395
396 class InstrProfError : public ErrorInfo<InstrProfError> {
397 public:
398 InstrProfError(instrprof_error Err, const Twine &ErrStr = Twine())
Err(Err)399 : Err(Err), Msg(ErrStr.str()) {
400 assert(Err != instrprof_error::success && "Not an error");
401 }
402
403 std::string message() const override;
404
log(raw_ostream & OS)405 void log(raw_ostream &OS) const override { OS << message(); }
406
convertToErrorCode()407 std::error_code convertToErrorCode() const override {
408 return make_error_code(Err);
409 }
410
get()411 instrprof_error get() const { return Err; }
getMessage()412 const std::string &getMessage() const { return Msg; }
413
414 /// Consume an Error and return the raw enum value contained within it, and
415 /// the optional error message. The Error must either be a success value, or
416 /// contain a single InstrProfError.
take(Error E)417 static std::pair<instrprof_error, std::string> take(Error E) {
418 auto Err = instrprof_error::success;
419 std::string Msg = "";
420 handleAllErrors(std::move(E), [&Err, &Msg](const InstrProfError &IPE) {
421 assert(Err == instrprof_error::success && "Multiple errors encountered");
422 Err = IPE.get();
423 Msg = IPE.getMessage();
424 });
425 return {Err, Msg};
426 }
427
428 static char ID;
429
430 private:
431 instrprof_error Err;
432 std::string Msg;
433 };
434
435 namespace object {
436
437 class SectionRef;
438
439 } // end namespace object
440
441 namespace IndexedInstrProf {
442
443 uint64_t ComputeHash(StringRef K);
444
445 } // end namespace IndexedInstrProf
446
447 /// A symbol table used for function [IR]PGO name look-up with keys
448 /// (such as pointers, md5hash values) to the function. A function's
449 /// [IR]PGO name or name's md5hash are used in retrieving the profile
450 /// data of the function. See \c getIRPGOFuncName() and \c getPGOFuncName
451 /// methods for details how [IR]PGO name is formed.
452 class InstrProfSymtab {
453 public:
454 using AddrHashMap = std::vector<std::pair<uint64_t, uint64_t>>;
455
456 private:
457 using AddrIntervalMap =
458 IntervalMap<uint64_t, uint64_t, 4, IntervalMapHalfOpenInfo<uint64_t>>;
459 StringRef Data;
460 uint64_t Address = 0;
461 // Unique name strings. Used to ensure entries in MD5NameMap (a vector that's
462 // going to be sorted) has unique MD5 keys in the first place.
463 StringSet<> NameTab;
464 // Records the unique virtual table names. This is used by InstrProfWriter to
465 // write out an on-disk chained hash table of virtual table names.
466 // InstrProfWriter stores per function profile data (keyed by function names)
467 // so it doesn't use a StringSet for function names.
468 StringSet<> VTableNames;
469 // A map from MD5 keys to function name strings.
470 std::vector<std::pair<uint64_t, StringRef>> MD5NameMap;
471 // A map from MD5 keys to function define. We only populate this map
472 // when build the Symtab from a Module.
473 std::vector<std::pair<uint64_t, Function *>> MD5FuncMap;
474 // A map from MD5 to the global variable. This map is only populated when
475 // building the symtab from a module. Use separate container instances for
476 // `MD5FuncMap` and `MD5VTableMap`.
477 // TODO: Unify the container type and the lambda function 'mapName' inside
478 // add{Func,VTable}WithName.
479 DenseMap<uint64_t, GlobalVariable *> MD5VTableMap;
480 // A map from function runtime address to function name MD5 hash.
481 // This map is only populated and used by raw instr profile reader.
482 AddrHashMap AddrToMD5Map;
483
484 AddrIntervalMap::Allocator VTableAddrMapAllocator;
485 // This map is only populated and used by raw instr profile reader.
486 AddrIntervalMap VTableAddrMap;
487 bool Sorted = false;
488
getExternalSymbol()489 static StringRef getExternalSymbol() { return "** External Symbol **"; }
490
491 // Returns the canonial name of the given PGOName. In a canonical name, all
492 // suffixes that begins with "." except ".__uniq." are stripped.
493 // FIXME: Unify this with `FunctionSamples::getCanonicalFnName`.
494 static StringRef getCanonicalName(StringRef PGOName);
495
496 // Add the function into the symbol table, by creating the following
497 // map entries:
498 // name-set = {PGOFuncName} union {getCanonicalName(PGOFuncName)}
499 // - In MD5NameMap: <MD5Hash(name), name> for name in name-set
500 // - In MD5FuncMap: <MD5Hash(name), &F> for name in name-set
501 Error addFuncWithName(Function &F, StringRef PGOFuncName);
502
503 // Add the vtable into the symbol table, by creating the following
504 // map entries:
505 // name-set = {PGOName} union {getCanonicalName(PGOName)}
506 // - In MD5NameMap: <MD5Hash(name), name> for name in name-set
507 // - In MD5VTableMap: <MD5Hash(name), name> for name in name-set
508 Error addVTableWithName(GlobalVariable &V, StringRef PGOVTableName);
509
510 // If the symtab is created by a series of calls to \c addFuncName, \c
511 // finalizeSymtab needs to be called before looking up function names.
512 // This is required because the underlying map is a vector (for space
513 // efficiency) which needs to be sorted.
514 inline void finalizeSymtab();
515
516 public:
InstrProfSymtab()517 InstrProfSymtab() : VTableAddrMap(VTableAddrMapAllocator) {}
518
519 // Not copyable or movable.
520 // Consider std::unique_ptr for move.
521 InstrProfSymtab(const InstrProfSymtab &) = delete;
522 InstrProfSymtab &operator=(const InstrProfSymtab &) = delete;
523 InstrProfSymtab(InstrProfSymtab &&) = delete;
524 InstrProfSymtab &operator=(InstrProfSymtab &&) = delete;
525
526 /// Create InstrProfSymtab from an object file section which
527 /// contains function PGO names. When section may contain raw
528 /// string data or string data in compressed form. This method
529 /// only initialize the symtab with reference to the data and
530 /// the section base address. The decompression will be delayed
531 /// until before it is used. See also \c create(StringRef) method.
532 Error create(object::SectionRef &Section);
533
534 /// \c NameStrings is a string composed of one of more sub-strings
535 /// encoded in the format described in \c collectPGOFuncNameStrings.
536 /// This method is a wrapper to \c readAndDecodeStrings method.
537 Error create(StringRef NameStrings);
538
539 /// Initialize symtab states with function names and vtable names. \c
540 /// FuncNameStrings is a string composed of one or more encoded function name
541 /// strings, and \c VTableNameStrings composes of one or more encoded vtable
542 /// names. This interface is solely used by raw profile reader.
543 Error create(StringRef FuncNameStrings, StringRef VTableNameStrings);
544
545 /// Initialize 'this' with the set of vtable names encoded in
546 /// \c CompressedVTableNames.
547 Error initVTableNamesFromCompressedStrings(StringRef CompressedVTableNames);
548
549 /// This interface is used by reader of CoverageMapping test
550 /// format.
551 inline Error create(StringRef D, uint64_t BaseAddr);
552
553 /// A wrapper interface to populate the PGO symtab with functions
554 /// decls from module \c M. This interface is used by transformation
555 /// passes such as indirect function call promotion. Variable \c InLTO
556 /// indicates if this is called from LTO optimization passes.
557 Error create(Module &M, bool InLTO = false);
558
559 /// Create InstrProfSymtab from a set of names iteratable from
560 /// \p IterRange. This interface is used by IndexedProfReader.
561 template <typename NameIterRange>
562 Error create(const NameIterRange &IterRange);
563
564 /// Create InstrProfSymtab from a set of function names and vtable
565 /// names iteratable from \p IterRange. This interface is used by
566 /// IndexedProfReader.
567 template <typename FuncNameIterRange, typename VTableNameIterRange>
568 Error create(const FuncNameIterRange &FuncIterRange,
569 const VTableNameIterRange &VTableIterRange);
570
571 // Map the MD5 of the symbol name to the name.
addSymbolName(StringRef SymbolName)572 Error addSymbolName(StringRef SymbolName) {
573 if (SymbolName.empty())
574 return make_error<InstrProfError>(instrprof_error::malformed,
575 "symbol name is empty");
576
577 // Insert into NameTab so that MD5NameMap (a vector that will be sorted)
578 // won't have duplicated entries in the first place.
579 auto Ins = NameTab.insert(SymbolName);
580 if (Ins.second) {
581 MD5NameMap.push_back(std::make_pair(
582 IndexedInstrProf::ComputeHash(SymbolName), Ins.first->getKey()));
583 Sorted = false;
584 }
585 return Error::success();
586 }
587
588 /// The method name is kept since there are many callers.
589 /// It just forwards to 'addSymbolName'.
addFuncName(StringRef FuncName)590 Error addFuncName(StringRef FuncName) { return addSymbolName(FuncName); }
591
592 /// Adds VTableName as a known symbol, and inserts it to a map that
593 /// tracks all vtable names.
addVTableName(StringRef VTableName)594 Error addVTableName(StringRef VTableName) {
595 if (Error E = addSymbolName(VTableName))
596 return E;
597
598 // Record VTableName. InstrProfWriter uses this set. The comment around
599 // class member explains why.
600 VTableNames.insert(VTableName);
601 return Error::success();
602 }
603
getVTableNames()604 const StringSet<> &getVTableNames() const { return VTableNames; }
605
606 /// Map a function address to its name's MD5 hash. This interface
607 /// is only used by the raw profiler reader.
mapAddress(uint64_t Addr,uint64_t MD5Val)608 void mapAddress(uint64_t Addr, uint64_t MD5Val) {
609 AddrToMD5Map.push_back(std::make_pair(Addr, MD5Val));
610 }
611
612 /// Map the address range (i.e., [start_address, end_address)) of a variable
613 /// to its names' MD5 hash. This interface is only used by the raw profile
614 /// reader.
mapVTableAddress(uint64_t StartAddr,uint64_t EndAddr,uint64_t MD5Val)615 void mapVTableAddress(uint64_t StartAddr, uint64_t EndAddr, uint64_t MD5Val) {
616 VTableAddrMap.insert(StartAddr, EndAddr, MD5Val);
617 }
618
619 /// Return a function's hash, or 0, if the function isn't in this SymTab.
620 uint64_t getFunctionHashFromAddress(uint64_t Address);
621
622 /// Return a vtable's hash, or 0 if the vtable doesn't exist in this SymTab.
623 uint64_t getVTableHashFromAddress(uint64_t Address);
624
625 /// Return function's PGO name from the function name's symbol
626 /// address in the object file. If an error occurs, return
627 /// an empty string.
628 StringRef getFuncName(uint64_t FuncNameAddress, size_t NameSize);
629
630 /// Return name of functions or global variables from the name's md5 hash
631 /// value. If not found, return an empty string.
632 inline StringRef getFuncOrVarName(uint64_t ValMD5Hash);
633
634 /// Just like getFuncOrVarName, except that it will return literal string
635 /// 'External Symbol' if the function or global variable is external to
636 /// this symbol table.
637 inline StringRef getFuncOrVarNameIfDefined(uint64_t ValMD5Hash);
638
639 /// True if Symbol is the value used to represent external symbols.
isExternalSymbol(const StringRef & Symbol)640 static bool isExternalSymbol(const StringRef &Symbol) {
641 return Symbol == InstrProfSymtab::getExternalSymbol();
642 }
643
644 /// Return function from the name's md5 hash. Return nullptr if not found.
645 inline Function *getFunction(uint64_t FuncMD5Hash);
646
647 /// Return the global variable corresponding to md5 hash. Return nullptr if
648 /// not found.
649 inline GlobalVariable *getGlobalVariable(uint64_t MD5Hash);
650
651 /// Return the name section data.
getNameData()652 inline StringRef getNameData() const { return Data; }
653
654 /// Dump the symbols in this table.
655 void dumpNames(raw_ostream &OS) const;
656 };
657
create(StringRef D,uint64_t BaseAddr)658 Error InstrProfSymtab::create(StringRef D, uint64_t BaseAddr) {
659 Data = D;
660 Address = BaseAddr;
661 return Error::success();
662 }
663
664 template <typename NameIterRange>
create(const NameIterRange & IterRange)665 Error InstrProfSymtab::create(const NameIterRange &IterRange) {
666 for (auto Name : IterRange)
667 if (Error E = addFuncName(Name))
668 return E;
669
670 finalizeSymtab();
671 return Error::success();
672 }
673
674 template <typename FuncNameIterRange, typename VTableNameIterRange>
create(const FuncNameIterRange & FuncIterRange,const VTableNameIterRange & VTableIterRange)675 Error InstrProfSymtab::create(const FuncNameIterRange &FuncIterRange,
676 const VTableNameIterRange &VTableIterRange) {
677 // Iterate elements by StringRef rather than by const reference.
678 // StringRef is small enough, so the loop is efficient whether
679 // element in the range is std::string or StringRef.
680 for (StringRef Name : FuncIterRange)
681 if (Error E = addFuncName(Name))
682 return E;
683
684 for (StringRef VTableName : VTableIterRange)
685 if (Error E = addVTableName(VTableName))
686 return E;
687
688 finalizeSymtab();
689 return Error::success();
690 }
691
finalizeSymtab()692 void InstrProfSymtab::finalizeSymtab() {
693 if (Sorted)
694 return;
695 llvm::sort(MD5NameMap, less_first());
696 llvm::sort(MD5FuncMap, less_first());
697 llvm::sort(AddrToMD5Map, less_first());
698 AddrToMD5Map.erase(std::unique(AddrToMD5Map.begin(), AddrToMD5Map.end()),
699 AddrToMD5Map.end());
700 Sorted = true;
701 }
702
getFuncOrVarNameIfDefined(uint64_t MD5Hash)703 StringRef InstrProfSymtab::getFuncOrVarNameIfDefined(uint64_t MD5Hash) {
704 StringRef ret = getFuncOrVarName(MD5Hash);
705 if (ret.empty())
706 return InstrProfSymtab::getExternalSymbol();
707 return ret;
708 }
709
getFuncOrVarName(uint64_t MD5Hash)710 StringRef InstrProfSymtab::getFuncOrVarName(uint64_t MD5Hash) {
711 finalizeSymtab();
712 auto Result = llvm::lower_bound(MD5NameMap, MD5Hash,
713 [](const std::pair<uint64_t, StringRef> &LHS,
714 uint64_t RHS) { return LHS.first < RHS; });
715 if (Result != MD5NameMap.end() && Result->first == MD5Hash)
716 return Result->second;
717 return StringRef();
718 }
719
getFunction(uint64_t FuncMD5Hash)720 Function* InstrProfSymtab::getFunction(uint64_t FuncMD5Hash) {
721 finalizeSymtab();
722 auto Result = llvm::lower_bound(MD5FuncMap, FuncMD5Hash,
723 [](const std::pair<uint64_t, Function *> &LHS,
724 uint64_t RHS) { return LHS.first < RHS; });
725 if (Result != MD5FuncMap.end() && Result->first == FuncMD5Hash)
726 return Result->second;
727 return nullptr;
728 }
729
getGlobalVariable(uint64_t MD5Hash)730 GlobalVariable *InstrProfSymtab::getGlobalVariable(uint64_t MD5Hash) {
731 if (auto Iter = MD5VTableMap.find(MD5Hash); Iter != MD5VTableMap.end())
732 return Iter->second;
733 return nullptr;
734 }
735
736 // To store the sums of profile count values, or the percentage of
737 // the sums of the total count values.
738 struct CountSumOrPercent {
739 uint64_t NumEntries;
740 double CountSum;
741 double ValueCounts[IPVK_Last - IPVK_First + 1];
CountSumOrPercentCountSumOrPercent742 CountSumOrPercent() : NumEntries(0), CountSum(0.0f), ValueCounts() {}
resetCountSumOrPercent743 void reset() {
744 NumEntries = 0;
745 CountSum = 0.0f;
746 for (double &VC : ValueCounts)
747 VC = 0.0f;
748 }
749 };
750
751 // Function level or program level overlap information.
752 struct OverlapStats {
753 enum OverlapStatsLevel { ProgramLevel, FunctionLevel };
754 // Sum of the total count values for the base profile.
755 CountSumOrPercent Base;
756 // Sum of the total count values for the test profile.
757 CountSumOrPercent Test;
758 // Overlap lap score. Should be in range of [0.0f to 1.0f].
759 CountSumOrPercent Overlap;
760 CountSumOrPercent Mismatch;
761 CountSumOrPercent Unique;
762 OverlapStatsLevel Level;
763 const std::string *BaseFilename;
764 const std::string *TestFilename;
765 StringRef FuncName;
766 uint64_t FuncHash;
767 bool Valid;
768
769 OverlapStats(OverlapStatsLevel L = ProgramLevel)
LevelOverlapStats770 : Level(L), BaseFilename(nullptr), TestFilename(nullptr), FuncHash(0),
771 Valid(false) {}
772
773 void dump(raw_fd_ostream &OS) const;
774
setFuncInfoOverlapStats775 void setFuncInfo(StringRef Name, uint64_t Hash) {
776 FuncName = Name;
777 FuncHash = Hash;
778 }
779
780 Error accumulateCounts(const std::string &BaseFilename,
781 const std::string &TestFilename, bool IsCS);
782 void addOneMismatch(const CountSumOrPercent &MismatchFunc);
783 void addOneUnique(const CountSumOrPercent &UniqueFunc);
784
scoreOverlapStats785 static inline double score(uint64_t Val1, uint64_t Val2, double Sum1,
786 double Sum2) {
787 if (Sum1 < 1.0f || Sum2 < 1.0f)
788 return 0.0f;
789 return std::min(Val1 / Sum1, Val2 / Sum2);
790 }
791 };
792
793 // This is used to filter the functions whose overlap information
794 // to be output.
795 struct OverlapFuncFilters {
796 uint64_t ValueCutoff;
797 const std::string NameFilter;
798 };
799
800 struct InstrProfValueSiteRecord {
801 /// Value profiling data pairs at a given value site.
802 std::list<InstrProfValueData> ValueData;
803
InstrProfValueSiteRecordInstrProfValueSiteRecord804 InstrProfValueSiteRecord() { ValueData.clear(); }
805 template <class InputIterator>
InstrProfValueSiteRecordInstrProfValueSiteRecord806 InstrProfValueSiteRecord(InputIterator F, InputIterator L)
807 : ValueData(F, L) {}
808
809 /// Sort ValueData ascending by Value
sortByTargetValuesInstrProfValueSiteRecord810 void sortByTargetValues() {
811 ValueData.sort(
812 [](const InstrProfValueData &left, const InstrProfValueData &right) {
813 return left.Value < right.Value;
814 });
815 }
816 /// Sort ValueData Descending by Count
817 inline void sortByCount();
818
819 /// Merge data from another InstrProfValueSiteRecord
820 /// Optionally scale merged counts by \p Weight.
821 void merge(InstrProfValueSiteRecord &Input, uint64_t Weight,
822 function_ref<void(instrprof_error)> Warn);
823 /// Scale up value profile data counts by N (Numerator) / D (Denominator).
824 void scale(uint64_t N, uint64_t D, function_ref<void(instrprof_error)> Warn);
825
826 /// Compute the overlap b/w this record and Input record.
827 void overlap(InstrProfValueSiteRecord &Input, uint32_t ValueKind,
828 OverlapStats &Overlap, OverlapStats &FuncLevelOverlap);
829 };
830
831 /// Profiling information for a single function.
832 struct InstrProfRecord {
833 std::vector<uint64_t> Counts;
834 std::vector<uint8_t> BitmapBytes;
835
836 InstrProfRecord() = default;
InstrProfRecordInstrProfRecord837 InstrProfRecord(std::vector<uint64_t> Counts) : Counts(std::move(Counts)) {}
InstrProfRecordInstrProfRecord838 InstrProfRecord(std::vector<uint64_t> Counts,
839 std::vector<uint8_t> BitmapBytes)
840 : Counts(std::move(Counts)), BitmapBytes(std::move(BitmapBytes)) {}
841 InstrProfRecord(InstrProfRecord &&) = default;
InstrProfRecordInstrProfRecord842 InstrProfRecord(const InstrProfRecord &RHS)
843 : Counts(RHS.Counts), BitmapBytes(RHS.BitmapBytes),
844 ValueData(RHS.ValueData
845 ? std::make_unique<ValueProfData>(*RHS.ValueData)
846 : nullptr) {}
847 InstrProfRecord &operator=(InstrProfRecord &&) = default;
848 InstrProfRecord &operator=(const InstrProfRecord &RHS) {
849 Counts = RHS.Counts;
850 BitmapBytes = RHS.BitmapBytes;
851 if (!RHS.ValueData) {
852 ValueData = nullptr;
853 return *this;
854 }
855 if (!ValueData)
856 ValueData = std::make_unique<ValueProfData>(*RHS.ValueData);
857 else
858 *ValueData = *RHS.ValueData;
859 return *this;
860 }
861
862 /// Return the number of value profile kinds with non-zero number
863 /// of profile sites.
864 inline uint32_t getNumValueKinds() const;
865 /// Return the number of instrumented sites for ValueKind.
866 inline uint32_t getNumValueSites(uint32_t ValueKind) const;
867
868 /// Return the total number of ValueData for ValueKind.
869 inline uint32_t getNumValueData(uint32_t ValueKind) const;
870
871 /// Return the number of value data collected for ValueKind at profiling
872 /// site: Site.
873 inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
874 uint32_t Site) const;
875
876 /// Return the array of profiled values at \p Site. If \p TotalC
877 /// is not null, the total count of all target values at this site
878 /// will be stored in \c *TotalC.
879 inline std::unique_ptr<InstrProfValueData[]>
880 getValueForSite(uint32_t ValueKind, uint32_t Site,
881 uint64_t *TotalC = nullptr) const;
882
883 /// Get the target value/counts of kind \p ValueKind collected at site
884 /// \p Site and store the result in array \p Dest. Return the total
885 /// counts of all target values at this site.
886 inline uint64_t getValueForSite(InstrProfValueData Dest[], uint32_t ValueKind,
887 uint32_t Site) const;
888
889 /// Reserve space for NumValueSites sites.
890 inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
891
892 /// Add ValueData for ValueKind at value Site.
893 void addValueData(uint32_t ValueKind, uint32_t Site,
894 InstrProfValueData *VData, uint32_t N,
895 InstrProfSymtab *SymTab);
896
897 /// Merge the counts in \p Other into this one.
898 /// Optionally scale merged counts by \p Weight.
899 void merge(InstrProfRecord &Other, uint64_t Weight,
900 function_ref<void(instrprof_error)> Warn);
901
902 /// Scale up profile counts (including value profile data) by
903 /// a factor of (N / D).
904 void scale(uint64_t N, uint64_t D, function_ref<void(instrprof_error)> Warn);
905
906 /// Sort value profile data (per site) by count.
sortValueDataInstrProfRecord907 void sortValueData() {
908 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
909 for (auto &SR : getValueSitesForKind(Kind))
910 SR.sortByCount();
911 }
912
913 /// Clear value data entries and edge counters.
ClearInstrProfRecord914 void Clear() {
915 Counts.clear();
916 clearValueData();
917 }
918
919 /// Clear value data entries
clearValueDataInstrProfRecord920 void clearValueData() { ValueData = nullptr; }
921
922 /// Compute the sums of all counts and store in Sum.
923 void accumulateCounts(CountSumOrPercent &Sum) const;
924
925 /// Compute the overlap b/w this IntrprofRecord and Other.
926 void overlap(InstrProfRecord &Other, OverlapStats &Overlap,
927 OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff);
928
929 /// Compute the overlap of value profile counts.
930 void overlapValueProfData(uint32_t ValueKind, InstrProfRecord &Src,
931 OverlapStats &Overlap,
932 OverlapStats &FuncLevelOverlap);
933
934 enum CountPseudoKind {
935 NotPseudo = 0,
936 PseudoHot,
937 PseudoWarm,
938 };
939 enum PseudoCountVal {
940 HotFunctionVal = -1,
941 WarmFunctionVal = -2,
942 };
getCountPseudoKindInstrProfRecord943 CountPseudoKind getCountPseudoKind() const {
944 uint64_t FirstCount = Counts[0];
945 if (FirstCount == (uint64_t)HotFunctionVal)
946 return PseudoHot;
947 if (FirstCount == (uint64_t)WarmFunctionVal)
948 return PseudoWarm;
949 return NotPseudo;
950 }
setPseudoCountInstrProfRecord951 void setPseudoCount(CountPseudoKind Kind) {
952 if (Kind == PseudoHot)
953 Counts[0] = (uint64_t)HotFunctionVal;
954 else if (Kind == PseudoWarm)
955 Counts[0] = (uint64_t)WarmFunctionVal;
956 }
957
958 private:
959 struct ValueProfData {
960 std::vector<InstrProfValueSiteRecord> IndirectCallSites;
961 std::vector<InstrProfValueSiteRecord> MemOPSizes;
962 std::vector<InstrProfValueSiteRecord> VTableTargets;
963 };
964 std::unique_ptr<ValueProfData> ValueData;
965
966 MutableArrayRef<InstrProfValueSiteRecord>
getValueSitesForKindInstrProfRecord967 getValueSitesForKind(uint32_t ValueKind) {
968 // Cast to /add/ const (should be an implicit_cast, ideally, if that's ever
969 // implemented in LLVM) to call the const overload of this function, then
970 // cast away the constness from the result.
971 auto AR = const_cast<const InstrProfRecord *>(this)->getValueSitesForKind(
972 ValueKind);
973 return MutableArrayRef(
974 const_cast<InstrProfValueSiteRecord *>(AR.data()), AR.size());
975 }
976 ArrayRef<InstrProfValueSiteRecord>
getValueSitesForKindInstrProfRecord977 getValueSitesForKind(uint32_t ValueKind) const {
978 if (!ValueData)
979 return std::nullopt;
980 switch (ValueKind) {
981 case IPVK_IndirectCallTarget:
982 return ValueData->IndirectCallSites;
983 case IPVK_MemOPSize:
984 return ValueData->MemOPSizes;
985 case IPVK_VTableTarget:
986 return ValueData->VTableTargets;
987 default:
988 llvm_unreachable("Unknown value kind!");
989 }
990 }
991
992 std::vector<InstrProfValueSiteRecord> &
getOrCreateValueSitesForKindInstrProfRecord993 getOrCreateValueSitesForKind(uint32_t ValueKind) {
994 if (!ValueData)
995 ValueData = std::make_unique<ValueProfData>();
996 switch (ValueKind) {
997 case IPVK_IndirectCallTarget:
998 return ValueData->IndirectCallSites;
999 case IPVK_MemOPSize:
1000 return ValueData->MemOPSizes;
1001 case IPVK_VTableTarget:
1002 return ValueData->VTableTargets;
1003 default:
1004 llvm_unreachable("Unknown value kind!");
1005 }
1006 }
1007
1008 // Map indirect call target name hash to name string.
1009 uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
1010 InstrProfSymtab *SymTab);
1011
1012 // Merge Value Profile data from Src record to this record for ValueKind.
1013 // Scale merged value counts by \p Weight.
1014 void mergeValueProfData(uint32_t ValkeKind, InstrProfRecord &Src,
1015 uint64_t Weight,
1016 function_ref<void(instrprof_error)> Warn);
1017
1018 // Scale up value profile data count by N (Numerator) / D (Denominator).
1019 void scaleValueProfData(uint32_t ValueKind, uint64_t N, uint64_t D,
1020 function_ref<void(instrprof_error)> Warn);
1021 };
1022
1023 struct NamedInstrProfRecord : InstrProfRecord {
1024 StringRef Name;
1025 uint64_t Hash;
1026
1027 // We reserve this bit as the flag for context sensitive profile record.
1028 static const int CS_FLAG_IN_FUNC_HASH = 60;
1029
1030 NamedInstrProfRecord() = default;
NamedInstrProfRecordNamedInstrProfRecord1031 NamedInstrProfRecord(StringRef Name, uint64_t Hash,
1032 std::vector<uint64_t> Counts)
1033 : InstrProfRecord(std::move(Counts)), Name(Name), Hash(Hash) {}
NamedInstrProfRecordNamedInstrProfRecord1034 NamedInstrProfRecord(StringRef Name, uint64_t Hash,
1035 std::vector<uint64_t> Counts,
1036 std::vector<uint8_t> BitmapBytes)
1037 : InstrProfRecord(std::move(Counts), std::move(BitmapBytes)), Name(Name),
1038 Hash(Hash) {}
1039
hasCSFlagInHashNamedInstrProfRecord1040 static bool hasCSFlagInHash(uint64_t FuncHash) {
1041 return ((FuncHash >> CS_FLAG_IN_FUNC_HASH) & 1);
1042 }
setCSFlagInHashNamedInstrProfRecord1043 static void setCSFlagInHash(uint64_t &FuncHash) {
1044 FuncHash |= ((uint64_t)1 << CS_FLAG_IN_FUNC_HASH);
1045 }
1046 };
1047
getNumValueKinds()1048 uint32_t InstrProfRecord::getNumValueKinds() const {
1049 uint32_t NumValueKinds = 0;
1050 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1051 NumValueKinds += !(getValueSitesForKind(Kind).empty());
1052 return NumValueKinds;
1053 }
1054
getNumValueData(uint32_t ValueKind)1055 uint32_t InstrProfRecord::getNumValueData(uint32_t ValueKind) const {
1056 uint32_t N = 0;
1057 for (const auto &SR : getValueSitesForKind(ValueKind))
1058 N += SR.ValueData.size();
1059 return N;
1060 }
1061
getNumValueSites(uint32_t ValueKind)1062 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
1063 return getValueSitesForKind(ValueKind).size();
1064 }
1065
getNumValueDataForSite(uint32_t ValueKind,uint32_t Site)1066 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
1067 uint32_t Site) const {
1068 return getValueSitesForKind(ValueKind)[Site].ValueData.size();
1069 }
1070
1071 std::unique_ptr<InstrProfValueData[]>
getValueForSite(uint32_t ValueKind,uint32_t Site,uint64_t * TotalC)1072 InstrProfRecord::getValueForSite(uint32_t ValueKind, uint32_t Site,
1073 uint64_t *TotalC) const {
1074 uint64_t Dummy = 0;
1075 uint64_t &TotalCount = (TotalC == nullptr ? Dummy : *TotalC);
1076 uint32_t N = getNumValueDataForSite(ValueKind, Site);
1077 if (N == 0) {
1078 TotalCount = 0;
1079 return std::unique_ptr<InstrProfValueData[]>(nullptr);
1080 }
1081
1082 auto VD = std::make_unique<InstrProfValueData[]>(N);
1083 TotalCount = getValueForSite(VD.get(), ValueKind, Site);
1084
1085 return VD;
1086 }
1087
getValueForSite(InstrProfValueData Dest[],uint32_t ValueKind,uint32_t Site)1088 uint64_t InstrProfRecord::getValueForSite(InstrProfValueData Dest[],
1089 uint32_t ValueKind,
1090 uint32_t Site) const {
1091 uint32_t I = 0;
1092 uint64_t TotalCount = 0;
1093 for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
1094 Dest[I].Value = V.Value;
1095 Dest[I].Count = V.Count;
1096 TotalCount = SaturatingAdd(TotalCount, V.Count);
1097 I++;
1098 }
1099 return TotalCount;
1100 }
1101
reserveSites(uint32_t ValueKind,uint32_t NumValueSites)1102 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
1103 if (!NumValueSites)
1104 return;
1105 getOrCreateValueSitesForKind(ValueKind).reserve(NumValueSites);
1106 }
1107
1108 // Include definitions for value profile data
1109 #define INSTR_PROF_VALUE_PROF_DATA
1110 #include "llvm/ProfileData/InstrProfData.inc"
1111
sortByCount()1112 void InstrProfValueSiteRecord::sortByCount() {
1113 ValueData.sort(
1114 [](const InstrProfValueData &left, const InstrProfValueData &right) {
1115 return left.Count > right.Count;
1116 });
1117 // Now truncate
1118 size_t max_s = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
1119 if (ValueData.size() > max_s)
1120 ValueData.resize(max_s);
1121 }
1122
1123 namespace IndexedInstrProf {
1124
1125 enum class HashT : uint32_t {
1126 MD5,
1127 Last = MD5
1128 };
1129
ComputeHash(HashT Type,StringRef K)1130 inline uint64_t ComputeHash(HashT Type, StringRef K) {
1131 switch (Type) {
1132 case HashT::MD5:
1133 return MD5Hash(K);
1134 }
1135 llvm_unreachable("Unhandled hash type");
1136 }
1137
1138 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
1139
1140 enum ProfVersion {
1141 // Version 1 is the first version. In this version, the value of
1142 // a key/value pair can only include profile data of a single function.
1143 // Due to this restriction, the number of block counters for a given
1144 // function is not recorded but derived from the length of the value.
1145 Version1 = 1,
1146 // The version 2 format supports recording profile data of multiple
1147 // functions which share the same key in one value field. To support this,
1148 // the number block counters is recorded as an uint64_t field right after the
1149 // function structural hash.
1150 Version2 = 2,
1151 // Version 3 supports value profile data. The value profile data is expected
1152 // to follow the block counter profile data.
1153 Version3 = 3,
1154 // In this version, profile summary data \c IndexedInstrProf::Summary is
1155 // stored after the profile header.
1156 Version4 = 4,
1157 // In this version, the frontend PGO stable hash algorithm defaults to V2.
1158 Version5 = 5,
1159 // In this version, the frontend PGO stable hash algorithm got fixed and
1160 // may produce hashes different from Version5.
1161 Version6 = 6,
1162 // An additional counter is added around logical operators.
1163 Version7 = 7,
1164 // An additional (optional) memory profile type is added.
1165 Version8 = 8,
1166 // Binary ids are added.
1167 Version9 = 9,
1168 // An additional (optional) temporal profile traces section is added.
1169 Version10 = 10,
1170 // An additional field is used for bitmap bytes.
1171 Version11 = 11,
1172 // VTable profiling,
1173 Version12 = 12,
1174 // The current version is 12.
1175 CurrentVersion = INSTR_PROF_INDEX_VERSION
1176 };
1177 const uint64_t Version = ProfVersion::CurrentVersion;
1178
1179 const HashT HashType = HashT::MD5;
1180
ComputeHash(StringRef K)1181 inline uint64_t ComputeHash(StringRef K) { return ComputeHash(HashType, K); }
1182
1183 // This structure defines the file header of the LLVM profile
1184 // data file in indexed-format. Please update llvm/docs/InstrProfileFormat.rst
1185 // as appropriate when updating the indexed profile format.
1186 struct Header {
1187 uint64_t Magic;
1188 // The lower 32 bits specify the version of the indexed profile.
1189 // The most significant 32 bits are reserved to specify the variant types of
1190 // the profile.
1191 uint64_t Version;
1192 uint64_t Unused; // Becomes unused since version 4
1193 uint64_t HashType;
1194 // This field records the offset of this hash table's metadata (i.e., the
1195 // number of buckets and entries), which follows right after the payload of
1196 // the entire hash table.
1197 uint64_t HashOffset;
1198 uint64_t MemProfOffset;
1199 uint64_t BinaryIdOffset;
1200 uint64_t TemporalProfTracesOffset;
1201 uint64_t VTableNamesOffset;
1202 // New fields should only be added at the end to ensure that the size
1203 // computation is correct. The methods below need to be updated to ensure that
1204 // the new field is read correctly.
1205
1206 // Reads a header struct from the buffer.
1207 static Expected<Header> readFromBuffer(const unsigned char *Buffer);
1208
1209 // Returns the size of the header in bytes for all valid fields based on the
1210 // version. I.e a older version header will return a smaller size.
1211 size_t size() const;
1212
1213 // Returns the format version in little endian. The header retains the version
1214 // in native endian of the compiler runtime.
1215 uint64_t formatVersion() const;
1216 };
1217
1218 // Profile summary data recorded in the profile data file in indexed
1219 // format. It is introduced in version 4. The summary data follows
1220 // right after the profile file header.
1221 struct Summary {
1222 struct Entry {
1223 uint64_t Cutoff; ///< The required percentile of total execution count.
1224 uint64_t
1225 MinBlockCount; ///< The minimum execution count for this percentile.
1226 uint64_t NumBlocks; ///< Number of blocks >= the minumum execution count.
1227 };
1228 // The field kind enumerator to assigned value mapping should remain
1229 // unchanged when a new kind is added or an old kind gets deleted in
1230 // the future.
1231 enum SummaryFieldKind {
1232 /// The total number of functions instrumented.
1233 TotalNumFunctions = 0,
1234 /// Total number of instrumented blocks/edges.
1235 TotalNumBlocks = 1,
1236 /// The maximal execution count among all functions.
1237 /// This field does not exist for profile data from IR based
1238 /// instrumentation.
1239 MaxFunctionCount = 2,
1240 /// Max block count of the program.
1241 MaxBlockCount = 3,
1242 /// Max internal block count of the program (excluding entry blocks).
1243 MaxInternalBlockCount = 4,
1244 /// The sum of all instrumented block counts.
1245 TotalBlockCount = 5,
1246 NumKinds = TotalBlockCount + 1
1247 };
1248
1249 // The number of summmary fields following the summary header.
1250 uint64_t NumSummaryFields;
1251 // The number of Cutoff Entries (Summary::Entry) following summary fields.
1252 uint64_t NumCutoffEntries;
1253
1254 Summary() = delete;
SummarySummary1255 Summary(uint32_t Size) { memset(this, 0, Size); }
1256
deleteSummary1257 void operator delete(void *ptr) { ::operator delete(ptr); }
1258
getSizeSummary1259 static uint32_t getSize(uint32_t NumSumFields, uint32_t NumCutoffEntries) {
1260 return sizeof(Summary) + NumCutoffEntries * sizeof(Entry) +
1261 NumSumFields * sizeof(uint64_t);
1262 }
1263
getSummaryDataBaseSummary1264 const uint64_t *getSummaryDataBase() const {
1265 return reinterpret_cast<const uint64_t *>(this + 1);
1266 }
1267
getSummaryDataBaseSummary1268 uint64_t *getSummaryDataBase() {
1269 return reinterpret_cast<uint64_t *>(this + 1);
1270 }
1271
getCutoffEntryBaseSummary1272 const Entry *getCutoffEntryBase() const {
1273 return reinterpret_cast<const Entry *>(
1274 &getSummaryDataBase()[NumSummaryFields]);
1275 }
1276
getCutoffEntryBaseSummary1277 Entry *getCutoffEntryBase() {
1278 return reinterpret_cast<Entry *>(&getSummaryDataBase()[NumSummaryFields]);
1279 }
1280
getSummary1281 uint64_t get(SummaryFieldKind K) const {
1282 return getSummaryDataBase()[K];
1283 }
1284
setSummary1285 void set(SummaryFieldKind K, uint64_t V) {
1286 getSummaryDataBase()[K] = V;
1287 }
1288
getEntrySummary1289 const Entry &getEntry(uint32_t I) const { return getCutoffEntryBase()[I]; }
1290
setEntrySummary1291 void setEntry(uint32_t I, const ProfileSummaryEntry &E) {
1292 Entry &ER = getCutoffEntryBase()[I];
1293 ER.Cutoff = E.Cutoff;
1294 ER.MinBlockCount = E.MinCount;
1295 ER.NumBlocks = E.NumCounts;
1296 }
1297 };
1298
allocSummary(uint32_t TotalSize)1299 inline std::unique_ptr<Summary> allocSummary(uint32_t TotalSize) {
1300 return std::unique_ptr<Summary>(new (::operator new(TotalSize))
1301 Summary(TotalSize));
1302 }
1303
1304 } // end namespace IndexedInstrProf
1305
1306 namespace RawInstrProf {
1307
1308 // Version 1: First version
1309 // Version 2: Added value profile data section. Per-function control data
1310 // struct has more fields to describe value profile information.
1311 // Version 3: Compressed name section support. Function PGO name reference
1312 // from control data struct is changed from raw pointer to Name's MD5 value.
1313 // Version 4: ValueDataBegin and ValueDataSizes fields are removed from the
1314 // raw header.
1315 // Version 5: Bit 60 of FuncHash is reserved for the flag for the context
1316 // sensitive records.
1317 // Version 6: Added binary id.
1318 // Version 7: Reorder binary id and include version in signature.
1319 // Version 8: Use relative counter pointer.
1320 // Version 9: Added relative bitmap bytes pointer and count used by MC/DC.
1321 // Version 10: Added vtable, a new type of value profile data.
1322 const uint64_t Version = INSTR_PROF_RAW_VERSION;
1323
1324 template <class IntPtrT> inline uint64_t getMagic();
1325 template <> inline uint64_t getMagic<uint64_t>() {
1326 return INSTR_PROF_RAW_MAGIC_64;
1327 }
1328
1329 template <> inline uint64_t getMagic<uint32_t>() {
1330 return INSTR_PROF_RAW_MAGIC_32;
1331 }
1332
1333 // Per-function profile data header/control structure.
1334 // The definition should match the structure defined in
1335 // compiler-rt/lib/profile/InstrProfiling.h.
1336 // It should also match the synthesized type in
1337 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
1338 template <class IntPtrT> struct alignas(8) ProfileData {
1339 #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
1340 #include "llvm/ProfileData/InstrProfData.inc"
1341 };
1342
1343 template <class IntPtrT> struct alignas(8) VTableProfileData {
1344 #define INSTR_PROF_VTABLE_DATA(Type, LLVMType, Name, Init) Type Name;
1345 #include "llvm/ProfileData/InstrProfData.inc"
1346 };
1347
1348 // File header structure of the LLVM profile data in raw format.
1349 // The definition should match the header referenced in
1350 // compiler-rt/lib/profile/InstrProfilingFile.c and
1351 // InstrProfilingBuffer.c.
1352 struct Header {
1353 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
1354 #include "llvm/ProfileData/InstrProfData.inc"
1355 };
1356
1357 } // end namespace RawInstrProf
1358
1359 // Create the variable for the profile file name.
1360 void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput);
1361
1362 // Whether to compress function names in profile records, and filenames in
1363 // code coverage mappings. Used by the Instrumentation library and unit tests.
1364 extern cl::opt<bool> DoInstrProfNameCompression;
1365
1366 } // end namespace llvm
1367 #endif // LLVM_PROFILEDATA_INSTRPROF_H
1368