1 //===- SampleProf.h - Sampling profiling format support ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains common definitions used in the reading and writing of
11 // sample profile data.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_PROFILEDATA_SAMPLEPROF_H
16 #define LLVM_PROFILEDATA_SAMPLEPROF_H
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/GlobalValue.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorOr.h"
27 #include "llvm/Support/MathExtras.h"
32 #include <system_error>
39 const std::error_category &sampleprof_category();
41 enum class sampleprof_error {
49 unsupported_writing_format,
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)
69 } // end namespace llvm
74 struct is_error_code_enum<llvm::sampleprof_error> : std::true_type {};
76 } // end namespace std
79 namespace sampleprof {
81 enum SampleProfileFormat {
84 SPF_Compact_Binary = 0x2,
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) {
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;
123 bool operator<(const LineLocation &O) const {
124 return LineOffset < O.LineOffset ||
125 (LineOffset == O.LineOffset && Discriminator < O.Discriminator);
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.
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) {
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];
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));
193 void print(raw_ostream &OS, unsigned Indent) const;
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 {
218 FunctionSamples() = default;
220 void print(raw_ostream &OS = dbgs(), unsigned Indent = 0) const;
223 sampleprof_error addTotalSamples(uint64_t Num, uint64_t Weight = 1) {
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) {
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(
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(
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();
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())
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 auto iter = CallsiteSamples.find(Loc);
297 if (iter == CallsiteSamples.end())
299 auto FS = iter->second.find(CalleeName);
300 if (FS != iter->second.end())
302 // If we cannot find exact match of the callee name, return the FS with
303 // the max total count.
304 uint64_t MaxTotalSamples = 0;
305 const FunctionSamples *R = nullptr;
306 for (const auto &NameFS : iter->second)
307 if (NameFS.second.getTotalSamples() >= MaxTotalSamples) {
308 MaxTotalSamples = NameFS.second.getTotalSamples();
314 bool empty() const { return TotalSamples == 0; }
316 /// Return the total number of samples collected inside the function.
317 uint64_t getTotalSamples() const { return TotalSamples; }
319 /// Return the total number of branch samples that have the function as the
320 /// branch target. This should be equivalent to the sample of the first
321 /// instruction of the symbol. But as we directly get this info for raw
322 /// profile without referring to potentially inaccurate debug info, this
323 /// gives more accurate profile data and is preferred for standalone symbols.
324 uint64_t getHeadSamples() const { return TotalHeadSamples; }
326 /// Return the sample count of the first instruction of the function.
327 /// The function can be either a standalone symbol or an inlined function.
328 uint64_t getEntrySamples() const {
329 // Use either BodySamples or CallsiteSamples which ever has the smaller
331 if (!BodySamples.empty() &&
332 (CallsiteSamples.empty() ||
333 BodySamples.begin()->first < CallsiteSamples.begin()->first))
334 return BodySamples.begin()->second.getSamples();
335 if (!CallsiteSamples.empty()) {
337 // An indirect callsite may be promoted to several inlined direct calls.
338 // We need to get the sum of them.
339 for (const auto &N_FS : CallsiteSamples.begin()->second)
340 T += N_FS.second.getEntrySamples();
346 /// Return all the samples collected in the body of the function.
347 const BodySampleMap &getBodySamples() const { return BodySamples; }
349 /// Return all the callsite samples collected in the body of the function.
350 const CallsiteSampleMap &getCallsiteSamples() const {
351 return CallsiteSamples;
354 /// Merge the samples in \p Other into this one.
355 /// Optionally scale samples by \p Weight.
356 sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight = 1) {
357 sampleprof_error Result = sampleprof_error::success;
358 Name = Other.getName();
359 MergeResult(Result, addTotalSamples(Other.getTotalSamples(), Weight));
360 MergeResult(Result, addHeadSamples(Other.getHeadSamples(), Weight));
361 for (const auto &I : Other.getBodySamples()) {
362 const LineLocation &Loc = I.first;
363 const SampleRecord &Rec = I.second;
364 MergeResult(Result, BodySamples[Loc].merge(Rec, Weight));
366 for (const auto &I : Other.getCallsiteSamples()) {
367 const LineLocation &Loc = I.first;
368 FunctionSamplesMap &FSMap = functionSamplesAt(Loc);
369 for (const auto &Rec : I.second)
370 MergeResult(Result, FSMap[Rec.first].merge(Rec.second, Weight));
375 /// Recursively traverses all children, if the total sample count of the
376 /// corresponding function is no less than \p Threshold, add its corresponding
377 /// GUID to \p S. Also traverse the BodySamples to add hot CallTarget's GUID
379 void findInlinedFunctions(DenseSet<GlobalValue::GUID> &S, const Module *M,
380 uint64_t Threshold, bool isCompact) const {
381 if (TotalSamples <= Threshold)
383 S.insert(Function::getGUID(Name));
384 // Import hot CallTargets, which may not be available in IR because full
385 // profile annotation cannot be done until backend compilation in ThinLTO.
386 for (const auto &BS : BodySamples)
387 for (const auto &TS : BS.second.getCallTargets())
388 if (TS.getValue() > Threshold) {
389 Function *Callee = M->getFunction(TS.getKey());
390 if (!Callee || !Callee->getSubprogram())
391 S.insert(isCompact ? std::stol(TS.getKey().data())
392 : Function::getGUID(TS.getKey()));
394 for (const auto &CS : CallsiteSamples)
395 for (const auto &NameFS : CS.second)
396 NameFS.second.findInlinedFunctions(S, M, Threshold, isCompact);
399 /// Set the name of the function.
400 void setName(StringRef FunctionName) { Name = FunctionName; }
402 /// Return the function name.
403 const StringRef &getName() const { return Name; }
405 /// Returns the line offset to the start line of the subprogram.
406 /// We assume that a single function will not exceed 65535 LOC.
407 static unsigned getOffset(const DILocation *DIL);
409 /// Get the FunctionSamples of the inline instance where DIL originates
412 /// The FunctionSamples of the instruction (Machine or IR) associated to
413 /// \p DIL is the inlined instance in which that instruction is coming from.
414 /// We traverse the inline stack of that instruction, and match it with the
415 /// tree nodes in the profile.
417 /// \returns the FunctionSamples pointer to the inlined instance.
418 const FunctionSamples *findFunctionSamples(const DILocation *DIL) const;
421 /// Mangled name of the function.
424 /// Total number of samples collected inside this function.
426 /// Samples are cumulative, they include all the samples collected
427 /// inside this function and all its inlined callees.
428 uint64_t TotalSamples = 0;
430 /// Total number of samples collected at the head of the function.
431 /// This is an approximation of the number of calls made to this function
433 uint64_t TotalHeadSamples = 0;
435 /// Map instruction locations to collected samples.
437 /// Each entry in this map contains the number of samples
438 /// collected at the corresponding line offset. All line locations
439 /// are an offset from the start of the function.
440 BodySampleMap BodySamples;
442 /// Map call sites to collected samples for the called function.
444 /// Each entry in this map corresponds to all the samples
445 /// collected for the inlined function call at the given
446 /// location. For example, given:
454 /// If the bar() and baz() calls were inlined inside foo(), this
455 /// map will contain two entries. One for all the samples collected
456 /// in the call to bar() at line offset 1, the other for all the samples
457 /// collected in the call to baz() at line offset 8.
458 CallsiteSampleMap CallsiteSamples;
461 raw_ostream &operator<<(raw_ostream &OS, const FunctionSamples &FS);
463 /// Sort a LocationT->SampleT map by LocationT.
465 /// It produces a sorted list of <LocationT, SampleT> records by ascending
466 /// order of LocationT.
467 template <class LocationT, class SampleT> class SampleSorter {
469 using SamplesWithLoc = std::pair<const LocationT, SampleT>;
470 using SamplesWithLocList = SmallVector<const SamplesWithLoc *, 20>;
472 SampleSorter(const std::map<LocationT, SampleT> &Samples) {
473 for (const auto &I : Samples)
475 std::stable_sort(V.begin(), V.end(),
476 [](const SamplesWithLoc *A, const SamplesWithLoc *B) {
477 return A->first < B->first;
481 const SamplesWithLocList &get() const { return V; }
484 SamplesWithLocList V;
487 } // end namespace sampleprof
488 } // end namespace llvm
490 #endif // LLVM_PROFILEDATA_SAMPLEPROF_H