[PGO] Add return code for vp rt record init routine to indicate error condition
[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 /// Return the total size in bytes of the on-disk value profile data
135 /// given the data stored in Record.
136 uint32_t getValueProfDataSize(ValueProfRecordClosure *Closure) {
137   uint32_t Kind;
138   uint32_t TotalSize = sizeof(ValueProfData);
139   const void *Record = Closure->Record;
140   uint32_t NumValueKinds = Closure->GetNumValueKinds(Record);
141   if (NumValueKinds == 0)
142     return TotalSize;
143
144   for (Kind = IPVK_First; Kind <= IPVK_Last; Kind++) {
145     uint32_t NumValueSites = Closure->GetNumValueSites(Record, Kind);
146     if (!NumValueSites)
147       continue;
148     TotalSize += getValueProfRecordSize(NumValueSites,
149                                         Closure->GetNumValueData(Record, Kind));
150   }
151   return TotalSize;
152 }
153
154 // Extract data from \c Closure and serialize into \c This instance.
155 void serializeValueProfRecordFrom(ValueProfRecord *This,
156                                   ValueProfRecordClosure *Closure,
157                                   uint32_t ValueKind, uint32_t NumValueSites) {
158   uint32_t S;
159   const void *Record = Closure->Record;
160   This->Kind = ValueKind;
161   This->NumValueSites = NumValueSites;
162   InstrProfValueData *DstVD = getValueProfRecordValueData(This);
163
164   for (S = 0; S < NumValueSites; S++) {
165     uint32_t ND = Closure->GetNumValueDataForSite(Record, ValueKind, S);
166     This->SiteCountArray[S] = ND;
167     Closure->GetValueForSite(Record, DstVD, ValueKind, S,
168                              Closure->RemapValueData);
169     DstVD += ND;
170   }
171 }
172
173 ValueProfData *serializeValueProfDataFrom(ValueProfRecordClosure *Closure,
174                                           ValueProfData *DstData) {
175   uint32_t TotalSize = getValueProfDataSize(Closure);
176
177   ValueProfData *VPD =
178       DstData ? DstData : Closure->AllocValueProfData(TotalSize);
179
180   VPD->TotalSize = TotalSize;
181   VPD->NumValueKinds = Closure->GetNumValueKinds(Closure->Record);
182   ValueProfRecord *VR = getFirstValueProfRecord(VPD);
183   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; Kind++) {
184     uint32_t NumValueSites = Closure->GetNumValueSites(Closure->Record, Kind);
185     if (!NumValueSites)
186       continue;
187     serializeValueProfRecordFrom(VR, Closure, Kind, NumValueSites);
188     VR = getValueProfRecordNext(VR);
189   }
190   return VPD;
191 }
192
193 /*! \brief ValueProfRecordClosure Interface implementation for  InstrProfRecord
194  *  class. These C wrappers are used as adaptors so that C++ code can be
195  *  invoked as callbacks.
196  */
197 uint32_t getNumValueKindsInstrProf(const void *Record) {
198   return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
199 }
200
201 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
202   return reinterpret_cast<const InstrProfRecord *>(Record)
203       ->getNumValueSites(VKind);
204 }
205
206 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
207   return reinterpret_cast<const InstrProfRecord *>(Record)
208       ->getNumValueData(VKind);
209 }
210
211 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
212                                          uint32_t S) {
213   return reinterpret_cast<const InstrProfRecord *>(R)
214       ->getNumValueDataForSite(VK, S);
215 }
216
217 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
218                               uint32_t K, uint32_t S,
219                               uint64_t (*Mapper)(uint32_t, uint64_t)) {
220   return reinterpret_cast<const InstrProfRecord *>(R)
221       ->getValueForSite(Dst, K, S, Mapper);
222 }
223
224 uint64_t stringToHash(uint32_t ValueKind, uint64_t Value) {
225   switch (ValueKind) {
226   case IPVK_IndirectCallTarget:
227     return IndexedInstrProf::ComputeHash(IndexedInstrProf::HashType,
228                                          (const char *)Value);
229     break;
230   default:
231     llvm_unreachable("value kind not handled !");
232   }
233   return Value;
234 }
235
236 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
237   return (ValueProfData *)(new (::operator new(TotalSizeInBytes))
238                                ValueProfData());
239 }
240
241 static ValueProfRecordClosure InstrProfRecordClosure = {
242     0,
243     getNumValueKindsInstrProf,
244     getNumValueSitesInstrProf,
245     getNumValueDataInstrProf,
246     getNumValueDataForSiteInstrProf,
247     stringToHash,
248     getValueForSiteInstrProf,
249     allocValueProfDataInstrProf
250 };
251
252 // Wrapper implementation using the closure mechanism.
253 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
254   InstrProfRecordClosure.Record = &Record;
255   return getValueProfDataSize(&InstrProfRecordClosure);
256 }
257
258 // Wrapper implementation using the closure mechanism.
259 std::unique_ptr<ValueProfData>
260 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
261   InstrProfRecordClosure.Record = &Record;
262
263   std::unique_ptr<ValueProfData> VPD(
264       serializeValueProfDataFrom(&InstrProfRecordClosure, 0));
265   return VPD;
266 }
267
268 /* The value profiler runtime library stores the value profile data
269  * for a given function in NumValueSites and Nodes. This is the
270  * method to initialize the RuntimeRecord with the runtime data to
271  * pre-compute the information needed to efficiently implement
272  * ValueProfRecordClosure's callback interfaces.
273  */
274 int initializeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord,
275                                      uint16_t *NumValueSites,
276                                      ValueProfNode **Nodes) {
277   unsigned I, J, S = 0, NumValueKinds = 0;
278   RuntimeRecord->NumValueSites = NumValueSites;
279   RuntimeRecord->Nodes = Nodes;
280   for (I = 0; I <= IPVK_Last; I++) {
281     uint16_t N = NumValueSites[I];
282     if (!N) {
283       RuntimeRecord->SiteCountArray[I] = 0;
284       continue;
285     }
286     NumValueKinds++;
287     RuntimeRecord->SiteCountArray[I] = (uint8_t *)calloc(N, 1);
288     RuntimeRecord->NodesKind[I] = &RuntimeRecord->Nodes[S];
289     if (!RuntimeRecord->NodesKind[I])
290       return 1;
291     for (J = 0; J < N; J++) {
292       uint8_t C = 0;
293       ValueProfNode *Site = RuntimeRecord->Nodes[S + J];
294       while (Site) {
295         C++;
296         Site = Site->Next;
297       }
298       if (C > UCHAR_MAX)
299         C = UCHAR_MAX;
300       RuntimeRecord->SiteCountArray[I][J] = C;
301     }
302     S += N;
303   }
304   RuntimeRecord->NumValueKinds = NumValueKinds;
305   return 0;
306 }
307
308 void finalizeValueProfRuntimeRecord(ValueProfRuntimeRecord *RuntimeRecord) {
309   unsigned I;
310   for (I = 0; I <= IPVK_Last; I++) {
311     if (RuntimeRecord->SiteCountArray[I])
312       free(RuntimeRecord->SiteCountArray[I]);
313   }
314 }
315
316 /* ValueProfRecordClosure Interface implementation for
317  * ValueProfDataRuntimeRecord.  */
318 uint32_t getNumValueKindsRT(const void *R) {
319   return ((const ValueProfRuntimeRecord *)R)->NumValueKinds;
320 }
321
322 uint32_t getNumValueSitesRT(const void *R, uint32_t VK) {
323   return ((const ValueProfRuntimeRecord *)R)->NumValueSites[VK];
324 }
325
326 uint32_t getNumValueDataForSiteRT(const void *R, uint32_t VK, uint32_t S) {
327   const ValueProfRuntimeRecord *Record = (const ValueProfRuntimeRecord *)R;
328   return Record->SiteCountArray[VK][S];
329 }
330
331 uint32_t getNumValueDataRT(const void *R, uint32_t VK) {
332   unsigned I, S = 0;
333   const ValueProfRuntimeRecord *Record = (const ValueProfRuntimeRecord *)R;
334   if (Record->SiteCountArray[VK] == 0)
335     return 0;
336   for (I = 0; I < Record->NumValueSites[VK]; I++)
337     S += Record->SiteCountArray[VK][I];
338   return S;
339 }
340
341 void getValueForSiteRT(const void *R, InstrProfValueData *Dst, uint32_t VK,
342                        uint32_t S, uint64_t (*Mapper)(uint32_t, uint64_t)) {
343   unsigned I, N = 0;
344   const ValueProfRuntimeRecord *Record = (const ValueProfRuntimeRecord *)R;
345   N = getNumValueDataForSiteRT(R, VK, S);
346   ValueProfNode *VNode = Record->NodesKind[VK][S];
347   for (I = 0; I < N; I++) {
348     Dst[I] = VNode->VData;
349     VNode = VNode->Next;
350   }
351 }
352
353 ValueProfData *allocValueProfDataRT(size_t TotalSizeInBytes) {
354   return (ValueProfData *)calloc(TotalSizeInBytes, 1);
355 }
356
357 static ValueProfRecordClosure RTRecordClosure = {0,
358                                                  getNumValueKindsRT,
359                                                  getNumValueSitesRT,
360                                                  getNumValueDataRT,
361                                                  getNumValueDataForSiteRT,
362                                                  0,
363                                                  getValueForSiteRT,
364                                                  allocValueProfDataRT};
365
366 /* Return the size of ValueProfData structure to store data
367  * recorded in the runtime record.
368  */
369 uint32_t getValueProfDataSizeRT(const ValueProfRuntimeRecord *Record) {
370   RTRecordClosure.Record = Record;
371   return getValueProfDataSize(&RTRecordClosure);
372 }
373
374 /* Return a ValueProfData instance that stores the data collected
375  * from runtime. If \c DstData is provided by the caller, the value
376  * profile data will be store in *DstData and DstData is returned,
377  * otherwise the method will allocate space for the value data and
378  * return pointer to the newly allocated space.
379  */
380 ValueProfData *
381 serializeValueProfDataFromRT(const ValueProfRuntimeRecord *Record,
382                              ValueProfData *DstData) {
383   RTRecordClosure.Record = Record;
384   return serializeValueProfDataFrom(&RTRecordClosure, DstData);
385 }
386
387 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
388                                     InstrProfRecord::ValueMapType *VMap) {
389   Record.reserveSites(Kind, NumValueSites);
390
391   InstrProfValueData *ValueData = getValueProfRecordValueData(this);
392   for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
393     uint8_t ValueDataCount = this->SiteCountArray[VSite];
394     Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
395     ValueData += ValueDataCount;
396   }
397 }
398
399 // For writing/serializing,  Old is the host endianness, and  New is
400 // byte order intended on disk. For Reading/deserialization, Old
401 // is the on-disk source endianness, and New is the host endianness.
402 void ValueProfRecord::swapBytes(support::endianness Old,
403                                 support::endianness New) {
404   using namespace support;
405   if (Old == New)
406     return;
407
408   if (getHostEndianness() != Old) {
409     sys::swapByteOrder<uint32_t>(NumValueSites);
410     sys::swapByteOrder<uint32_t>(Kind);
411   }
412   uint32_t ND = getValueProfRecordNumValueData(this);
413   InstrProfValueData *VD = getValueProfRecordValueData(this);
414
415   // No need to swap byte array: SiteCountArrray.
416   for (uint32_t I = 0; I < ND; I++) {
417     sys::swapByteOrder<uint64_t>(VD[I].Value);
418     sys::swapByteOrder<uint64_t>(VD[I].Count);
419   }
420   if (getHostEndianness() == Old) {
421     sys::swapByteOrder<uint32_t>(NumValueSites);
422     sys::swapByteOrder<uint32_t>(Kind);
423   }
424 }
425
426 void ValueProfData::deserializeTo(InstrProfRecord &Record,
427                                   InstrProfRecord::ValueMapType *VMap) {
428   if (NumValueKinds == 0)
429     return;
430
431   ValueProfRecord *VR = getFirstValueProfRecord(this);
432   for (uint32_t K = 0; K < NumValueKinds; K++) {
433     VR->deserializeTo(Record, VMap);
434     VR = getValueProfRecordNext(VR);
435   }
436 }
437
438 template <class T>
439 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
440   using namespace support;
441   if (Orig == little)
442     return endian::readNext<T, little, unaligned>(D);
443   else
444     return endian::readNext<T, big, unaligned>(D);
445 }
446
447 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
448   return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
449                                             ValueProfData());
450 }
451
452 instrprof_error ValueProfData::checkIntegrity() {
453   if (NumValueKinds > IPVK_Last + 1)
454     return instrprof_error::malformed;
455   // Total size needs to be mulltiple of quadword size.
456   if (TotalSize % sizeof(uint64_t))
457     return instrprof_error::malformed;
458
459   ValueProfRecord *VR = getFirstValueProfRecord(this);
460   for (uint32_t K = 0; K < this->NumValueKinds; K++) {
461     if (VR->Kind > IPVK_Last)
462       return instrprof_error::malformed;
463     VR = getValueProfRecordNext(VR);
464     if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
465       return instrprof_error::malformed;
466   }
467   return instrprof_error::success;
468 }
469
470 ErrorOr<std::unique_ptr<ValueProfData>>
471 ValueProfData::getValueProfData(const unsigned char *D,
472                                 const unsigned char *const BufferEnd,
473                                 support::endianness Endianness) {
474   using namespace support;
475   if (D + sizeof(ValueProfData) > BufferEnd)
476     return instrprof_error::truncated;
477
478   const unsigned char *Header = D;
479   uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
480   if (D + TotalSize > BufferEnd)
481     return instrprof_error::too_large;
482
483   std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
484   memcpy(VPD.get(), D, TotalSize);
485   // Byte swap.
486   VPD->swapBytesToHost(Endianness);
487
488   instrprof_error EC = VPD->checkIntegrity();
489   if (EC != instrprof_error::success)
490     return EC;
491
492   return std::move(VPD);
493 }
494
495 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
496   using namespace support;
497   if (Endianness == getHostEndianness())
498     return;
499
500   sys::swapByteOrder<uint32_t>(TotalSize);
501   sys::swapByteOrder<uint32_t>(NumValueKinds);
502
503   ValueProfRecord *VR = getFirstValueProfRecord(this);
504   for (uint32_t K = 0; K < NumValueKinds; K++) {
505     VR->swapBytes(Endianness, getHostEndianness());
506     VR = getValueProfRecordNext(VR);
507   }
508 }
509
510 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
511   using namespace support;
512   if (Endianness == getHostEndianness())
513     return;
514
515   ValueProfRecord *VR = getFirstValueProfRecord(this);
516   for (uint32_t K = 0; K < NumValueKinds; K++) {
517     ValueProfRecord *NVR = getValueProfRecordNext(VR);
518     VR->swapBytes(getHostEndianness(), Endianness);
519     VR = NVR;
520   }
521   sys::swapByteOrder<uint32_t>(TotalSize);
522   sys::swapByteOrder<uint32_t>(NumValueKinds);
523 }
524
525 }