[PGO] Cleanup: Move large member functions out of line (NFC)
[oota-llvm.git] / lib / ProfileData / InstrProf.cpp
1 //=-- InstrProf.cpp - Instrumented profiling format support -----------------=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for clang's instrumentation based PGO and
11 // coverage.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/IR/Constants.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/IR/Module.h"
18 #include "llvm/IR/GlobalVariable.h"
19 #include "llvm/ProfileData/InstrProf.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/ManagedStatic.h"
22
23 using namespace llvm;
24
25 namespace {
26 class InstrProfErrorCategoryType : public std::error_category {
27   const char *name() const LLVM_NOEXCEPT override { return "llvm.instrprof"; }
28   std::string message(int IE) const override {
29     instrprof_error E = static_cast<instrprof_error>(IE);
30     switch (E) {
31     case instrprof_error::success:
32       return "Success";
33     case instrprof_error::eof:
34       return "End of File";
35     case instrprof_error::unrecognized_format:
36       return "Unrecognized instrumentation profile encoding format";
37     case instrprof_error::bad_magic:
38       return "Invalid instrumentation profile data (bad magic)";
39     case instrprof_error::bad_header:
40       return "Invalid instrumentation profile data (file header is corrupt)";
41     case instrprof_error::unsupported_version:
42       return "Unsupported instrumentation profile format version";
43     case instrprof_error::unsupported_hash_type:
44       return "Unsupported instrumentation profile hash type";
45     case instrprof_error::too_large:
46       return "Too much profile data";
47     case instrprof_error::truncated:
48       return "Truncated profile data";
49     case instrprof_error::malformed:
50       return "Malformed instrumentation profile data";
51     case instrprof_error::unknown_function:
52       return "No profile data available for function";
53     case instrprof_error::hash_mismatch:
54       return "Function control flow change detected (hash mismatch)";
55     case instrprof_error::count_mismatch:
56       return "Function basic block count change detected (counter mismatch)";
57     case instrprof_error::counter_overflow:
58       return "Counter overflow";
59     case instrprof_error::value_site_count_mismatch:
60       return "Function value site count change detected (counter mismatch)";
61     }
62     llvm_unreachable("A value of instrprof_error has no message.");
63   }
64 };
65 }
66
67 static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
68
69 const std::error_category &llvm::instrprof_category() {
70   return *ErrorCategory;
71 }
72
73 namespace llvm {
74
75 std::string getPGOFuncName(StringRef RawFuncName,
76                            GlobalValue::LinkageTypes Linkage,
77                            StringRef FileName,
78                            uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
79
80   // Function names may be prefixed with a binary '1' to indicate
81   // that the backend should not modify the symbols due to any platform
82   // naming convention. Do not include that '1' in the PGO profile name.
83   if (RawFuncName[0] == '\1')
84     RawFuncName = RawFuncName.substr(1);
85
86   std::string FuncName = RawFuncName;
87   if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
88     // For local symbols, prepend the main file name to distinguish them.
89     // Do not include the full path in the file name since there's no guarantee
90     // that it will stay the same, e.g., if the files are checked out from
91     // version control in different locations.
92     if (FileName.empty())
93       FuncName = FuncName.insert(0, "<unknown>:");
94     else
95       FuncName = FuncName.insert(0, FileName.str() + ":");
96   }
97   return FuncName;
98 }
99
100 std::string getPGOFuncName(const Function &F, uint64_t Version) {
101   return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName(),
102                         Version);
103 }
104
105 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
106   if (FileName.empty())
107     return PGOFuncName;
108   // Drop the file name including ':'. See also getPGOFuncName.
109   if (PGOFuncName.startswith(FileName))
110     PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
111   return PGOFuncName;
112 }
113
114 // \p FuncName is the string used as profile lookup key for the function. A
115 // symbol is created to hold the name. Return the legalized symbol name.
116 static std::string getPGOFuncNameVarName(StringRef FuncName,
117                                          GlobalValue::LinkageTypes Linkage) {
118   std::string VarName = getInstrProfNameVarPrefix();
119   VarName += FuncName;
120
121   if (!GlobalValue::isLocalLinkage(Linkage))
122     return VarName;
123
124   // Now fix up illegal chars in local VarName that may upset the assembler.
125   const char *InvalidChars = "-:<>\"'";
126   size_t found = VarName.find_first_of(InvalidChars);
127   while (found != std::string::npos) {
128     VarName[found] = '_';
129     found = VarName.find_first_of(InvalidChars, found + 1);
130   }
131   return VarName;
132 }
133
134 GlobalVariable *createPGOFuncNameVar(Module &M,
135                                      GlobalValue::LinkageTypes Linkage,
136                                      StringRef FuncName) {
137
138   // We generally want to match the function's linkage, but available_externally
139   // and extern_weak both have the wrong semantics, and anything that doesn't
140   // need to link across compilation units doesn't need to be visible at all.
141   if (Linkage == GlobalValue::ExternalWeakLinkage)
142     Linkage = GlobalValue::LinkOnceAnyLinkage;
143   else if (Linkage == GlobalValue::AvailableExternallyLinkage)
144     Linkage = GlobalValue::LinkOnceODRLinkage;
145   else if (Linkage == GlobalValue::InternalLinkage ||
146            Linkage == GlobalValue::ExternalLinkage)
147     Linkage = GlobalValue::PrivateLinkage;
148
149   auto *Value = ConstantDataArray::getString(M.getContext(), FuncName, false);
150   auto FuncNameVar =
151       new GlobalVariable(M, Value->getType(), true, Linkage, Value,
152                          getPGOFuncNameVarName(FuncName, Linkage));
153
154   // Hide the symbol so that we correctly get a copy for each executable.
155   if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
156     FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
157
158   return FuncNameVar;
159 }
160
161 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName) {
162   return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), FuncName);
163 }
164
165 // Merge Value Profile data from Src record to this record for ValueKind.
166 // Scale merged value counts by \p Weight.
167 instrprof_error InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
168                                                     InstrProfRecord &Src,
169                                                     uint64_t Weight) {
170   uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
171   uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
172   if (ThisNumValueSites != OtherNumValueSites)
173     return instrprof_error::value_site_count_mismatch;
174   std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
175       getValueSitesForKind(ValueKind);
176   std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
177       Src.getValueSitesForKind(ValueKind);
178   instrprof_error Result = instrprof_error::success;
179   for (uint32_t I = 0; I < ThisNumValueSites; I++)
180     MergeResult(Result,
181                 ThisSiteRecords[I].mergeValueData(OtherSiteRecords[I], Weight));
182   return Result;
183 }
184
185 instrprof_error InstrProfRecord::merge(InstrProfRecord &Other,
186                                        uint64_t Weight) {
187   // If the number of counters doesn't match we either have bad data
188   // or a hash collision.
189   if (Counts.size() != Other.Counts.size())
190     return instrprof_error::count_mismatch;
191
192   instrprof_error Result = instrprof_error::success;
193
194   for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
195     bool Overflowed;
196     uint64_t OtherCount = Other.Counts[I];
197     if (Weight > 1) {
198       OtherCount = SaturatingMultiply(OtherCount, Weight, &Overflowed);
199       if (Overflowed)
200         Result = instrprof_error::counter_overflow;
201     }
202     Counts[I] = SaturatingAdd(Counts[I], OtherCount, &Overflowed);
203     if (Overflowed)
204       Result = instrprof_error::counter_overflow;
205   }
206
207   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
208     MergeResult(Result, mergeValueProfData(Kind, Other, Weight));
209
210   return Result;
211 }
212 // Map indirect call target name hash to name string.
213 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
214                                      ValueMapType *HashKeys) {
215   if (!HashKeys)
216     return Value;
217   switch (ValueKind) {
218   case IPVK_IndirectCallTarget: {
219     auto Result =
220         std::lower_bound(HashKeys->begin(), HashKeys->end(), Value,
221                          [](const std::pair<uint64_t, const char *> &LHS,
222                             uint64_t RHS) { return LHS.first < RHS; });
223     if (Result != HashKeys->end())
224       Value = (uint64_t)Result->second;
225     break;
226   }
227   }
228   return Value;
229 }
230
231 void InstrProfRecord::updateStrings(InstrProfStringTable *StrTab) {
232   if (!StrTab)
233     return;
234
235   Name = StrTab->insertString(Name);
236   for (auto &VSite : IndirectCallSites)
237     for (auto &VData : VSite.ValueData)
238       VData.Value = (uint64_t)StrTab->insertString((const char *)VData.Value);
239 }
240
241 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
242                                    InstrProfValueData *VData, uint32_t N,
243                                    ValueMapType *HashKeys) {
244   for (uint32_t I = 0; I < N; I++) {
245     VData[I].Value = remapValue(VData[I].Value, ValueKind, HashKeys);
246   }
247   std::vector<InstrProfValueSiteRecord> &ValueSites =
248       getValueSitesForKind(ValueKind);
249   if (N == 0)
250     ValueSites.push_back(InstrProfValueSiteRecord());
251   else
252     ValueSites.emplace_back(VData, VData + N);
253 }
254
255 #define INSTR_PROF_COMMON_API_IMPL
256 #include "llvm/ProfileData/InstrProfData.inc"
257
258 /*!
259  * \brief ValueProfRecordClosure Interface implementation for  InstrProfRecord
260  *  class. These C wrappers are used as adaptors so that C++ code can be
261  *  invoked as callbacks.
262  */
263 uint32_t getNumValueKindsInstrProf(const void *Record) {
264   return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
265 }
266
267 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
268   return reinterpret_cast<const InstrProfRecord *>(Record)
269       ->getNumValueSites(VKind);
270 }
271
272 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
273   return reinterpret_cast<const InstrProfRecord *>(Record)
274       ->getNumValueData(VKind);
275 }
276
277 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
278                                          uint32_t S) {
279   return reinterpret_cast<const InstrProfRecord *>(R)
280       ->getNumValueDataForSite(VK, S);
281 }
282
283 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
284                               uint32_t K, uint32_t S,
285                               uint64_t (*Mapper)(uint32_t, uint64_t)) {
286   return reinterpret_cast<const InstrProfRecord *>(R)
287       ->getValueForSite(Dst, K, S, Mapper);
288 }
289
290 uint64_t stringToHash(uint32_t ValueKind, uint64_t Value) {
291   switch (ValueKind) {
292   case IPVK_IndirectCallTarget:
293     return IndexedInstrProf::ComputeHash((const char *)Value);
294     break;
295   default:
296     llvm_unreachable("value kind not handled !");
297   }
298   return Value;
299 }
300
301 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
302   ValueProfData *VD =
303       (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
304   memset(VD, 0, TotalSizeInBytes);
305   return VD;
306 }
307
308 static ValueProfRecordClosure InstrProfRecordClosure = {
309     0,
310     getNumValueKindsInstrProf,
311     getNumValueSitesInstrProf,
312     getNumValueDataInstrProf,
313     getNumValueDataForSiteInstrProf,
314     stringToHash,
315     getValueForSiteInstrProf,
316     allocValueProfDataInstrProf};
317
318 // Wrapper implementation using the closure mechanism.
319 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
320   InstrProfRecordClosure.Record = &Record;
321   return getValueProfDataSize(&InstrProfRecordClosure);
322 }
323
324 // Wrapper implementation using the closure mechanism.
325 std::unique_ptr<ValueProfData>
326 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
327   InstrProfRecordClosure.Record = &Record;
328
329   std::unique_ptr<ValueProfData> VPD(
330       serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
331   return VPD;
332 }
333
334 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
335                                     InstrProfRecord::ValueMapType *VMap) {
336   Record.reserveSites(Kind, NumValueSites);
337
338   InstrProfValueData *ValueData = getValueProfRecordValueData(this);
339   for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
340     uint8_t ValueDataCount = this->SiteCountArray[VSite];
341     Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
342     ValueData += ValueDataCount;
343   }
344 }
345
346 // For writing/serializing,  Old is the host endianness, and  New is
347 // byte order intended on disk. For Reading/deserialization, Old
348 // is the on-disk source endianness, and New is the host endianness.
349 void ValueProfRecord::swapBytes(support::endianness Old,
350                                 support::endianness New) {
351   using namespace support;
352   if (Old == New)
353     return;
354
355   if (getHostEndianness() != Old) {
356     sys::swapByteOrder<uint32_t>(NumValueSites);
357     sys::swapByteOrder<uint32_t>(Kind);
358   }
359   uint32_t ND = getValueProfRecordNumValueData(this);
360   InstrProfValueData *VD = getValueProfRecordValueData(this);
361
362   // No need to swap byte array: SiteCountArrray.
363   for (uint32_t I = 0; I < ND; I++) {
364     sys::swapByteOrder<uint64_t>(VD[I].Value);
365     sys::swapByteOrder<uint64_t>(VD[I].Count);
366   }
367   if (getHostEndianness() == Old) {
368     sys::swapByteOrder<uint32_t>(NumValueSites);
369     sys::swapByteOrder<uint32_t>(Kind);
370   }
371 }
372
373 void ValueProfData::deserializeTo(InstrProfRecord &Record,
374                                   InstrProfRecord::ValueMapType *VMap) {
375   if (NumValueKinds == 0)
376     return;
377
378   ValueProfRecord *VR = getFirstValueProfRecord(this);
379   for (uint32_t K = 0; K < NumValueKinds; K++) {
380     VR->deserializeTo(Record, VMap);
381     VR = getValueProfRecordNext(VR);
382   }
383 }
384
385 template <class T>
386 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
387   using namespace support;
388   if (Orig == little)
389     return endian::readNext<T, little, unaligned>(D);
390   else
391     return endian::readNext<T, big, unaligned>(D);
392 }
393
394 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
395   return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
396                                             ValueProfData());
397 }
398
399 instrprof_error ValueProfData::checkIntegrity() {
400   if (NumValueKinds > IPVK_Last + 1)
401     return instrprof_error::malformed;
402   // Total size needs to be mulltiple of quadword size.
403   if (TotalSize % sizeof(uint64_t))
404     return instrprof_error::malformed;
405
406   ValueProfRecord *VR = getFirstValueProfRecord(this);
407   for (uint32_t K = 0; K < this->NumValueKinds; K++) {
408     if (VR->Kind > IPVK_Last)
409       return instrprof_error::malformed;
410     VR = getValueProfRecordNext(VR);
411     if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
412       return instrprof_error::malformed;
413   }
414   return instrprof_error::success;
415 }
416
417 ErrorOr<std::unique_ptr<ValueProfData>>
418 ValueProfData::getValueProfData(const unsigned char *D,
419                                 const unsigned char *const BufferEnd,
420                                 support::endianness Endianness) {
421   using namespace support;
422   if (D + sizeof(ValueProfData) > BufferEnd)
423     return instrprof_error::truncated;
424
425   const unsigned char *Header = D;
426   uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
427   if (D + TotalSize > BufferEnd)
428     return instrprof_error::too_large;
429
430   std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
431   memcpy(VPD.get(), D, TotalSize);
432   // Byte swap.
433   VPD->swapBytesToHost(Endianness);
434
435   instrprof_error EC = VPD->checkIntegrity();
436   if (EC != instrprof_error::success)
437     return EC;
438
439   return std::move(VPD);
440 }
441
442 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
443   using namespace support;
444   if (Endianness == getHostEndianness())
445     return;
446
447   sys::swapByteOrder<uint32_t>(TotalSize);
448   sys::swapByteOrder<uint32_t>(NumValueKinds);
449
450   ValueProfRecord *VR = getFirstValueProfRecord(this);
451   for (uint32_t K = 0; K < NumValueKinds; K++) {
452     VR->swapBytes(Endianness, getHostEndianness());
453     VR = getValueProfRecordNext(VR);
454   }
455 }
456
457 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
458   using namespace support;
459   if (Endianness == getHostEndianness())
460     return;
461
462   ValueProfRecord *VR = getFirstValueProfRecord(this);
463   for (uint32_t K = 0; K < NumValueKinds; K++) {
464     ValueProfRecord *NVR = getValueProfRecordNext(VR);
465     VR->swapBytes(getHostEndianness(), Endianness);
466     VR = NVR;
467   }
468   sys::swapByteOrder<uint32_t>(TotalSize);
469   sys::swapByteOrder<uint32_t>(NumValueKinds);
470 }
471
472 }