98cb5b8e25a7a492e3530796429bc6ae1c7c18dc
[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 const std::error_category &instrprof_category();
160
161 enum class instrprof_error {
162   success = 0,
163   eof,
164   unrecognized_format,
165   bad_magic,
166   bad_header,
167   unsupported_version,
168   unsupported_hash_type,
169   too_large,
170   truncated,
171   malformed,
172   unknown_function,
173   hash_mismatch,
174   count_mismatch,
175   counter_overflow,
176   value_site_count_mismatch
177 };
178
179 inline std::error_code make_error_code(instrprof_error E) {
180   return std::error_code(static_cast<int>(E), instrprof_category());
181 }
182
183 enum InstrProfValueKind : uint32_t {
184 #define VALUE_PROF_KIND(Enumerator, Value) Enumerator = Value,
185 #include "llvm/ProfileData/InstrProfData.inc"
186 };
187
188 struct InstrProfStringTable {
189   // Set of string values in profiling data.
190   StringSet<> StringValueSet;
191   InstrProfStringTable() { StringValueSet.clear(); }
192   // Get a pointer to internal storage of a string in set
193   const char *getStringData(StringRef Str) {
194     auto Result = StringValueSet.find(Str);
195     return (Result == StringValueSet.end()) ? nullptr : Result->first().data();
196   }
197   // Insert a string to StringTable
198   const char *insertString(StringRef Str) {
199     auto Result = StringValueSet.insert(Str);
200     return Result.first->first().data();
201   }
202 };
203
204 struct InstrProfValueSiteRecord {
205   /// Value profiling data pairs at a given value site.
206   std::list<InstrProfValueData> ValueData;
207
208   InstrProfValueSiteRecord() { ValueData.clear(); }
209   template <class InputIterator>
210   InstrProfValueSiteRecord(InputIterator F, InputIterator L)
211       : ValueData(F, L) {}
212
213   /// Sort ValueData ascending by Value
214   void sortByTargetValues() {
215     ValueData.sort(
216         [](const InstrProfValueData &left, const InstrProfValueData &right) {
217           return left.Value < right.Value;
218         });
219   }
220
221   /// Merge data from another InstrProfValueSiteRecord
222   /// Optionally scale merged counts by \p Weight.
223   void mergeValueData(InstrProfValueSiteRecord &Input, uint64_t Weight = 1) {
224     this->sortByTargetValues();
225     Input.sortByTargetValues();
226     auto I = ValueData.begin();
227     auto IE = ValueData.end();
228     for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
229          ++J) {
230       while (I != IE && I->Value < J->Value)
231         ++I;
232       if (I != IE && I->Value == J->Value) {
233         // FIXME: Improve handling of counter overflow.
234         uint64_t JCount = J->Count;
235         bool Overflowed;
236         if (Weight > 1) {
237           JCount = SaturatingMultiply(JCount, Weight, &Overflowed);
238           assert(!Overflowed && "Value data counter overflowed!");
239         }
240         I->Count = SaturatingAdd(I->Count, JCount, &Overflowed);
241         assert(!Overflowed && "Value data counter overflowed!");
242         ++I;
243         continue;
244       }
245       ValueData.insert(I, *J);
246     }
247   }
248 };
249
250 /// Profiling information for a single function.
251 struct InstrProfRecord {
252   InstrProfRecord() {}
253   InstrProfRecord(StringRef Name, uint64_t Hash, std::vector<uint64_t> Counts)
254       : Name(Name), Hash(Hash), Counts(std::move(Counts)) {}
255   StringRef Name;
256   uint64_t Hash;
257   std::vector<uint64_t> Counts;
258
259   typedef std::vector<std::pair<uint64_t, const char *>> ValueMapType;
260
261   /// Return the number of value profile kinds with non-zero number
262   /// of profile sites.
263   inline uint32_t getNumValueKinds() const;
264   /// Return the number of instrumented sites for ValueKind.
265   inline uint32_t getNumValueSites(uint32_t ValueKind) const;
266   /// Return the total number of ValueData for ValueKind.
267   inline uint32_t getNumValueData(uint32_t ValueKind) const;
268   /// Return the number of value data collected for ValueKind at profiling
269   /// site: Site.
270   inline uint32_t getNumValueDataForSite(uint32_t ValueKind,
271                                          uint32_t Site) const;
272   /// Return the array of profiled values at \p Site.
273   inline std::unique_ptr<InstrProfValueData[]>
274   getValueForSite(uint32_t ValueKind, uint32_t Site,
275                   uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
276   inline void
277   getValueForSite(InstrProfValueData Dest[], uint32_t ValueKind, uint32_t Site,
278                   uint64_t (*ValueMapper)(uint32_t, uint64_t) = 0) const;
279   /// Reserve space for NumValueSites sites.
280   inline void reserveSites(uint32_t ValueKind, uint32_t NumValueSites);
281   /// Add ValueData for ValueKind at value Site.
282   inline void addValueData(uint32_t ValueKind, uint32_t Site,
283                            InstrProfValueData *VData, uint32_t N,
284                            ValueMapType *HashKeys);
285
286   /// Merge the counts in \p Other into this one.
287   /// Optionally scale merged counts by \p Weight.
288   inline instrprof_error merge(InstrProfRecord &Other, uint64_t Weight = 1);
289
290   /// Used by InstrProfWriter: update the value strings to commoned strings in
291   /// the writer instance.
292   inline void updateStrings(InstrProfStringTable *StrTab);
293
294   /// Clear value data entries
295   inline void clearValueData() {
296     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
297       getValueSitesForKind(Kind).clear();
298   }
299
300 private:
301   std::vector<InstrProfValueSiteRecord> IndirectCallSites;
302   const std::vector<InstrProfValueSiteRecord> &
303   getValueSitesForKind(uint32_t ValueKind) const {
304     switch (ValueKind) {
305     case IPVK_IndirectCallTarget:
306       return IndirectCallSites;
307     default:
308       llvm_unreachable("Unknown value kind!");
309     }
310     return IndirectCallSites;
311   }
312
313   std::vector<InstrProfValueSiteRecord> &
314   getValueSitesForKind(uint32_t ValueKind) {
315     return const_cast<std::vector<InstrProfValueSiteRecord> &>(
316         const_cast<const InstrProfRecord *>(this)
317             ->getValueSitesForKind(ValueKind));
318   }
319
320   // Map indirect call target name hash to name string.
321   uint64_t remapValue(uint64_t Value, uint32_t ValueKind,
322                       ValueMapType *HashKeys) {
323     if (!HashKeys)
324       return Value;
325     switch (ValueKind) {
326     case IPVK_IndirectCallTarget: {
327       auto Result =
328           std::lower_bound(HashKeys->begin(), HashKeys->end(), Value,
329                            [](const std::pair<uint64_t, const char *> &LHS,
330                               uint64_t RHS) { return LHS.first < RHS; });
331       if (Result != HashKeys->end())
332         Value = (uint64_t)Result->second;
333       break;
334     }
335     }
336     return Value;
337   }
338
339   // Merge Value Profile data from Src record to this record for ValueKind.
340   // Scale merged value counts by \p Weight.
341   instrprof_error mergeValueProfData(uint32_t ValueKind, InstrProfRecord &Src,
342                                      uint64_t Weight) {
343     uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
344     uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
345     if (ThisNumValueSites != OtherNumValueSites)
346       return instrprof_error::value_site_count_mismatch;
347     std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
348         getValueSitesForKind(ValueKind);
349     std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
350         Src.getValueSitesForKind(ValueKind);
351     for (uint32_t I = 0; I < ThisNumValueSites; I++)
352       ThisSiteRecords[I].mergeValueData(OtherSiteRecords[I], Weight);
353     return instrprof_error::success;
354   }
355 };
356
357 uint32_t InstrProfRecord::getNumValueKinds() const {
358   uint32_t NumValueKinds = 0;
359   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
360     NumValueKinds += !(getValueSitesForKind(Kind).empty());
361   return NumValueKinds;
362 }
363
364 uint32_t InstrProfRecord::getNumValueData(uint32_t ValueKind) const {
365   uint32_t N = 0;
366   const std::vector<InstrProfValueSiteRecord> &SiteRecords =
367       getValueSitesForKind(ValueKind);
368   for (auto &SR : SiteRecords) {
369     N += SR.ValueData.size();
370   }
371   return N;
372 }
373
374 uint32_t InstrProfRecord::getNumValueSites(uint32_t ValueKind) const {
375   return getValueSitesForKind(ValueKind).size();
376 }
377
378 uint32_t InstrProfRecord::getNumValueDataForSite(uint32_t ValueKind,
379                                                  uint32_t Site) const {
380   return getValueSitesForKind(ValueKind)[Site].ValueData.size();
381 }
382
383 std::unique_ptr<InstrProfValueData[]> InstrProfRecord::getValueForSite(
384     uint32_t ValueKind, uint32_t Site,
385     uint64_t (*ValueMapper)(uint32_t, uint64_t)) const {
386   uint32_t N = getNumValueDataForSite(ValueKind, Site);
387   if (N == 0)
388     return std::unique_ptr<InstrProfValueData[]>(nullptr);
389
390   auto VD = llvm::make_unique<InstrProfValueData[]>(N);
391   getValueForSite(VD.get(), ValueKind, Site, ValueMapper);
392
393   return VD;
394 }
395
396 void InstrProfRecord::getValueForSite(InstrProfValueData Dest[],
397                                       uint32_t ValueKind, uint32_t Site,
398                                       uint64_t (*ValueMapper)(uint32_t,
399                                                               uint64_t)) const {
400   uint32_t I = 0;
401   for (auto V : getValueSitesForKind(ValueKind)[Site].ValueData) {
402     Dest[I].Value = ValueMapper ? ValueMapper(ValueKind, V.Value) : V.Value;
403     Dest[I].Count = V.Count;
404     I++;
405   }
406 }
407
408 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
409                                    InstrProfValueData *VData, uint32_t N,
410                                    ValueMapType *HashKeys) {
411   for (uint32_t I = 0; I < N; I++) {
412     VData[I].Value = remapValue(VData[I].Value, ValueKind, HashKeys);
413   }
414   std::vector<InstrProfValueSiteRecord> &ValueSites =
415       getValueSitesForKind(ValueKind);
416   if (N == 0)
417     ValueSites.push_back(InstrProfValueSiteRecord());
418   else
419     ValueSites.emplace_back(VData, VData + N);
420 }
421
422 void InstrProfRecord::reserveSites(uint32_t ValueKind, uint32_t NumValueSites) {
423   std::vector<InstrProfValueSiteRecord> &ValueSites =
424       getValueSitesForKind(ValueKind);
425   ValueSites.reserve(NumValueSites);
426 }
427
428 void InstrProfRecord::updateStrings(InstrProfStringTable *StrTab) {
429   if (!StrTab)
430     return;
431
432   Name = StrTab->insertString(Name);
433   for (auto &VSite : IndirectCallSites)
434     for (auto &VData : VSite.ValueData)
435       VData.Value = (uint64_t)StrTab->insertString((const char *)VData.Value);
436 }
437
438 instrprof_error InstrProfRecord::merge(InstrProfRecord &Other,
439                                        uint64_t Weight) {
440   // If the number of counters doesn't match we either have bad data
441   // or a hash collision.
442   if (Counts.size() != Other.Counts.size())
443     return instrprof_error::count_mismatch;
444
445   instrprof_error Result = instrprof_error::success;
446
447   for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
448     bool Overflowed;
449     uint64_t OtherCount = Other.Counts[I];
450     if (Weight > 1) {
451       OtherCount = SaturatingMultiply(OtherCount, Weight, &Overflowed);
452       if (Overflowed)
453         Result = instrprof_error::counter_overflow;
454     }
455     Counts[I] = SaturatingAdd(Counts[I], OtherCount, &Overflowed);
456     if (Overflowed)
457       Result = instrprof_error::counter_overflow;
458   }
459
460   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
461     instrprof_error MergeValueResult = mergeValueProfData(Kind, Other, Weight);
462     if (MergeValueResult != instrprof_error::success)
463       Result = MergeValueResult;
464   }
465
466   return Result;
467 }
468
469 inline support::endianness getHostEndianness() {
470   return sys::IsLittleEndianHost ? support::little : support::big;
471 }
472
473
474 // Include definitions for value profile data
475 #define INSTR_PROF_VALUE_PROF_DATA
476 #include "llvm/ProfileData/InstrProfData.inc"
477
478  /*
479  * Initialize the record for runtime value profile data. 
480  * Return 0 if the initialization is successful, otherwise
481  * return 1.
482  */
483 int initializeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord,
484                                      const uint16_t *NumValueSites,
485                                      ValueProfNode **Nodes);
486
487 /* Release memory allocated for the runtime record.  */
488 void finalizeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord);
489
490 /* Return the size of ValueProfData structure that can be used to store
491    the value profile data collected at runtime. */
492 uint32_t getValueProfDataSizeRT(const ValueProfRuntimeRecord *Record);
493
494 /* Return a ValueProfData instance that stores the data collected at runtime. */
495 ValueProfData *
496 serializeValueProfDataFromRT(const ValueProfRuntimeRecord *Record,
497                              ValueProfData *Dst);
498
499 namespace IndexedInstrProf {
500
501 enum class HashT : uint32_t {
502   MD5,
503
504   Last = MD5
505 };
506
507 static inline uint64_t MD5Hash(StringRef Str) {
508   MD5 Hash;
509   Hash.update(Str);
510   llvm::MD5::MD5Result Result;
511   Hash.final(Result);
512   // Return the least significant 8 bytes. Our MD5 implementation returns the
513   // result in little endian, so we may need to swap bytes.
514   using namespace llvm::support;
515   return endian::read<uint64_t, little, unaligned>(Result);
516 }
517
518 static inline uint64_t ComputeHash(HashT Type, StringRef K) {
519   switch (Type) {
520   case HashT::MD5:
521     return IndexedInstrProf::MD5Hash(K);
522   }
523   llvm_unreachable("Unhandled hash type");
524 }
525
526 const uint64_t Magic = 0x8169666f72706cff; // "\xfflprofi\x81"
527 const uint64_t Version = INSTR_PROF_INDEX_VERSION;
528 const HashT HashType = HashT::MD5;
529
530 // This structure defines the file header of the LLVM profile
531 // data file in indexed-format.
532 struct Header {
533   uint64_t Magic;
534   uint64_t Version;
535   uint64_t MaxFunctionCount;
536   uint64_t HashType;
537   uint64_t HashOffset;
538 };
539
540 } // end namespace IndexedInstrProf
541
542 namespace RawInstrProf {
543
544 const uint64_t Version = INSTR_PROF_RAW_VERSION;
545
546 template <class IntPtrT> inline uint64_t getMagic();
547 template <> inline uint64_t getMagic<uint64_t>() {
548   return INSTR_PROF_RAW_MAGIC_64;
549 }
550
551 template <> inline uint64_t getMagic<uint32_t>() {
552   return INSTR_PROF_RAW_MAGIC_32;
553 }
554
555 // Per-function profile data header/control structure.
556 // The definition should match the structure defined in
557 // compiler-rt/lib/profile/InstrProfiling.h.
558 // It should also match the synthesized type in
559 // Transforms/Instrumentation/InstrProfiling.cpp:getOrCreateRegionCounters.
560 template <class IntPtrT> struct LLVM_ALIGNAS(8) ProfileData {
561   #define INSTR_PROF_DATA(Type, LLVMType, Name, Init) Type Name;
562   #include "llvm/ProfileData/InstrProfData.inc"
563 };
564
565 // File header structure of the LLVM profile data in raw format.
566 // The definition should match the header referenced in
567 // compiler-rt/lib/profile/InstrProfilingFile.c  and
568 // InstrProfilingBuffer.c.
569 struct Header {
570 #define INSTR_PROF_RAW_HEADER(Type, Name, Init) const Type Name;
571 #include "llvm/ProfileData/InstrProfData.inc"
572 };
573
574 }  // end namespace RawInstrProf
575
576 namespace coverage {
577
578 // Profile coverage map has the following layout:
579 // [CoverageMapFileHeader]
580 // [ArrayStart]
581 //  [CovMapFunctionRecord]
582 //  [CovMapFunctionRecord]
583 //  ...
584 // [ArrayEnd]
585 // [Encoded Region Mapping Data]
586 LLVM_PACKED_START
587 template <class IntPtrT> struct CovMapFunctionRecord {
588   #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Type Name;
589   #include "llvm/ProfileData/InstrProfData.inc"
590 };
591 LLVM_PACKED_END
592
593 }
594
595 } // end namespace llvm
596
597 namespace std {
598 template <>
599 struct is_error_code_enum<llvm::instrprof_error> : std::true_type {};
600 }
601
602 #endif // LLVM_PROFILEDATA_INSTRPROF_H_