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