[llvm-profdata] Add support for weighted merge of profile data
[oota-llvm.git] / include / llvm / ProfileData / InstrProf.h
1 //=-- InstrProf.h - Instrumented profiling format support ---------*- C++ -*-=//
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 // Instrumentation-based profiling data is generated by instrumented
11 // binaries through library functions in compiler-rt, and read by the clang
12 // frontend to feed PGO.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_PROFILEDATA_INSTRPROF_H_
17 #define LLVM_PROFILEDATA_INSTRPROF_H_
18
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/StringSet.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/IR/GlobalValue.h"
23 #include "llvm/ProfileData/InstrProfData.inc"
24 #include "llvm/Support/Endian.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/ErrorOr.h"
27 #include "llvm/Support/MD5.h"
28 #include <cstdint>
29 #include <list>
30 #include <system_error>
31 #include <vector>
32
33 namespace llvm {
34
35 class Function;
36 class GlobalVariable;
37 class Module;
38
39 /// Return the name of data section containing profile counter variables.
40 inline StringRef getInstrProfCountersSectionName(bool AddSegment) {
41   return AddSegment ? "__DATA," INSTR_PROF_CNTS_SECT_NAME_STR
42                     : INSTR_PROF_CNTS_SECT_NAME_STR;
43 }
44
45 /// Return the name of data section containing names of instrumented
46 /// functions.
47 inline StringRef getInstrProfNameSectionName(bool AddSegment) {
48   return AddSegment ? "__DATA," INSTR_PROF_NAME_SECT_NAME_STR
49                     : INSTR_PROF_NAME_SECT_NAME_STR;
50 }
51
52 /// Return the name of the data section containing per-function control
53 /// data.
54 inline StringRef getInstrProfDataSectionName(bool AddSegment) {
55   return AddSegment ? "__DATA," INSTR_PROF_DATA_SECT_NAME_STR
56                     : INSTR_PROF_DATA_SECT_NAME_STR;
57 }
58
59 /// Return the name profile runtime entry point to do value profiling
60 /// for a given site.
61 inline StringRef getInstrProfValueProfFuncName() {
62   return INSTR_PROF_VALUE_PROF_FUNC_STR;
63 }
64
65 /// Return the name of the section containing function coverage mapping
66 /// data.
67 inline StringRef getInstrProfCoverageSectionName(bool AddSegment) {
68   return AddSegment ? "__DATA,__llvm_covmap" : "__llvm_covmap";
69 }
70
71 /// Return the name prefix of variables containing instrumented function names.
72 inline StringRef getInstrProfNameVarPrefix() { return "__llvm_profile_name_"; }
73
74 /// Return the name prefix of variables containing per-function control data.
75 inline StringRef getInstrProfDataVarPrefix() { return "__llvm_profile_data_"; }
76
77 /// Return the name prefix of profile counter variables.
78 inline StringRef getInstrProfCountersVarPrefix() {
79   return "__llvm_profile_counters_";
80 }
81
82 /// Return the name prefix of the COMDAT group for instrumentation variables
83 /// associated with a COMDAT function.
84 inline StringRef getInstrProfComdatPrefix() { return "__llvm_profile_vars_"; }
85
86 /// Return the name of a covarage mapping variable (internal linkage)
87 /// for each instrumented source module. Such variables are allocated
88 /// in the __llvm_covmap section.
89 inline StringRef getCoverageMappingVarName() {
90   return "__llvm_coverage_mapping";
91 }
92
93 /// Return the name of function that registers all the per-function control
94 /// data at program startup time by calling __llvm_register_function. This
95 /// function has internal linkage and is called by  __llvm_profile_init
96 /// runtime method. This function is not generated for these platforms:
97 /// Darwin, Linux, and FreeBSD.
98 inline StringRef getInstrProfRegFuncsName() {
99   return "__llvm_profile_register_functions";
100 }
101
102 /// Return the name of the runtime interface that registers per-function control
103 /// data for one instrumented function.
104 inline StringRef getInstrProfRegFuncName() {
105   return "__llvm_profile_register_function";
106 }
107
108 /// Return the name of the runtime initialization method that is generated by
109 /// the compiler. The function calls __llvm_profile_register_functions and
110 /// __llvm_profile_override_default_filename functions if needed. This function
111 /// has internal linkage and invoked at startup time via init_array.
112 inline StringRef getInstrProfInitFuncName() { return "__llvm_profile_init"; }
113
114 /// Return the name of the hook variable defined in profile runtime library.
115 /// A reference to the variable causes the linker to link in the runtime
116 /// initialization module (which defines the hook variable).
117 inline StringRef getInstrProfRuntimeHookVarName() {
118   return "__llvm_profile_runtime";
119 }
120
121 /// Return the name of the compiler generated function that references the
122 /// runtime hook variable. The function is a weak global.
123 inline StringRef getInstrProfRuntimeHookVarUseFuncName() {
124   return "__llvm_profile_runtime_user";
125 }
126
127 /// Return the name of the profile runtime interface that overrides the default
128 /// profile data file name.
129 inline StringRef getInstrProfFileOverriderFuncName() {
130   return "__llvm_profile_override_default_filename";
131 }
132
133 /// Return the modified name for function \c F suitable to be
134 /// used the key for profile lookup.
135 std::string getPGOFuncName(const Function &F);
136
137 /// Return the modified name for a function suitable to be
138 /// used the key for profile lookup. The function's original
139 /// name is \c RawFuncName and has linkage of type \c Linkage.
140 /// The function is defined in module \c FileName.
141 std::string getPGOFuncName(StringRef RawFuncName,
142                            GlobalValue::LinkageTypes Linkage,
143                            StringRef FileName);
144
145 /// Create and return the global variable for function name used in PGO
146 /// instrumentation. \c FuncName is the name of the function returned
147 /// by \c getPGOFuncName call.
148 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName);
149
150 /// Create and return the global variable for function name used in PGO
151 /// instrumentation.  /// \c FuncName is the name of the function
152 /// returned by \c getPGOFuncName call, \c M is the owning module,
153 /// and \c Linkage is the linkage of the instrumented function.
154 GlobalVariable *createPGOFuncNameVar(Module &M,
155                                      GlobalValue::LinkageTypes Linkage,
156                                      StringRef FuncName);
157
158 const std::error_category &instrprof_category();
159
160 enum class instrprof_error {
161   success = 0,
162   eof,
163   unrecognized_format,
164   bad_magic,
165   bad_header,
166   unsupported_version,
167   unsupported_hash_type,
168   too_large,
169   truncated,
170   malformed,
171   unknown_function,
172   hash_mismatch,
173   count_mismatch,
174   counter_overflow,
175   value_site_count_mismatch
176 };
177
178 inline std::error_code make_error_code(instrprof_error E) {
179   return std::error_code(static_cast<int>(E), instrprof_category());
180 }
181
182 enum InstrProfValueKind : uint32_t {
183 #define VALUE_PROF_KIND(Enumerator, Value) Enumerator = Value,
184 #include "llvm/ProfileData/InstrProfData.inc"
185 };
186
187 struct InstrProfStringTable {
188   // Set of string values in profiling data.
189   StringSet<> StringValueSet;
190   InstrProfStringTable() { StringValueSet.clear(); }
191   // Get a pointer to internal storage of a string in set
192   const char *getStringData(StringRef Str) {
193     auto Result = StringValueSet.find(Str);
194     return (Result == StringValueSet.end()) ? nullptr : Result->first().data();
195   }
196   // Insert a string to StringTable
197   const char *insertString(StringRef Str) {
198     auto Result = StringValueSet.insert(Str);
199     return Result.first->first().data();
200   }
201 };
202
203 struct InstrProfValueSiteRecord {
204   /// Value profiling data pairs at a given value site.
205   std::list<InstrProfValueData> ValueData;
206
207   InstrProfValueSiteRecord() { ValueData.clear(); }
208   template <class InputIterator>
209   InstrProfValueSiteRecord(InputIterator F, InputIterator L)
210       : ValueData(F, L) {}
211
212   /// Sort ValueData ascending by Value
213   void sortByTargetValues() {
214     ValueData.sort(
215         [](const InstrProfValueData &left, const InstrProfValueData &right) {
216           return left.Value < right.Value;
217         });
218   }
219
220   /// Merge data from another InstrProfValueSiteRecord
221   /// Optionally scale merged counts by \p Weight.
222   void mergeValueData(InstrProfValueSiteRecord &Input, uint64_t Weight = 1) {
223     this->sortByTargetValues();
224     Input.sortByTargetValues();
225     auto I = ValueData.begin();
226     auto IE = ValueData.end();
227     for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
228          ++J) {
229       while (I != IE && I->Value < J->Value)
230         ++I;
231       if (I != IE && I->Value == J->Value) {
232         // TODO: Check for counter overflow and return error if it occurs.
233         uint64_t JCount = J->Count;
234         if (Weight > 1)
235           JCount = SaturatingMultiply(JCount, Weight);
236         I->Count = SaturatingAdd(I->Count, JCount);
237         ++I;
238         continue;
239       }
240       ValueData.insert(I, *J);
241     }
242   }
243 };
244
245 /// Profiling information for a single function.
246 struct InstrProfRecord {
247   InstrProfRecord() {}
248   InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
249       : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
250   StringRef Name;
251   uint64_t Hash;
252   std::vector<uint64_t> Counts;
253
254   typedef std::vector<std::pair<uint64_t, const char *>> ValueMapType;
255
256   /// Return the number of value profile kinds with non-zero number
257   /// of profile sites.
258   inline uint32_t getNumValueKinds() const;
259   /// Return the number of instrumented sites for ValueKind.
260   inline uint32_t getNumValueSites(uint32_t ValueKind) const;
261   /// Return the total number of ValueData for ValueKind.
262   inline uint32_t getNumValueData(uint32_t ValueKind) const;
263   /// Return the number of value data collected for ValueKind at profiling
264   /// site: Site.
265   inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
266                                          uint32_t Site) const;
267   /// Return the array of profiled values at \p Site.
268   inline std::unique_ptr<InstrProfValueData[]>
269   getValueForSite(uint32_t ValueKind, uint32_t Site,
270                   uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
271   inline void
272   getValueForSite(InstrProfValueData Dest[], uint32_t ValueKind, uint32_t Site,
273                   uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
274   /// Reserve space for NumValueSites sites.
275   inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
276   /// Add ValueData for ValueKind at value Site.
277   inline void addValueData(uint32_t ValueKind, uint32_t Site,
278                            InstrProfValueData *VData, uint32_t N,
279                            ValueMapType *HashKeys);
280
281   /// Merge the counts in \p Other into this one.
282   /// Optionally scale merged counts by \p Weight.
283   inline instrprof_error merge(InstrProfRecord &Other, uint64_t Weight = 1);
284
285   /// Used by InstrProfWriter: update the value strings to commoned strings in
286   /// the writer instance.
287   inline void updateStrings(InstrProfStringTable *StrTab);
288
289   /// Clear value data entries
290   inline void clearValueData() {
291     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
292       getValueSitesForKind(Kind).clear();
293   }
294
295 private:
296   std::vector<InstrProfValueSiteRecord> IndirectCallSites;
297   const std::vector<InstrProfValueSiteRecord> &
298   getValueSitesForKind(uint32_t ValueKind) const {
299     switch (ValueKind) {
300     case IPVK_IndirectCallTarget:
301       return IndirectCallSites;
302     default:
303       llvm_unreachable("Unknown value kind!");
304     }
305     return IndirectCallSites;
306   }
307
308   std::vector<InstrProfValueSiteRecord> &
309   getValueSitesForKind(uint32_t ValueKind) {
310     return const_cast<std::vector<InstrProfValueSiteRecord> &>(
311         const_cast<const InstrProfRecord *>(this)
312             ->getValueSitesForKind(ValueKind));
313   }
314
315   // Map indirect call target name hash to name string.
316   uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
317                       ValueMapType *HashKeys) {
318     if (!HashKeys)
319       return Value;
320     switch (ValueKind) {
321     case IPVK_IndirectCallTarget: {
322       auto Result =
323           std::lower_bound(HashKeys->begin(), HashKeys->end(), Value,
324                            [](const std::pair<uint64_t, const char *> &LHS,
325                               uint64_t RHS) { return LHS.first < RHS; });
326       if (Result != HashKeys->end())
327         Value = (uint64_t)Result->second;
328       break;
329     }
330     }
331     return Value;
332   }
333
334   // Merge Value Profile data from Src record to this record for ValueKind.
335   // Scale merged value counts by \p Weight.
336   instrprof_error mergeValueProfData(uint32_t ValueKind, InstrProfRecord &Src,
337                                      uint64_t Weight) {
338     uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
339     uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
340     if (ThisNumValueSites != OtherNumValueSites)
341       return instrprof_error::value_site_count_mismatch;
342     std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
343         getValueSitesForKind(ValueKind);
344     std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
345         Src.getValueSitesForKind(ValueKind);
346     for (uint32_t I = 0; I < ThisNumValueSites; I++)
347       ThisSiteRecords[I].mergeValueData(OtherSiteRecords[I], Weight);
348     return instrprof_error::success;
349   }
350 };
351
352 uint32_t InstrProfRecord::getNumValueKinds() const {
353   uint32_t NumValueKinds = 0;
354   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
355     NumValueKinds += !(getValueSitesForKind(Kind).empty());
356   return NumValueKinds;
357 }
358
359 uint32_t InstrProfRecord::getNumValueData(uint32_t ValueKind) const {
360   uint32_t N = 0;
361   const std::vector<InstrProfValueSiteRecord> &SiteRecords =
362       getValueSitesForKind(ValueKind);
363   for (auto &SR : SiteRecords) {
364     N += SR.ValueData.size();
365   }
366   return N;
367 }
368
369 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
370   return getValueSitesForKind(ValueKind).size();
371 }
372
373 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
374                                                  uint32_t Site) const {
375   return getValueSitesForKind(ValueKind)[Site].ValueData.size();
376 }
377
378 std::unique_ptr<InstrProfValueData[]> InstrProfRecord::getValueForSite(
379     uint32_t ValueKind, uint32_t Site,
380     uint64_t (*ValueMapper)(uint32_t, uint64_t)) const {
381   uint32_t N = getNumValueDataForSite(ValueKind, Site);
382   if (N == 0)
383     return std::unique_ptr<InstrProfValueData[]>(nullptr);
384
385   auto VD = llvm::make_unique<InstrProfValueData[]>(N);
386   getValueForSite(VD.get(), ValueKind, Site, ValueMapper);
387
388   return VD;
389 }
390
391 void InstrProfRecord::getValueForSite(InstrProfValueData Dest[],
392                                       uint32_t ValueKind, uint32_t Site,
393                                       uint64_t (*ValueMapper)(uint32_t,
394                                                               uint64_t)) const {
395   uint32_t I = 0;
396   for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
397     Dest[I].Value = ValueMapper ? ValueMapper(ValueKind, V.Value) : V.Value;
398     Dest[I].Count = V.Count;
399     I++;
400   }
401 }
402
403 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
404                                    InstrProfValueData *VData, uint32_t N,
405                                    ValueMapType *HashKeys) {
406   for (uint32_t I = 0; I < N; I++) {
407     VData[I].Value = remapValue(VData[I].Value, ValueKind, HashKeys);
408   }
409   std::vector<InstrProfValueSiteRecord> &ValueSites =
410       getValueSitesForKind(ValueKind);
411   if (N == 0)
412     ValueSites.push_back(InstrProfValueSiteRecord());
413   else
414     ValueSites.emplace_back(VData, VData + N);
415 }
416
417 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
418   std::vector<InstrProfValueSiteRecord> &ValueSites =
419       getValueSitesForKind(ValueKind);
420   ValueSites.reserve(NumValueSites);
421 }
422
423 void InstrProfRecord::updateStrings(InstrProfStringTable *StrTab) {
424   if (!StrTab)
425     return;
426
427   Name = StrTab->insertString(Name);
428   for (auto &VSite : IndirectCallSites)
429     for (auto &VData : VSite.ValueData)
430       VData.Value = (uint64_t)StrTab->insertString((const char *)VData.Value);
431 }
432
433 instrprof_error InstrProfRecord::merge(InstrProfRecord &Other,
434                                        uint64_t Weight) {
435   // If the number of counters doesn't match we either have bad data
436   // or a hash collision.
437   if (Counts.size() != Other.Counts.size())
438     return instrprof_error::count_mismatch;
439
440   instrprof_error Result = instrprof_error::success;
441
442   for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
443     bool ResultOverflowed;
444     uint64_t OtherCount = Other.Counts[I];
445     if (Weight > 1) {
446       OtherCount = SaturatingMultiply(OtherCount, Weight, ResultOverflowed);
447       if (ResultOverflowed)
448         Result = instrprof_error::counter_overflow;
449     }
450     Counts[I] = SaturatingAdd(Counts[I], OtherCount, ResultOverflowed);
451     if (ResultOverflowed)
452       Result = instrprof_error::counter_overflow;
453   }
454
455   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
456     instrprof_error MergeValueResult = mergeValueProfData(Kind, Other, Weight);
457     if (MergeValueResult != instrprof_error::success)
458       Result = MergeValueResult;
459   }
460
461   return Result;
462 }
463
464 inline support::endianness getHostEndianness() {
465   return sys::IsLittleEndianHost ? support::little : support::big;
466 }
467
468
469 // Include definitions for value profile data
470 #define INSTR_PROF_VALUE_PROF_DATA
471 #include "llvm/ProfileData/InstrProfData.inc"
472
473  /*
474  * Initialize the record for runtime value profile data. 
475  * Return 0 if the initialization is successful, otherwise
476  * return 1.
477  */
478 int initializeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord,
479                                      const uint16_t *NumValueSites,
480                                      ValueProfNode **Nodes);
481
482 /* Release memory allocated for the runtime record.  */
483 void finalizeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord);
484
485 /* Return the size of ValueProfData structure that can be used to store
486    the value profile data collected at runtime. */
487 uint32_t getValueProfDataSizeRT(const ValueProfRuntimeRecord *Record);
488
489 /* Return a ValueProfData instance that stores the data collected at runtime. */
490 ValueProfData *
491 serializeValueProfDataFromRT(const ValueProfRuntimeRecord *Record,
492                              ValueProfData *Dst);
493
494 namespace IndexedInstrProf {
495
496 enum class HashT : uint32_t {
497   MD5,
498
499   Last = MD5
500 };
501
502 static inline uint64_t MD5Hash(StringRef Str) {
503   MD5 Hash;
504   Hash.update(Str);
505   llvm::MD5::MD5Result Result;
506   Hash.final(Result);
507   // Return the least significant 8 bytes. Our MD5 implementation returns the
508   // result in little endian, so we may need to swap bytes.
509   using namespace llvm::support;
510   return endian::read<uint64_t, little, unaligned>(Result);
511 }
512
513 static inline uint64_t ComputeHash(HashT Type, StringRef K) {
514   switch (Type) {
515   case HashT::MD5:
516     return IndexedInstrProf::MD5Hash(K);
517   }
518   llvm_unreachable("Unhandled hash type");
519 }
520
521 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
522 const uint64_t Version = 3;
523 const HashT HashType = HashT::MD5;
524
525 // This structure defines the file header of the LLVM profile
526 // data file in indexed-format.
527 struct Header {
528   uint64_t Magic;
529   uint64_t Version;
530   uint64_t MaxFunctionCount;
531   uint64_t HashType;
532   uint64_t HashOffset;
533 };
534
535 } // end namespace IndexedInstrProf
536
537 namespace RawInstrProf {
538
539 const uint64_t Version = INSTR_PROF_RAW_VERSION;
540
541 template <class IntPtrT> inline uint64_t getMagic();
542 template <> inline uint64_t getMagic<uint64_t>() {
543   return INSTR_PROF_RAW_MAGIC_64;
544 }
545
546 template <> inline uint64_t getMagic<uint32_t>() {
547   return INSTR_PROF_RAW_MAGIC_32;
548 }
549
550 // Per-function profile data header/control structure.
551 // The definition should match the structure defined in
552 // compiler-rt/lib/profile/InstrProfiling.h.
553 // It should also match the synthesized type in
554 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
555 template <class IntPtrT> struct LLVM_ALIGNAS(8) ProfileData {
556   #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
557   #include "llvm/ProfileData/InstrProfData.inc"
558 };
559
560 // File header structure of the LLVM profile data in raw format.
561 // The definition should match the header referenced in
562 // compiler-rt/lib/profile/InstrProfilingFile.c  and
563 // InstrProfilingBuffer.c.
564 struct Header {
565 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
566 #include "llvm/ProfileData/InstrProfData.inc"
567 };
568
569 }  // end namespace RawInstrProf
570
571 namespace coverage {
572
573 // Profile coverage map has the following layout:
574 // [CoverageMapFileHeader]
575 // [ArrayStart]
576 //  [CovMapFunctionRecord]
577 //  [CovMapFunctionRecord]
578 //  ...
579 // [ArrayEnd]
580 // [Encoded Region Mapping Data]
581 LLVM_PACKED_START
582 template <class IntPtrT> struct CovMapFunctionRecord {
583   #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Type Name;
584   #include "llvm/ProfileData/InstrProfData.inc"
585 };
586 LLVM_PACKED_END
587
588 }
589
590 } // end namespace llvm
591
592 namespace std {
593 template <>
594 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
595 }
596
597 #endif // LLVM_PROFILEDATA_INSTRPROF_H_