1 //=-- InstrProf.cpp - Instrumented profiling format support -----------------=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for clang's instrumentation based PGO and
13 //===----------------------------------------------------------------------===//
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"
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);
31 case instrprof_error::success:
33 case instrprof_error::eof:
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)";
62 llvm_unreachable("A value of instrprof_error has no message.");
67 static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
69 const std::error_category &llvm::instrprof_category() {
70 return *ErrorCategory;
75 std::string getPGOFuncName(StringRef RawFuncName,
76 GlobalValue::LinkageTypes Linkage,
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);
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.
92 FuncName = FuncName.insert(0, "<unknown>:");
94 FuncName = FuncName.insert(0, FileName.str() + ":");
99 std::string getPGOFuncName(const Function &F) {
100 return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName());
103 GlobalVariable *createPGOFuncNameVar(Module &M,
104 GlobalValue::LinkageTypes Linkage,
105 StringRef FuncName) {
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;
118 auto *Value = ConstantDataArray::getString(M.getContext(), FuncName, false);
120 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
121 Twine(getInstrProfNameVarPrefix()) + FuncName);
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);
130 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName) {
131 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), FuncName);
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) {
138 uint32_t TotalSize = sizeof(ValueProfData);
139 const void *Record = Closure->Record;
140 uint32_t NumValueKinds = Closure->GetNumValueKinds(Record);
141 if (NumValueKinds == 0)
144 for (Kind = IPVK_First; Kind <= IPVK_Last; Kind++) {
145 uint32_t NumValueSites = Closure->GetNumValueSites(Record, Kind);
148 TotalSize += getValueProfRecordSize(NumValueSites,
149 Closure->GetNumValueData(Record, Kind));
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) {
159 const void *Record = Closure->Record;
160 This->Kind = ValueKind;
161 This->NumValueSites = NumValueSites;
162 InstrProfValueData *DstVD = getValueProfRecordValueData(This);
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);
173 ValueProfData *serializeValueProfDataFrom(ValueProfRecordClosure *Closure) {
174 uint32_t TotalSize = getValueProfDataSize(Closure);
176 ValueProfData *VPD = Closure->AllocValueProfData(TotalSize);
178 VPD->TotalSize = TotalSize;
179 VPD->NumValueKinds = Closure->GetNumValueKinds(Closure->Record);
180 ValueProfRecord *VR = getFirstValueProfRecord(VPD);
181 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; Kind++) {
182 uint32_t NumValueSites = Closure->GetNumValueSites(Closure->Record, Kind);
185 serializeValueProfRecordFrom(VR, Closure, Kind, NumValueSites);
186 VR = getValueProfRecordNext(VR);
191 // C wrappers of InstrProfRecord member functions used in Closure.
192 // These C wrappers are used as adaptors so that C++ code can be
193 // invoked as callbacks.
194 uint32_t getNumValueKindsInstrProf(const void *Record) {
195 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
198 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
199 return reinterpret_cast<const InstrProfRecord *>(Record)
200 ->getNumValueSites(VKind);
203 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
204 return reinterpret_cast<const InstrProfRecord *>(Record)
205 ->getNumValueData(VKind);
208 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
210 return reinterpret_cast<const InstrProfRecord *>(R)
211 ->getNumValueDataForSite(VK, S);
214 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
215 uint32_t K, uint32_t S,
216 uint64_t (*Mapper)(uint32_t, uint64_t)) {
217 return reinterpret_cast<const InstrProfRecord *>(R)
218 ->getValueForSite(Dst, K, S, Mapper);
221 uint64_t stringToHash(uint32_t ValueKind, uint64_t Value) {
223 case IPVK_IndirectCallTarget:
224 return IndexedInstrProf::ComputeHash(IndexedInstrProf::HashType,
225 (const char *)Value);
228 llvm_unreachable("value kind not handled !");
233 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
234 return (ValueProfData *)(new (::operator new(TotalSizeInBytes))
238 static ValueProfRecordClosure InstrProfRecordClosure = {
240 getNumValueKindsInstrProf,
241 getNumValueSitesInstrProf,
242 getNumValueDataInstrProf,
243 getNumValueDataForSiteInstrProf,
245 getValueForSiteInstrProf,
246 allocValueProfDataInstrProf
249 // Wrapper implementation using the closure mechanism.
250 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
251 InstrProfRecordClosure.Record = &Record;
252 return getValueProfDataSize(&InstrProfRecordClosure);
255 // Wrapper implementation using the closure mechanism.
256 std::unique_ptr<ValueProfData>
257 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
258 InstrProfRecordClosure.Record = &Record;
260 std::unique_ptr<ValueProfData> VPD(
261 serializeValueProfDataFrom(&InstrProfRecordClosure));
265 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
266 InstrProfRecord::ValueMapType *VMap) {
267 Record.reserveSites(Kind, NumValueSites);
269 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
270 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
271 uint8_t ValueDataCount = this->SiteCountArray[VSite];
272 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
273 ValueData += ValueDataCount;
276 // For writing/serializing, Old is the host endianness, and New is
277 // byte order intended on disk. For Reading/deserialization, Old
278 // is the on-disk source endianness, and New is the host endianness.
279 void ValueProfRecord::swapBytes(support::endianness Old,
280 support::endianness New) {
281 using namespace support;
285 if (getHostEndianness() != Old) {
286 sys::swapByteOrder<uint32_t>(NumValueSites);
287 sys::swapByteOrder<uint32_t>(Kind);
289 uint32_t ND = getValueProfRecordNumValueData(this);
290 InstrProfValueData *VD = getValueProfRecordValueData(this);
292 // No need to swap byte array: SiteCountArrray.
293 for (uint32_t I = 0; I < ND; I++) {
294 sys::swapByteOrder<uint64_t>(VD[I].Value);
295 sys::swapByteOrder<uint64_t>(VD[I].Count);
297 if (getHostEndianness() == Old) {
298 sys::swapByteOrder<uint32_t>(NumValueSites);
299 sys::swapByteOrder<uint32_t>(Kind);
303 void ValueProfData::deserializeTo(InstrProfRecord &Record,
304 InstrProfRecord::ValueMapType *VMap) {
305 if (NumValueKinds == 0)
308 ValueProfRecord *VR = getFirstValueProfRecord(this);
309 for (uint32_t K = 0; K < NumValueKinds; K++) {
310 VR->deserializeTo(Record, VMap);
311 VR = getValueProfRecordNext(VR);
316 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
317 using namespace support;
319 return endian::readNext<T, little, unaligned>(D);
321 return endian::readNext<T, big, unaligned>(D);
324 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
325 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
329 ErrorOr<std::unique_ptr<ValueProfData>>
330 ValueProfData::getValueProfData(const unsigned char *D,
331 const unsigned char *const BufferEnd,
332 support::endianness Endianness) {
333 using namespace support;
334 if (D + sizeof(ValueProfData) > BufferEnd)
335 return instrprof_error::truncated;
337 const unsigned char *Header = D;
338 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
339 uint32_t NumValueKinds = swapToHostOrder<uint32_t>(Header, Endianness);
341 if (D + TotalSize > BufferEnd)
342 return instrprof_error::too_large;
343 if (NumValueKinds > IPVK_Last + 1)
344 return instrprof_error::malformed;
345 // Total size needs to be mulltiple of quadword size.
346 if (TotalSize % sizeof(uint64_t))
347 return instrprof_error::malformed;
349 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
351 memcpy(VPD.get(), D, TotalSize);
353 VPD->swapBytesToHost(Endianness);
355 // Data integrity check:
356 ValueProfRecord *VR = getFirstValueProfRecord(VPD.get());
357 for (uint32_t K = 0; K < VPD->NumValueKinds; K++) {
358 if (VR->Kind > IPVK_Last)
359 return instrprof_error::malformed;
360 VR = getValueProfRecordNext(VR);
361 if ((char *)VR - (char *)VPD.get() > (ptrdiff_t)TotalSize)
362 return instrprof_error::malformed;
365 return std::move(VPD);
368 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
369 using namespace support;
370 if (Endianness == getHostEndianness())
373 sys::swapByteOrder<uint32_t>(TotalSize);
374 sys::swapByteOrder<uint32_t>(NumValueKinds);
376 ValueProfRecord *VR = getFirstValueProfRecord(this);
377 for (uint32_t K = 0; K < NumValueKinds; K++) {
378 VR->swapBytes(Endianness, getHostEndianness());
379 VR = getValueProfRecordNext(VR);
383 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
384 using namespace support;
385 if (Endianness == getHostEndianness())
388 ValueProfRecord *VR = getFirstValueProfRecord(this);
389 for (uint32_t K = 0; K < NumValueKinds; K++) {
390 ValueProfRecord *NVR = getValueProfRecordNext(VR);
391 VR->swapBytes(getHostEndianness(), Endianness);
394 sys::swapByteOrder<uint32_t>(TotalSize);
395 sys::swapByteOrder<uint32_t>(NumValueKinds);