Recommit [NFC] Better encapsulation of llvm::Optional Storage
[llvm-complete.git] / include / llvm / ProfileData / SampleProf.h
blobca3e2dec561424373e07c064cb64bebbda8ad876
1 //===- SampleProf.h - Sampling 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 // This file contains common definitions used in the reading and writing of
10 // sample profile data.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_PROFILEDATA_SAMPLEPROF_H
15 #define LLVM_PROFILEDATA_SAMPLEPROF_H
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/GlobalValue.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorOr.h"
26 #include "llvm/Support/MathExtras.h"
27 #include <algorithm>
28 #include <cstdint>
29 #include <map>
30 #include <string>
31 #include <system_error>
32 #include <utility>
34 namespace llvm {
36 class raw_ostream;
38 const std::error_category &sampleprof_category();
40 enum class sampleprof_error {
41 success = 0,
42 bad_magic,
43 unsupported_version,
44 too_large,
45 truncated,
46 malformed,
47 unrecognized_format,
48 unsupported_writing_format,
49 truncated_name_table,
50 not_implemented,
51 counter_overflow,
52 ostream_seek_unsupported
55 inline std::error_code make_error_code(sampleprof_error E) {
56 return std::error_code(static_cast<int>(E), sampleprof_category());
59 inline sampleprof_error MergeResult(sampleprof_error &Accumulator,
60 sampleprof_error Result) {
61 // Prefer first error encountered as later errors may be secondary effects of
62 // the initial problem.
63 if (Accumulator == sampleprof_error::success &&
64 Result != sampleprof_error::success)
65 Accumulator = Result;
66 return Accumulator;
69 } // end namespace llvm
71 namespace std {
73 template <>
74 struct is_error_code_enum<llvm::sampleprof_error> : std::true_type {};
76 } // end namespace std
78 namespace llvm {
79 namespace sampleprof {
81 enum SampleProfileFormat {
82 SPF_None = 0,
83 SPF_Text = 0x1,
84 SPF_Compact_Binary = 0x2,
85 SPF_GCC = 0x3,
86 SPF_Binary = 0xff
89 static inline uint64_t SPMagic(SampleProfileFormat Format = SPF_Binary) {
90 return uint64_t('S') << (64 - 8) | uint64_t('P') << (64 - 16) |
91 uint64_t('R') << (64 - 24) | uint64_t('O') << (64 - 32) |
92 uint64_t('F') << (64 - 40) | uint64_t('4') << (64 - 48) |
93 uint64_t('2') << (64 - 56) | uint64_t(Format);
96 // Get the proper representation of a string in the input Format.
97 static inline StringRef getRepInFormat(StringRef Name,
98 SampleProfileFormat Format,
99 std::string &GUIDBuf) {
100 if (Name.empty())
101 return Name;
102 GUIDBuf = std::to_string(Function::getGUID(Name));
103 return (Format == SPF_Compact_Binary) ? StringRef(GUIDBuf) : Name;
106 static inline uint64_t SPVersion() { return 103; }
108 /// Represents the relative location of an instruction.
110 /// Instruction locations are specified by the line offset from the
111 /// beginning of the function (marked by the line where the function
112 /// header is) and the discriminator value within that line.
114 /// The discriminator value is useful to distinguish instructions
115 /// that are on the same line but belong to different basic blocks
116 /// (e.g., the two post-increment instructions in "if (p) x++; else y++;").
117 struct LineLocation {
118 LineLocation(uint32_t L, uint32_t D) : LineOffset(L), Discriminator(D) {}
120 void print(raw_ostream &OS) const;
121 void dump() const;
123 bool operator<(const LineLocation &O) const {
124 return LineOffset < O.LineOffset ||
125 (LineOffset == O.LineOffset && Discriminator < O.Discriminator);
128 uint32_t LineOffset;
129 uint32_t Discriminator;
132 raw_ostream &operator<<(raw_ostream &OS, const LineLocation &Loc);
134 /// Representation of a single sample record.
136 /// A sample record is represented by a positive integer value, which
137 /// indicates how frequently was the associated line location executed.
139 /// Additionally, if the associated location contains a function call,
140 /// the record will hold a list of all the possible called targets. For
141 /// direct calls, this will be the exact function being invoked. For
142 /// indirect calls (function pointers, virtual table dispatch), this
143 /// will be a list of one or more functions.
144 class SampleRecord {
145 public:
146 using CallTargetMap = StringMap<uint64_t>;
148 SampleRecord() = default;
150 /// Increment the number of samples for this record by \p S.
151 /// Optionally scale sample count \p S by \p Weight.
153 /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
154 /// around unsigned integers.
155 sampleprof_error addSamples(uint64_t S, uint64_t Weight = 1) {
156 bool Overflowed;
157 NumSamples = SaturatingMultiplyAdd(S, Weight, NumSamples, &Overflowed);
158 return Overflowed ? sampleprof_error::counter_overflow
159 : sampleprof_error::success;
162 /// Add called function \p F with samples \p S.
163 /// Optionally scale sample count \p S by \p Weight.
165 /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
166 /// around unsigned integers.
167 sampleprof_error addCalledTarget(StringRef F, uint64_t S,
168 uint64_t Weight = 1) {
169 uint64_t &TargetSamples = CallTargets[F];
170 bool Overflowed;
171 TargetSamples =
172 SaturatingMultiplyAdd(S, Weight, TargetSamples, &Overflowed);
173 return Overflowed ? sampleprof_error::counter_overflow
174 : sampleprof_error::success;
177 /// Return true if this sample record contains function calls.
178 bool hasCalls() const { return !CallTargets.empty(); }
180 uint64_t getSamples() const { return NumSamples; }
181 const CallTargetMap &getCallTargets() const { return CallTargets; }
183 /// Merge the samples in \p Other into this record.
184 /// Optionally scale sample counts by \p Weight.
185 sampleprof_error merge(const SampleRecord &Other, uint64_t Weight = 1) {
186 sampleprof_error Result = addSamples(Other.getSamples(), Weight);
187 for (const auto &I : Other.getCallTargets()) {
188 MergeResult(Result, addCalledTarget(I.first(), I.second, Weight));
190 return Result;
193 void print(raw_ostream &OS, unsigned Indent) const;
194 void dump() const;
196 private:
197 uint64_t NumSamples = 0;
198 CallTargetMap CallTargets;
201 raw_ostream &operator<<(raw_ostream &OS, const SampleRecord &Sample);
203 class FunctionSamples;
205 using BodySampleMap = std::map<LineLocation, SampleRecord>;
206 // NOTE: Using a StringMap here makes parsed profiles consume around 17% more
207 // memory, which is *very* significant for large profiles.
208 using FunctionSamplesMap = std::map<std::string, FunctionSamples>;
209 using CallsiteSampleMap = std::map<LineLocation, FunctionSamplesMap>;
211 /// Representation of the samples collected for a function.
213 /// This data structure contains all the collected samples for the body
214 /// of a function. Each sample corresponds to a LineLocation instance
215 /// within the body of the function.
216 class FunctionSamples {
217 public:
218 FunctionSamples() = default;
220 void print(raw_ostream &OS = dbgs(), unsigned Indent = 0) const;
221 void dump() const;
223 sampleprof_error addTotalSamples(uint64_t Num, uint64_t Weight = 1) {
224 bool Overflowed;
225 TotalSamples =
226 SaturatingMultiplyAdd(Num, Weight, TotalSamples, &Overflowed);
227 return Overflowed ? sampleprof_error::counter_overflow
228 : sampleprof_error::success;
231 sampleprof_error addHeadSamples(uint64_t Num, uint64_t Weight = 1) {
232 bool Overflowed;
233 TotalHeadSamples =
234 SaturatingMultiplyAdd(Num, Weight, TotalHeadSamples, &Overflowed);
235 return Overflowed ? sampleprof_error::counter_overflow
236 : sampleprof_error::success;
239 sampleprof_error addBodySamples(uint32_t LineOffset, uint32_t Discriminator,
240 uint64_t Num, uint64_t Weight = 1) {
241 return BodySamples[LineLocation(LineOffset, Discriminator)].addSamples(
242 Num, Weight);
245 sampleprof_error addCalledTargetSamples(uint32_t LineOffset,
246 uint32_t Discriminator,
247 StringRef FName, uint64_t Num,
248 uint64_t Weight = 1) {
249 return BodySamples[LineLocation(LineOffset, Discriminator)].addCalledTarget(
250 FName, Num, Weight);
253 /// Return the number of samples collected at the given location.
254 /// Each location is specified by \p LineOffset and \p Discriminator.
255 /// If the location is not found in profile, return error.
256 ErrorOr<uint64_t> findSamplesAt(uint32_t LineOffset,
257 uint32_t Discriminator) const {
258 const auto &ret = BodySamples.find(LineLocation(LineOffset, Discriminator));
259 if (ret == BodySamples.end())
260 return std::error_code();
261 else
262 return ret->second.getSamples();
265 /// Returns the call target map collected at a given location.
266 /// Each location is specified by \p LineOffset and \p Discriminator.
267 /// If the location is not found in profile, return error.
268 ErrorOr<SampleRecord::CallTargetMap>
269 findCallTargetMapAt(uint32_t LineOffset, uint32_t Discriminator) const {
270 const auto &ret = BodySamples.find(LineLocation(LineOffset, Discriminator));
271 if (ret == BodySamples.end())
272 return std::error_code();
273 return ret->second.getCallTargets();
276 /// Return the function samples at the given callsite location.
277 FunctionSamplesMap &functionSamplesAt(const LineLocation &Loc) {
278 return CallsiteSamples[Loc];
281 /// Returns the FunctionSamplesMap at the given \p Loc.
282 const FunctionSamplesMap *
283 findFunctionSamplesMapAt(const LineLocation &Loc) const {
284 auto iter = CallsiteSamples.find(Loc);
285 if (iter == CallsiteSamples.end())
286 return nullptr;
287 return &iter->second;
290 /// Returns a pointer to FunctionSamples at the given callsite location \p Loc
291 /// with callee \p CalleeName. If no callsite can be found, relax the
292 /// restriction to return the FunctionSamples at callsite location \p Loc
293 /// with the maximum total sample count.
294 const FunctionSamples *findFunctionSamplesAt(const LineLocation &Loc,
295 StringRef CalleeName) const {
296 std::string CalleeGUID;
297 CalleeName = getRepInFormat(CalleeName, Format, CalleeGUID);
299 auto iter = CallsiteSamples.find(Loc);
300 if (iter == CallsiteSamples.end())
301 return nullptr;
302 auto FS = iter->second.find(CalleeName);
303 if (FS != iter->second.end())
304 return &FS->second;
305 // If we cannot find exact match of the callee name, return the FS with
306 // the max total count.
307 uint64_t MaxTotalSamples = 0;
308 const FunctionSamples *R = nullptr;
309 for (const auto &NameFS : iter->second)
310 if (NameFS.second.getTotalSamples() >= MaxTotalSamples) {
311 MaxTotalSamples = NameFS.second.getTotalSamples();
312 R = &NameFS.second;
314 return R;
317 bool empty() const { return TotalSamples == 0; }
319 /// Return the total number of samples collected inside the function.
320 uint64_t getTotalSamples() const { return TotalSamples; }
322 /// Return the total number of branch samples that have the function as the
323 /// branch target. This should be equivalent to the sample of the first
324 /// instruction of the symbol. But as we directly get this info for raw
325 /// profile without referring to potentially inaccurate debug info, this
326 /// gives more accurate profile data and is preferred for standalone symbols.
327 uint64_t getHeadSamples() const { return TotalHeadSamples; }
329 /// Return the sample count of the first instruction of the function.
330 /// The function can be either a standalone symbol or an inlined function.
331 uint64_t getEntrySamples() const {
332 // Use either BodySamples or CallsiteSamples which ever has the smaller
333 // lineno.
334 if (!BodySamples.empty() &&
335 (CallsiteSamples.empty() ||
336 BodySamples.begin()->first < CallsiteSamples.begin()->first))
337 return BodySamples.begin()->second.getSamples();
338 if (!CallsiteSamples.empty()) {
339 uint64_t T = 0;
340 // An indirect callsite may be promoted to several inlined direct calls.
341 // We need to get the sum of them.
342 for (const auto &N_FS : CallsiteSamples.begin()->second)
343 T += N_FS.second.getEntrySamples();
344 return T;
346 return 0;
349 /// Return all the samples collected in the body of the function.
350 const BodySampleMap &getBodySamples() const { return BodySamples; }
352 /// Return all the callsite samples collected in the body of the function.
353 const CallsiteSampleMap &getCallsiteSamples() const {
354 return CallsiteSamples;
357 /// Merge the samples in \p Other into this one.
358 /// Optionally scale samples by \p Weight.
359 sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight = 1) {
360 sampleprof_error Result = sampleprof_error::success;
361 Name = Other.getName();
362 MergeResult(Result, addTotalSamples(Other.getTotalSamples(), Weight));
363 MergeResult(Result, addHeadSamples(Other.getHeadSamples(), Weight));
364 for (const auto &I : Other.getBodySamples()) {
365 const LineLocation &Loc = I.first;
366 const SampleRecord &Rec = I.second;
367 MergeResult(Result, BodySamples[Loc].merge(Rec, Weight));
369 for (const auto &I : Other.getCallsiteSamples()) {
370 const LineLocation &Loc = I.first;
371 FunctionSamplesMap &FSMap = functionSamplesAt(Loc);
372 for (const auto &Rec : I.second)
373 MergeResult(Result, FSMap[Rec.first].merge(Rec.second, Weight));
375 return Result;
378 /// Recursively traverses all children, if the total sample count of the
379 /// corresponding function is no less than \p Threshold, add its corresponding
380 /// GUID to \p S. Also traverse the BodySamples to add hot CallTarget's GUID
381 /// to \p S.
382 void findInlinedFunctions(DenseSet<GlobalValue::GUID> &S, const Module *M,
383 uint64_t Threshold) const {
384 if (TotalSamples <= Threshold)
385 return;
386 S.insert(getGUID(Name));
387 // Import hot CallTargets, which may not be available in IR because full
388 // profile annotation cannot be done until backend compilation in ThinLTO.
389 for (const auto &BS : BodySamples)
390 for (const auto &TS : BS.second.getCallTargets())
391 if (TS.getValue() > Threshold) {
392 const Function *Callee =
393 M->getFunction(getNameInModule(TS.getKey(), M));
394 if (!Callee || !Callee->getSubprogram())
395 S.insert(getGUID(TS.getKey()));
397 for (const auto &CS : CallsiteSamples)
398 for (const auto &NameFS : CS.second)
399 NameFS.second.findInlinedFunctions(S, M, Threshold);
402 /// Set the name of the function.
403 void setName(StringRef FunctionName) { Name = FunctionName; }
405 /// Return the function name.
406 StringRef getName() const { return Name; }
408 /// Return the original function name if it exists in Module \p M.
409 StringRef getFuncNameInModule(const Module *M) const {
410 return getNameInModule(Name, M);
413 /// Translate \p Name into its original name in Module.
414 /// When the Format is not SPF_Compact_Binary, \p Name needs no translation.
415 /// When the Format is SPF_Compact_Binary, \p Name in current FunctionSamples
416 /// is actually GUID of the original function name. getNameInModule will
417 /// translate \p Name in current FunctionSamples into its original name.
418 /// If the original name doesn't exist in \p M, return empty StringRef.
419 StringRef getNameInModule(StringRef Name, const Module *M) const {
420 if (Format != SPF_Compact_Binary)
421 return Name;
422 // Expect CurrentModule to be initialized by GUIDToFuncNameMapper.
423 if (M != CurrentModule)
424 llvm_unreachable("Input Module should be the same as CurrentModule");
425 auto iter = GUIDToFuncNameMap.find(std::stoull(Name.data()));
426 if (iter == GUIDToFuncNameMap.end())
427 return StringRef();
428 return iter->second;
431 /// Returns the line offset to the start line of the subprogram.
432 /// We assume that a single function will not exceed 65535 LOC.
433 static unsigned getOffset(const DILocation *DIL);
435 /// Get the FunctionSamples of the inline instance where DIL originates
436 /// from.
438 /// The FunctionSamples of the instruction (Machine or IR) associated to
439 /// \p DIL is the inlined instance in which that instruction is coming from.
440 /// We traverse the inline stack of that instruction, and match it with the
441 /// tree nodes in the profile.
443 /// \returns the FunctionSamples pointer to the inlined instance.
444 const FunctionSamples *findFunctionSamples(const DILocation *DIL) const;
446 static SampleProfileFormat Format;
447 /// GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
448 /// all the function symbols defined or declared in CurrentModule.
449 static DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
450 static Module *CurrentModule;
452 class GUIDToFuncNameMapper {
453 public:
454 GUIDToFuncNameMapper(Module &M) {
455 if (Format != SPF_Compact_Binary)
456 return;
458 for (const auto &F : M) {
459 StringRef OrigName = F.getName();
460 GUIDToFuncNameMap.insert({Function::getGUID(OrigName), OrigName});
461 /// Local to global var promotion used by optimization like thinlto
462 /// will rename the var and add suffix like ".llvm.xxx" to the
463 /// original local name. In sample profile, the suffixes of function
464 /// names are all stripped. Since it is possible that the mapper is
465 /// built in post-thin-link phase and var promotion has been done,
466 /// we need to add the substring of function name without the suffix
467 /// into the GUIDToFuncNameMap.
468 auto pos = OrigName.find('.');
469 if (pos != StringRef::npos) {
470 StringRef NewName = OrigName.substr(0, pos);
471 GUIDToFuncNameMap.insert({Function::getGUID(NewName), NewName});
474 CurrentModule = &M;
477 ~GUIDToFuncNameMapper() {
478 if (Format != SPF_Compact_Binary)
479 return;
481 GUIDToFuncNameMap.clear();
482 CurrentModule = nullptr;
486 // Assume the input \p Name is a name coming from FunctionSamples itself.
487 // If the format is SPF_Compact_Binary, the name is already a GUID and we
488 // don't want to return the GUID of GUID.
489 static uint64_t getGUID(StringRef Name) {
490 return (Format == SPF_Compact_Binary) ? std::stoull(Name.data())
491 : Function::getGUID(Name);
494 private:
495 /// Mangled name of the function.
496 StringRef Name;
498 /// Total number of samples collected inside this function.
500 /// Samples are cumulative, they include all the samples collected
501 /// inside this function and all its inlined callees.
502 uint64_t TotalSamples = 0;
504 /// Total number of samples collected at the head of the function.
505 /// This is an approximation of the number of calls made to this function
506 /// at runtime.
507 uint64_t TotalHeadSamples = 0;
509 /// Map instruction locations to collected samples.
511 /// Each entry in this map contains the number of samples
512 /// collected at the corresponding line offset. All line locations
513 /// are an offset from the start of the function.
514 BodySampleMap BodySamples;
516 /// Map call sites to collected samples for the called function.
518 /// Each entry in this map corresponds to all the samples
519 /// collected for the inlined function call at the given
520 /// location. For example, given:
522 /// void foo() {
523 /// 1 bar();
524 /// ...
525 /// 8 baz();
526 /// }
528 /// If the bar() and baz() calls were inlined inside foo(), this
529 /// map will contain two entries. One for all the samples collected
530 /// in the call to bar() at line offset 1, the other for all the samples
531 /// collected in the call to baz() at line offset 8.
532 CallsiteSampleMap CallsiteSamples;
535 raw_ostream &operator<<(raw_ostream &OS, const FunctionSamples &FS);
537 /// Sort a LocationT->SampleT map by LocationT.
539 /// It produces a sorted list of <LocationT, SampleT> records by ascending
540 /// order of LocationT.
541 template <class LocationT, class SampleT> class SampleSorter {
542 public:
543 using SamplesWithLoc = std::pair<const LocationT, SampleT>;
544 using SamplesWithLocList = SmallVector<const SamplesWithLoc *, 20>;
546 SampleSorter(const std::map<LocationT, SampleT> &Samples) {
547 for (const auto &I : Samples)
548 V.push_back(&I);
549 std::stable_sort(V.begin(), V.end(),
550 [](const SamplesWithLoc *A, const SamplesWithLoc *B) {
551 return A->first < B->first;
555 const SamplesWithLocList &get() const { return V; }
557 private:
558 SamplesWithLocList V;
561 } // end namespace sampleprof
562 } // end namespace llvm
564 #endif // LLVM_PROFILEDATA_SAMPLEPROF_H