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