[PGO] Convert InstrProfRecord based serialization methods to use common C methods
[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
79   // Function names may be prefixed with a binary '1' to indicate
80   // that the backend should not modify the symbols due to any platform
81   // naming convention. Do not include that '1' in the PGO profile name.
82   if (RawFuncName[0] == '\1')
83     RawFuncName = RawFuncName.substr(1);
84
85   std::string FuncName = RawFuncName;
86   if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
87     // For local symbols, prepend the main file name to distinguish them.
88     // Do not include the full path in the file name since there's no guarantee
89     // that it will stay the same, e.g., if the files are checked out from
90     // version control in different locations.
91     if (FileName.empty())
92       FuncName = FuncName.insert(0, "<unknown>:");
93     else
94       FuncName = FuncName.insert(0, FileName.str() + ":");
95   }
96   return FuncName;
97 }
98
99 std::string getPGOFuncName(const Function &F) {
100   return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName());
101 }
102
103 GlobalVariable *createPGOFuncNameVar(Module &M,
104                                      GlobalValue::LinkageTypes Linkage,
105                                      StringRef FuncName) {
106
107   // We generally want to match the function's linkage, but available_externally
108   // and extern_weak both have the wrong semantics, and anything that doesn't
109   // need to link across compilation units doesn't need to be visible at all.
110   if (Linkage == GlobalValue::ExternalWeakLinkage)
111     Linkage = GlobalValue::LinkOnceAnyLinkage;
112   else if (Linkage == GlobalValue::AvailableExternallyLinkage)
113     Linkage = GlobalValue::LinkOnceODRLinkage;
114   else if (Linkage == GlobalValue::InternalLinkage ||
115            Linkage == GlobalValue::ExternalLinkage)
116     Linkage = GlobalValue::PrivateLinkage;
117
118   auto *Value = ConstantDataArray::getString(M.getContext(), FuncName, false);
119   auto FuncNameVar =
120       new GlobalVariable(M, Value->getType(), true, Linkage, Value,
121                          Twine(getInstrProfNameVarPrefix()) + FuncName);
122
123   // Hide the symbol so that we correctly get a copy for each executable.
124   if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
125     FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
126
127   return FuncNameVar;
128 }
129
130 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName) {
131   return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), FuncName);
132 }
133
134 uint64_t stringToHash(uint32_t ValueKind, uint64_t Value) {
135   switch (ValueKind) {
136   case IPVK_IndirectCallTarget:
137     return IndexedInstrProf::ComputeHash(IndexedInstrProf::HashType,
138                                          (const char *)Value);
139     break;
140   default:
141     llvm_unreachable("value kind not handled !");
142   }
143   return Value;
144 }
145
146 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
147                                     InstrProfRecord::ValueMapType *VMap) {
148   Record.reserveSites(Kind, NumValueSites);
149
150   InstrProfValueData *ValueData = getValueProfRecordValueData(this);
151   for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
152     uint8_t ValueDataCount = this->SiteCountArray[VSite];
153     Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
154     ValueData += ValueDataCount;
155   }
156 }
157
158 // Extract data from \c Closure and serialize into \c This instance.
159 void serializeValueProfRecordFrom(ValueProfRecord *This,
160                                   ValueProfRecordClosure *Closure,
161                                   uint32_t ValueKind, uint32_t NumValueSites) {
162   uint32_t S;
163   const void *Record = Closure->Record;
164   This->Kind = ValueKind;
165   This->NumValueSites = NumValueSites;
166   InstrProfValueData *DstVD = getValueProfRecordValueData(This);
167
168   for (S = 0; S < NumValueSites; S++) {
169     uint32_t ND = Closure->GetNumValueDataForSite(Record, ValueKind, S);
170     This->SiteCountArray[S] = ND;
171     Closure->GetValueForSite(Record, DstVD, ValueKind, S,
172                              Closure->RemapValueData);
173     DstVD += ND;
174   }
175 }
176
177 template <class T>
178 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
179   using namespace support;
180   if (Orig == little)
181     return endian::readNext<T, little, unaligned>(D);
182   else
183     return endian::readNext<T, big, unaligned>(D);
184 }
185
186 // For writing/serializing,  Old is the host endianness, and  New is
187 // byte order intended on disk. For Reading/deserialization, Old
188 // is the on-disk source endianness, and New is the host endianness.
189 void ValueProfRecord::swapBytes(support::endianness Old,
190                                 support::endianness New) {
191   using namespace support;
192   if (Old == New)
193     return;
194
195   if (getHostEndianness() != Old) {
196     sys::swapByteOrder<uint32_t>(NumValueSites);
197     sys::swapByteOrder<uint32_t>(Kind);
198   }
199   uint32_t ND = getValueProfRecordNumValueData(this);
200   InstrProfValueData *VD = getValueProfRecordValueData(this);
201
202   // No need to swap byte array: SiteCountArrray.
203   for (uint32_t I = 0; I < ND; I++) {
204     sys::swapByteOrder<uint64_t>(VD[I].Value);
205     sys::swapByteOrder<uint64_t>(VD[I].Count);
206   }
207   if (getHostEndianness() == Old) {
208     sys::swapByteOrder<uint32_t>(NumValueSites);
209     sys::swapByteOrder<uint32_t>(Kind);
210   }
211 }
212
213 /// Return the total size in bytes of the on-disk value profile data
214 /// given the data stored in Record.
215 uint32_t getValueProfDataSize(ValueProfRecordClosure *Closure) {
216   uint32_t Kind;
217   uint32_t TotalSize = sizeof(ValueProfData);
218   const void *Record = Closure->Record;
219   uint32_t NumValueKinds = Closure->GetNumValueKinds(Record);
220   if (NumValueKinds == 0)
221     return TotalSize;
222
223   for (Kind = IPVK_First; Kind <= IPVK_Last; Kind++) {
224     uint32_t NumValueSites = Closure->GetNumValueSites(Record, Kind);
225     if (!NumValueSites)
226       continue;
227     TotalSize += getValueProfRecordSize(NumValueSites,
228                                         Closure->GetNumValueData(Record, Kind));
229   }
230   return TotalSize;
231 }
232
233 void ValueProfData::deserializeTo(InstrProfRecord &Record,
234                                   InstrProfRecord::ValueMapType *VMap) {
235   if (NumValueKinds == 0)
236     return;
237
238   ValueProfRecord *VR = getFirstValueProfRecord(this);
239   for (uint32_t K = 0; K < NumValueKinds; K++) {
240     VR->deserializeTo(Record, VMap);
241     VR = getValueProfRecordNext(VR);
242   }
243 }
244
245 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
246   return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
247                                             ValueProfData());
248 }
249
250 ValueProfData *serializeValueProfDataFrom(ValueProfRecordClosure *Closure) {
251   uint32_t TotalSize = getValueProfDataSize(Closure);
252
253   ValueProfData *VPD = Closure->AllocValueProfData(TotalSize);
254
255   VPD->TotalSize = TotalSize;
256   VPD->NumValueKinds = Closure->GetNumValueKinds(Closure->Record);
257   ValueProfRecord *VR = getFirstValueProfRecord(VPD);
258   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; Kind++) {
259     uint32_t NumValueSites = Closure->GetNumValueSites(Closure->Record, Kind);
260     if (!NumValueSites)
261       continue;
262     serializeValueProfRecordFrom(VR, Closure, Kind, NumValueSites);
263     VR = getValueProfRecordNext(VR);
264   }
265   return VPD;
266 }
267
268 // C wrappers of InstrProfRecord member functions used in Closure.
269 // These C wrappers are used as adaptors so that C++ code can be
270 // invoked as callbacks.
271 uint32_t getNumValueKindsInstrProf(const void *Record) {
272   return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
273 }
274
275 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
276   return reinterpret_cast<const InstrProfRecord *>(Record)
277       ->getNumValueSites(VKind);
278 }
279
280 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
281   return reinterpret_cast<const InstrProfRecord *>(Record)
282       ->getNumValueData(VKind);
283 }
284
285 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
286                                          uint32_t S) {
287   return reinterpret_cast<const InstrProfRecord *>(R)
288       ->getNumValueDataForSite(VK, S);
289 }
290
291 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
292                               uint32_t K, uint32_t S,
293                               uint64_t (*Mapper)(uint32_t, uint64_t)) {
294   return reinterpret_cast<const InstrProfRecord *>(R)
295       ->getValueForSite(Dst, K, S, Mapper);
296 }
297
298 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
299   return (ValueProfData *)(new (::operator new(TotalSizeInBytes))
300                                ValueProfData());
301 }
302
303 static ValueProfRecordClosure InstrProfRecordClosure = {
304     0,
305     getNumValueKindsInstrProf,
306     getNumValueSitesInstrProf,
307     getNumValueDataInstrProf,
308     getNumValueDataForSiteInstrProf,
309     stringToHash,
310     getValueForSiteInstrProf,
311     allocValueProfDataInstrProf};
312
313 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
314   InstrProfRecordClosure.Record = &Record;
315   return getValueProfDataSize(&InstrProfRecordClosure);
316 }
317
318 std::unique_ptr<ValueProfData>
319 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
320   InstrProfRecordClosure.Record = &Record;
321
322   std::unique_ptr<ValueProfData> VPD(
323       serializeValueProfDataFrom(&InstrProfRecordClosure));
324   return VPD;
325 }
326
327 ErrorOr<std::unique_ptr<ValueProfData>>
328 ValueProfData::getValueProfData(const unsigned char *D,
329                                 const unsigned char *const BufferEnd,
330                                 support::endianness Endianness) {
331   using namespace support;
332   if (D + sizeof(ValueProfData) > BufferEnd)
333     return instrprof_error::truncated;
334
335   const unsigned char *Header = D;
336   uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
337   uint32_t NumValueKinds = swapToHostOrder<uint32_t>(Header, Endianness);
338
339   if (D + TotalSize > BufferEnd)
340     return instrprof_error::too_large;
341   if (NumValueKinds > IPVK_Last + 1)
342     return instrprof_error::malformed;
343   // Total size needs to be mulltiple of quadword size.
344   if (TotalSize % sizeof(uint64_t))
345     return instrprof_error::malformed;
346
347   std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
348
349   memcpy(VPD.get(), D, TotalSize);
350   // Byte swap.
351   VPD->swapBytesToHost(Endianness);
352
353   // Data integrity check:
354   ValueProfRecord *VR = getFirstValueProfRecord(VPD.get());
355   for (uint32_t K = 0; K < VPD->NumValueKinds; K++) {
356     if (VR->Kind > IPVK_Last)
357       return instrprof_error::malformed;
358     VR = getValueProfRecordNext(VR);
359     if ((char *)VR - (char *)VPD.get() > (ptrdiff_t)TotalSize)
360       return instrprof_error::malformed;
361   }
362
363   return std::move(VPD);
364 }
365
366 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
367   using namespace support;
368   if (Endianness == getHostEndianness())
369     return;
370
371   sys::swapByteOrder<uint32_t>(TotalSize);
372   sys::swapByteOrder<uint32_t>(NumValueKinds);
373
374   ValueProfRecord *VR = getFirstValueProfRecord(this);
375   for (uint32_t K = 0; K < NumValueKinds; K++) {
376     VR->swapBytes(Endianness, getHostEndianness());
377     VR = getValueProfRecordNext(VR);
378   }
379 }
380
381 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
382   using namespace support;
383   if (Endianness == getHostEndianness())
384     return;
385
386   ValueProfRecord *VR = getFirstValueProfRecord(this);
387   for (uint32_t K = 0; K < NumValueKinds; K++) {
388     ValueProfRecord *NVR = getValueProfRecordNext(VR);
389     VR->swapBytes(getHostEndianness(), Endianness);
390     VR = NVR;
391   }
392   sys::swapByteOrder<uint32_t>(TotalSize);
393   sys::swapByteOrder<uint32_t>(NumValueKinds);
394 }
395 }