d7596d7b1b77340f924978caf5e9024c2957a5cf
[oota-llvm.git] / include / llvm / ProfileData / SampleProf.h
1 //=-- SampleProf.h - Sampling profiling format support --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains common definitions used in the reading and writing of
11 // sample profile data.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_PROFILEDATA_SAMPLEPROF_H_
16 #define LLVM_PROFILEDATA_SAMPLEPROF_H_
17
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorOr.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <system_error>
25
26 namespace llvm {
27
28 const std::error_category &sampleprof_category();
29
30 enum class sampleprof_error {
31   success = 0,
32   bad_magic,
33   unsupported_version,
34   too_large,
35   truncated,
36   malformed,
37   unrecognized_format,
38   unsupported_writing_format,
39   truncated_name_table,
40   not_implemented
41 };
42
43 inline std::error_code make_error_code(sampleprof_error E) {
44   return std::error_code(static_cast<int>(E), sampleprof_category());
45 }
46
47 } // end namespace llvm
48
49 namespace std {
50 template <>
51 struct is_error_code_enum<llvm::sampleprof_error> : std::true_type {};
52 }
53
54 namespace llvm {
55
56 namespace sampleprof {
57
58 static inline uint64_t SPMagic() {
59   return uint64_t('S') << (64 - 8) | uint64_t('P') << (64 - 16) |
60          uint64_t('R') << (64 - 24) | uint64_t('O') << (64 - 32) |
61          uint64_t('F') << (64 - 40) | uint64_t('4') << (64 - 48) |
62          uint64_t('2') << (64 - 56) | uint64_t(0xff);
63 }
64
65 static inline uint64_t SPVersion() { return 102; }
66
67 /// Represents the relative location of an instruction.
68 ///
69 /// Instruction locations are specified by the line offset from the
70 /// beginning of the function (marked by the line where the function
71 /// header is) and the discriminator value within that line.
72 ///
73 /// The discriminator value is useful to distinguish instructions
74 /// that are on the same line but belong to different basic blocks
75 /// (e.g., the two post-increment instructions in "if (p) x++; else y++;").
76 struct LineLocation {
77   LineLocation(uint32_t L, uint32_t D) : LineOffset(L), Discriminator(D) {}
78   void print(raw_ostream &OS) const;
79   void dump() const;
80
81   uint32_t LineOffset;
82   uint32_t Discriminator;
83 };
84
85 raw_ostream &operator<<(raw_ostream &OS, const LineLocation &Loc);
86
87 /// Represents the relative location of a callsite.
88 ///
89 /// Callsite locations are specified by the line offset from the
90 /// beginning of the function (marked by the line where the function
91 /// head is), the discriminator value within that line, and the callee
92 /// function name.
93 struct CallsiteLocation : public LineLocation {
94   CallsiteLocation(uint32_t L, uint32_t D, StringRef N)
95       : LineLocation(L, D), CalleeName(N) {}
96   void print(raw_ostream &OS) const;
97   void dump() const;
98
99   StringRef CalleeName;
100 };
101
102 raw_ostream &operator<<(raw_ostream &OS, const CallsiteLocation &Loc);
103
104 } // End namespace sampleprof
105
106 template <> struct DenseMapInfo<sampleprof::LineLocation> {
107   typedef DenseMapInfo<uint32_t> OffsetInfo;
108   typedef DenseMapInfo<uint32_t> DiscriminatorInfo;
109   static inline sampleprof::LineLocation getEmptyKey() {
110     return sampleprof::LineLocation(OffsetInfo::getEmptyKey(),
111                                     DiscriminatorInfo::getEmptyKey());
112   }
113   static inline sampleprof::LineLocation getTombstoneKey() {
114     return sampleprof::LineLocation(OffsetInfo::getTombstoneKey(),
115                                     DiscriminatorInfo::getTombstoneKey());
116   }
117   static inline unsigned getHashValue(sampleprof::LineLocation Val) {
118     return DenseMapInfo<std::pair<uint32_t, uint32_t>>::getHashValue(
119         std::pair<uint32_t, uint32_t>(Val.LineOffset, Val.Discriminator));
120   }
121   static inline bool isEqual(sampleprof::LineLocation LHS,
122                              sampleprof::LineLocation RHS) {
123     return LHS.LineOffset == RHS.LineOffset &&
124            LHS.Discriminator == RHS.Discriminator;
125   }
126 };
127
128 template <> struct DenseMapInfo<sampleprof::CallsiteLocation> {
129   typedef DenseMapInfo<uint32_t> OffsetInfo;
130   typedef DenseMapInfo<uint32_t> DiscriminatorInfo;
131   typedef DenseMapInfo<StringRef> CalleeNameInfo;
132   static inline sampleprof::CallsiteLocation getEmptyKey() {
133     return sampleprof::CallsiteLocation(OffsetInfo::getEmptyKey(),
134                                         DiscriminatorInfo::getEmptyKey(), "");
135   }
136   static inline sampleprof::CallsiteLocation getTombstoneKey() {
137     return sampleprof::CallsiteLocation(OffsetInfo::getTombstoneKey(),
138                                         DiscriminatorInfo::getTombstoneKey(),
139                                         "");
140   }
141   static inline unsigned getHashValue(sampleprof::CallsiteLocation Val) {
142     return DenseMapInfo<std::pair<uint32_t, uint32_t>>::getHashValue(
143         std::pair<uint32_t, uint32_t>(Val.LineOffset, Val.Discriminator));
144   }
145   static inline bool isEqual(sampleprof::CallsiteLocation LHS,
146                              sampleprof::CallsiteLocation RHS) {
147     return LHS.LineOffset == RHS.LineOffset &&
148            LHS.Discriminator == RHS.Discriminator &&
149            LHS.CalleeName.equals(RHS.CalleeName);
150   }
151 };
152
153 namespace sampleprof {
154
155 /// Representation of a single sample record.
156 ///
157 /// A sample record is represented by a positive integer value, which
158 /// indicates how frequently was the associated line location executed.
159 ///
160 /// Additionally, if the associated location contains a function call,
161 /// the record will hold a list of all the possible called targets. For
162 /// direct calls, this will be the exact function being invoked. For
163 /// indirect calls (function pointers, virtual table dispatch), this
164 /// will be a list of one or more functions.
165 class SampleRecord {
166 public:
167   typedef StringMap<uint64_t> CallTargetMap;
168
169   SampleRecord() : NumSamples(0), CallTargets() {}
170
171   /// Increment the number of samples for this record by \p S.
172   ///
173   /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
174   /// around unsigned integers.
175   void addSamples(uint64_t S) {
176     if (NumSamples <= std::numeric_limits<uint64_t>::max() - S)
177       NumSamples += S;
178     else
179       NumSamples = std::numeric_limits<uint64_t>::max();
180   }
181
182   /// Add called function \p F with samples \p S.
183   ///
184   /// Sample counts accumulate using saturating arithmetic, to avoid wrapping
185   /// around unsigned integers.
186   void addCalledTarget(StringRef F, uint64_t S) {
187     uint64_t &TargetSamples = CallTargets[F];
188     if (TargetSamples <= std::numeric_limits<uint64_t>::max() - S)
189       TargetSamples += S;
190     else
191       TargetSamples = std::numeric_limits<uint64_t>::max();
192   }
193
194   /// Return true if this sample record contains function calls.
195   bool hasCalls() const { return CallTargets.size() > 0; }
196
197   uint64_t getSamples() const { return NumSamples; }
198   const CallTargetMap &getCallTargets() const { return CallTargets; }
199
200   /// Merge the samples in \p Other into this record.
201   void merge(const SampleRecord &Other) {
202     addSamples(Other.getSamples());
203     for (const auto &I : Other.getCallTargets())
204       addCalledTarget(I.first(), I.second);
205   }
206
207   void print(raw_ostream &OS, unsigned Indent) const;
208   void dump() const;
209
210 private:
211   uint64_t NumSamples;
212   CallTargetMap CallTargets;
213 };
214
215 raw_ostream &operator<<(raw_ostream &OS, const SampleRecord &Sample);
216
217 typedef DenseMap<LineLocation, SampleRecord> BodySampleMap;
218 class FunctionSamples;
219 typedef DenseMap<CallsiteLocation, FunctionSamples> CallsiteSampleMap;
220
221 /// Representation of the samples collected for a function.
222 ///
223 /// This data structure contains all the collected samples for the body
224 /// of a function. Each sample corresponds to a LineLocation instance
225 /// within the body of the function.
226 class FunctionSamples {
227 public:
228   FunctionSamples() : TotalSamples(0), TotalHeadSamples(0) {}
229   void print(raw_ostream &OS = dbgs(), unsigned Indent = 0) const;
230   void dump() const;
231   void addTotalSamples(uint64_t Num) { TotalSamples += Num; }
232   void addHeadSamples(uint64_t Num) { TotalHeadSamples += Num; }
233   void addBodySamples(uint32_t LineOffset, uint32_t Discriminator,
234                       uint64_t Num) {
235     BodySamples[LineLocation(LineOffset, Discriminator)].addSamples(Num);
236   }
237   void addCalledTargetSamples(uint32_t LineOffset, uint32_t Discriminator,
238                               std::string FName, uint64_t Num) {
239     BodySamples[LineLocation(LineOffset, Discriminator)].addCalledTarget(FName,
240                                                                          Num);
241   }
242
243   /// Return the number of samples collected at the given location.
244   /// Each location is specified by \p LineOffset and \p Discriminator.
245   /// If the location is not found in profile, return error.
246   ErrorOr<uint64_t> findSamplesAt(uint32_t LineOffset,
247                                   uint32_t Discriminator) const {
248     const auto &ret = BodySamples.find(LineLocation(LineOffset, Discriminator));
249     if (ret == BodySamples.end())
250       return std::error_code();
251     else
252       return ret->second.getSamples();
253   }
254
255   /// Return the function samples at the given callsite location.
256   FunctionSamples &functionSamplesAt(const CallsiteLocation &Loc) {
257     return CallsiteSamples[Loc];
258   }
259
260   /// Return a pointer to function samples at the given callsite location.
261   const FunctionSamples *
262   findFunctionSamplesAt(const CallsiteLocation &Loc) const {
263     auto iter = CallsiteSamples.find(Loc);
264     if (iter == CallsiteSamples.end()) {
265       return nullptr;
266     } else {
267       return &iter->second;
268     }
269   }
270
271   bool empty() const { return TotalSamples == 0; }
272
273   /// Return the total number of samples collected inside the function.
274   uint64_t getTotalSamples() const { return TotalSamples; }
275
276   /// Return the total number of samples collected at the head of the
277   /// function.
278   uint64_t getHeadSamples() const { return TotalHeadSamples; }
279
280   /// Return all the samples collected in the body of the function.
281   const BodySampleMap &getBodySamples() const { return BodySamples; }
282
283   /// Return all the callsite samples collected in the body of the function.
284   const CallsiteSampleMap &getCallsiteSamples() const {
285     return CallsiteSamples;
286   }
287
288   /// Merge the samples in \p Other into this one.
289   void merge(const FunctionSamples &Other) {
290     addTotalSamples(Other.getTotalSamples());
291     addHeadSamples(Other.getHeadSamples());
292     for (const auto &I : Other.getBodySamples()) {
293       const LineLocation &Loc = I.first;
294       const SampleRecord &Rec = I.second;
295       BodySamples[Loc].merge(Rec);
296     }
297     for (const auto &I : Other.getCallsiteSamples()) {
298       const CallsiteLocation &Loc = I.first;
299       const FunctionSamples &Rec = I.second;
300       functionSamplesAt(Loc).merge(Rec);
301     }
302   }
303
304 private:
305   /// Total number of samples collected inside this function.
306   ///
307   /// Samples are cumulative, they include all the samples collected
308   /// inside this function and all its inlined callees.
309   uint64_t TotalSamples;
310
311   /// Total number of samples collected at the head of the function.
312   /// This is an approximation of the number of calls made to this function
313   /// at runtime.
314   uint64_t TotalHeadSamples;
315
316   /// Map instruction locations to collected samples.
317   ///
318   /// Each entry in this map contains the number of samples
319   /// collected at the corresponding line offset. All line locations
320   /// are an offset from the start of the function.
321   BodySampleMap BodySamples;
322
323   /// Map call sites to collected samples for the called function.
324   ///
325   /// Each entry in this map corresponds to all the samples
326   /// collected for the inlined function call at the given
327   /// location. For example, given:
328   ///
329   ///     void foo() {
330   ///  1    bar();
331   ///  ...
332   ///  8    baz();
333   ///     }
334   ///
335   /// If the bar() and baz() calls were inlined inside foo(), this
336   /// map will contain two entries.  One for all the samples collected
337   /// in the call to bar() at line offset 1, the other for all the samples
338   /// collected in the call to baz() at line offset 8.
339   CallsiteSampleMap CallsiteSamples;
340 };
341
342 raw_ostream &operator<<(raw_ostream &OS, const FunctionSamples &FS);
343
344 } // end namespace sampleprof
345
346 } // end namespace llvm
347
348 #endif // LLVM_PROFILEDATA_SAMPLEPROF_H_