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/ProfileData/InstrProf.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/GlobalVariable.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/Support/Compression.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/LEB128.h"
24 #include "llvm/Support/ManagedStatic.h"
29 class InstrProfErrorCategoryType : public std::error_category {
30 const char *name() const LLVM_NOEXCEPT override { return "llvm.instrprof"; }
31 std::string message(int IE) const override {
32 instrprof_error E = static_cast<instrprof_error>(IE);
34 case instrprof_error::success:
36 case instrprof_error::eof:
38 case instrprof_error::unrecognized_format:
39 return "Unrecognized instrumentation profile encoding format";
40 case instrprof_error::bad_magic:
41 return "Invalid instrumentation profile data (bad magic)";
42 case instrprof_error::bad_header:
43 return "Invalid instrumentation profile data (file header is corrupt)";
44 case instrprof_error::unsupported_version:
45 return "Unsupported instrumentation profile format version";
46 case instrprof_error::unsupported_hash_type:
47 return "Unsupported instrumentation profile hash type";
48 case instrprof_error::too_large:
49 return "Too much profile data";
50 case instrprof_error::truncated:
51 return "Truncated profile data";
52 case instrprof_error::malformed:
53 return "Malformed instrumentation profile data";
54 case instrprof_error::unknown_function:
55 return "No profile data available for function";
56 case instrprof_error::hash_mismatch:
57 return "Function control flow change detected (hash mismatch)";
58 case instrprof_error::count_mismatch:
59 return "Function basic block count change detected (counter mismatch)";
60 case instrprof_error::counter_overflow:
61 return "Counter overflow";
62 case instrprof_error::value_site_count_mismatch:
63 return "Function value site count change detected (counter mismatch)";
65 llvm_unreachable("A value of instrprof_error has no message.");
70 static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
72 const std::error_category &llvm::instrprof_category() {
73 return *ErrorCategory;
78 std::string getPGOFuncName(StringRef RawFuncName,
79 GlobalValue::LinkageTypes Linkage,
81 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
83 // Function names may be prefixed with a binary '1' to indicate
84 // that the backend should not modify the symbols due to any platform
85 // naming convention. Do not include that '1' in the PGO profile name.
86 if (RawFuncName[0] == '\1')
87 RawFuncName = RawFuncName.substr(1);
89 std::string FuncName = RawFuncName;
90 if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
91 // For local symbols, prepend the main file name to distinguish them.
92 // Do not include the full path in the file name since there's no guarantee
93 // that it will stay the same, e.g., if the files are checked out from
94 // version control in different locations.
96 FuncName = FuncName.insert(0, "<unknown>:");
98 FuncName = FuncName.insert(0, FileName.str() + ":");
103 std::string getPGOFuncName(const Function &F, uint64_t Version) {
104 return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName(),
108 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
109 if (FileName.empty())
111 // Drop the file name including ':'. See also getPGOFuncName.
112 if (PGOFuncName.startswith(FileName))
113 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
117 // \p FuncName is the string used as profile lookup key for the function. A
118 // symbol is created to hold the name. Return the legalized symbol name.
119 static std::string getPGOFuncNameVarName(StringRef FuncName,
120 GlobalValue::LinkageTypes Linkage) {
121 std::string VarName = getInstrProfNameVarPrefix();
124 if (!GlobalValue::isLocalLinkage(Linkage))
127 // Now fix up illegal chars in local VarName that may upset the assembler.
128 const char *InvalidChars = "-:<>\"'";
129 size_t found = VarName.find_first_of(InvalidChars);
130 while (found != std::string::npos) {
131 VarName[found] = '_';
132 found = VarName.find_first_of(InvalidChars, found + 1);
137 GlobalVariable *createPGOFuncNameVar(Module &M,
138 GlobalValue::LinkageTypes Linkage,
139 StringRef FuncName) {
141 // We generally want to match the function's linkage, but available_externally
142 // and extern_weak both have the wrong semantics, and anything that doesn't
143 // need to link across compilation units doesn't need to be visible at all.
144 if (Linkage == GlobalValue::ExternalWeakLinkage)
145 Linkage = GlobalValue::LinkOnceAnyLinkage;
146 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
147 Linkage = GlobalValue::LinkOnceODRLinkage;
148 else if (Linkage == GlobalValue::InternalLinkage ||
149 Linkage == GlobalValue::ExternalLinkage)
150 Linkage = GlobalValue::PrivateLinkage;
152 auto *Value = ConstantDataArray::getString(M.getContext(), FuncName, false);
154 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
155 getPGOFuncNameVarName(FuncName, Linkage));
157 // Hide the symbol so that we correctly get a copy for each executable.
158 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
159 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
164 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName) {
165 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), FuncName);
168 int collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
169 bool doCompression, std::string &Result) {
170 uint8_t Header[16], *P = Header;
171 std::string UncompressedNameStrings =
172 join(NameStrs.begin(), NameStrs.end(), StringRef(" "));
174 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
177 auto WriteStringToResult = [&](size_t CompressedLen,
178 const std::string &InputStr) {
179 EncLen = encodeULEB128(CompressedLen, P);
181 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
182 unsigned HeaderLen = P - &Header[0];
183 Result.append(HeaderStr, HeaderLen);
189 return WriteStringToResult(0, UncompressedNameStrings);
191 SmallVector<char, 128> CompressedNameStrings;
192 zlib::Status Success =
193 zlib::compress(StringRef(UncompressedNameStrings), CompressedNameStrings,
194 zlib::BestSizeCompression);
196 if (Success != zlib::StatusOK)
199 return WriteStringToResult(
200 CompressedNameStrings.size(),
201 std::string(CompressedNameStrings.data(), CompressedNameStrings.size()));
204 StringRef getPGOFuncNameInitializer(GlobalVariable *NameVar) {
205 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
207 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
211 int collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
212 std::string &Result) {
213 std::vector<std::string> NameStrs;
214 for (auto *NameVar : NameVars) {
215 NameStrs.push_back(getPGOFuncNameInitializer(NameVar));
217 return collectPGOFuncNameStrings(NameStrs, zlib::isAvailable(), Result);
220 int readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
221 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
222 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
226 uint64_t UncompressedSize = decodeULEB128(P, &N);
228 uint64_t CompressedSize = decodeULEB128(P, &N);
230 bool isCompressed = (CompressedSize != 0);
231 SmallString<128> UncompressedNameStrings;
232 StringRef NameStrings;
234 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
236 if (zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
237 UncompressedSize) != zlib::StatusOK)
240 NameStrings = StringRef(UncompressedNameStrings.data(),
241 UncompressedNameStrings.size());
244 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
245 P += UncompressedSize;
247 // Now parse the name strings.
248 SmallVector<StringRef, 0> Names;
249 NameStrings.split(Names, ' ');
250 for (StringRef &Name : Names)
251 Symtab.addFuncName(Name);
253 while (P < EndP && *P == 0)
256 Symtab.finalizeSymtab();
260 instrprof_error InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
262 this->sortByTargetValues();
263 Input.sortByTargetValues();
264 auto I = ValueData.begin();
265 auto IE = ValueData.end();
266 instrprof_error Result = instrprof_error::success;
267 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
269 while (I != IE && I->Value < J->Value)
271 if (I != IE && I->Value == J->Value) {
272 uint64_t JCount = J->Count;
275 JCount = SaturatingMultiply(JCount, Weight, &Overflowed);
277 Result = instrprof_error::counter_overflow;
279 I->Count = SaturatingAdd(I->Count, JCount, &Overflowed);
281 Result = instrprof_error::counter_overflow;
285 ValueData.insert(I, *J);
290 instrprof_error InstrProfValueSiteRecord::scale(uint64_t Weight) {
291 instrprof_error Result = instrprof_error::success;
292 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
294 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
296 Result = instrprof_error::counter_overflow;
301 // Merge Value Profile data from Src record to this record for ValueKind.
302 // Scale merged value counts by \p Weight.
303 instrprof_error InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
304 InstrProfRecord &Src,
306 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
307 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
308 if (ThisNumValueSites != OtherNumValueSites)
309 return instrprof_error::value_site_count_mismatch;
310 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
311 getValueSitesForKind(ValueKind);
312 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
313 Src.getValueSitesForKind(ValueKind);
314 instrprof_error Result = instrprof_error::success;
315 for (uint32_t I = 0; I < ThisNumValueSites; I++)
316 MergeResult(Result, ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight));
320 instrprof_error InstrProfRecord::merge(InstrProfRecord &Other,
322 // If the number of counters doesn't match we either have bad data
323 // or a hash collision.
324 if (Counts.size() != Other.Counts.size())
325 return instrprof_error::count_mismatch;
327 instrprof_error Result = instrprof_error::success;
329 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
331 uint64_t OtherCount = Other.Counts[I];
333 OtherCount = SaturatingMultiply(OtherCount, Weight, &Overflowed);
335 Result = instrprof_error::counter_overflow;
337 Counts[I] = SaturatingAdd(Counts[I], OtherCount, &Overflowed);
339 Result = instrprof_error::counter_overflow;
342 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
343 MergeResult(Result, mergeValueProfData(Kind, Other, Weight));
348 instrprof_error InstrProfRecord::scaleValueProfData(uint32_t ValueKind,
350 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
351 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
352 getValueSitesForKind(ValueKind);
353 instrprof_error Result = instrprof_error::success;
354 for (uint32_t I = 0; I < ThisNumValueSites; I++)
355 MergeResult(Result, ThisSiteRecords[I].scale(Weight));
359 instrprof_error InstrProfRecord::scale(uint64_t Weight) {
360 instrprof_error Result = instrprof_error::success;
361 for (auto &Count : this->Counts) {
363 Count = SaturatingMultiply(Count, Weight, &Overflowed);
364 if (Overflowed && Result == instrprof_error::success) {
365 Result = instrprof_error::counter_overflow;
368 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
369 MergeResult(Result, scaleValueProfData(Kind, Weight));
374 // Map indirect call target name hash to name string.
375 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
376 ValueMapType *ValueMap) {
380 case IPVK_IndirectCallTarget: {
382 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
383 [](const std::pair<uint64_t, uint64_t> &LHS,
384 uint64_t RHS) { return LHS.first < RHS; });
385 if (Result != ValueMap->end())
386 Value = (uint64_t)Result->second;
393 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
394 InstrProfValueData *VData, uint32_t N,
395 ValueMapType *ValueMap) {
396 for (uint32_t I = 0; I < N; I++) {
397 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
399 std::vector<InstrProfValueSiteRecord> &ValueSites =
400 getValueSitesForKind(ValueKind);
402 ValueSites.push_back(InstrProfValueSiteRecord());
404 ValueSites.emplace_back(VData, VData + N);
407 #define INSTR_PROF_COMMON_API_IMPL
408 #include "llvm/ProfileData/InstrProfData.inc"
411 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
412 * class. These C wrappers are used as adaptors so that C++ code can be
413 * invoked as callbacks.
415 uint32_t getNumValueKindsInstrProf(const void *Record) {
416 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
419 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
420 return reinterpret_cast<const InstrProfRecord *>(Record)
421 ->getNumValueSites(VKind);
424 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
425 return reinterpret_cast<const InstrProfRecord *>(Record)
426 ->getNumValueData(VKind);
429 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
431 return reinterpret_cast<const InstrProfRecord *>(R)
432 ->getNumValueDataForSite(VK, S);
435 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
436 uint32_t K, uint32_t S,
437 uint64_t (*Mapper)(uint32_t, uint64_t)) {
438 return reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(
442 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
444 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
445 memset(VD, 0, TotalSizeInBytes);
449 static ValueProfRecordClosure InstrProfRecordClosure = {
451 getNumValueKindsInstrProf,
452 getNumValueSitesInstrProf,
453 getNumValueDataInstrProf,
454 getNumValueDataForSiteInstrProf,
456 getValueForSiteInstrProf,
457 allocValueProfDataInstrProf};
459 // Wrapper implementation using the closure mechanism.
460 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
461 InstrProfRecordClosure.Record = &Record;
462 return getValueProfDataSize(&InstrProfRecordClosure);
465 // Wrapper implementation using the closure mechanism.
466 std::unique_ptr<ValueProfData>
467 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
468 InstrProfRecordClosure.Record = &Record;
470 std::unique_ptr<ValueProfData> VPD(
471 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
475 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
476 InstrProfRecord::ValueMapType *VMap) {
477 Record.reserveSites(Kind, NumValueSites);
479 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
480 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
481 uint8_t ValueDataCount = this->SiteCountArray[VSite];
482 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
483 ValueData += ValueDataCount;
487 // For writing/serializing, Old is the host endianness, and New is
488 // byte order intended on disk. For Reading/deserialization, Old
489 // is the on-disk source endianness, and New is the host endianness.
490 void ValueProfRecord::swapBytes(support::endianness Old,
491 support::endianness New) {
492 using namespace support;
496 if (getHostEndianness() != Old) {
497 sys::swapByteOrder<uint32_t>(NumValueSites);
498 sys::swapByteOrder<uint32_t>(Kind);
500 uint32_t ND = getValueProfRecordNumValueData(this);
501 InstrProfValueData *VD = getValueProfRecordValueData(this);
503 // No need to swap byte array: SiteCountArrray.
504 for (uint32_t I = 0; I < ND; I++) {
505 sys::swapByteOrder<uint64_t>(VD[I].Value);
506 sys::swapByteOrder<uint64_t>(VD[I].Count);
508 if (getHostEndianness() == Old) {
509 sys::swapByteOrder<uint32_t>(NumValueSites);
510 sys::swapByteOrder<uint32_t>(Kind);
514 void ValueProfData::deserializeTo(InstrProfRecord &Record,
515 InstrProfRecord::ValueMapType *VMap) {
516 if (NumValueKinds == 0)
519 ValueProfRecord *VR = getFirstValueProfRecord(this);
520 for (uint32_t K = 0; K < NumValueKinds; K++) {
521 VR->deserializeTo(Record, VMap);
522 VR = getValueProfRecordNext(VR);
527 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
528 using namespace support;
530 return endian::readNext<T, little, unaligned>(D);
532 return endian::readNext<T, big, unaligned>(D);
535 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
536 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
540 instrprof_error ValueProfData::checkIntegrity() {
541 if (NumValueKinds > IPVK_Last + 1)
542 return instrprof_error::malformed;
543 // Total size needs to be mulltiple of quadword size.
544 if (TotalSize % sizeof(uint64_t))
545 return instrprof_error::malformed;
547 ValueProfRecord *VR = getFirstValueProfRecord(this);
548 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
549 if (VR->Kind > IPVK_Last)
550 return instrprof_error::malformed;
551 VR = getValueProfRecordNext(VR);
552 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
553 return instrprof_error::malformed;
555 return instrprof_error::success;
558 ErrorOr<std::unique_ptr<ValueProfData>>
559 ValueProfData::getValueProfData(const unsigned char *D,
560 const unsigned char *const BufferEnd,
561 support::endianness Endianness) {
562 using namespace support;
563 if (D + sizeof(ValueProfData) > BufferEnd)
564 return instrprof_error::truncated;
566 const unsigned char *Header = D;
567 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
568 if (D + TotalSize > BufferEnd)
569 return instrprof_error::too_large;
571 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
572 memcpy(VPD.get(), D, TotalSize);
574 VPD->swapBytesToHost(Endianness);
576 instrprof_error EC = VPD->checkIntegrity();
577 if (EC != instrprof_error::success)
580 return std::move(VPD);
583 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
584 using namespace support;
585 if (Endianness == getHostEndianness())
588 sys::swapByteOrder<uint32_t>(TotalSize);
589 sys::swapByteOrder<uint32_t>(NumValueKinds);
591 ValueProfRecord *VR = getFirstValueProfRecord(this);
592 for (uint32_t K = 0; K < NumValueKinds; K++) {
593 VR->swapBytes(Endianness, getHostEndianness());
594 VR = getValueProfRecordNext(VR);
598 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
599 using namespace support;
600 if (Endianness == getHostEndianness())
603 ValueProfRecord *VR = getFirstValueProfRecord(this);
604 for (uint32_t K = 0; K < NumValueKinds; K++) {
605 ValueProfRecord *NVR = getValueProfRecordNext(VR);
606 VR->swapBytes(getHostEndianness(), Endianness);
609 sys::swapByteOrder<uint32_t>(TotalSize);
610 sys::swapByteOrder<uint32_t>(NumValueKinds);