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/MDBuilder.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Support/Compression.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/LEB128.h"
25 #include "llvm/Support/ManagedStatic.h"
30 class InstrProfErrorCategoryType : public std::error_category {
31 const char *name() const LLVM_NOEXCEPT override { return "llvm.instrprof"; }
32 std::string message(int IE) const override {
33 instrprof_error E = static_cast<instrprof_error>(IE);
35 case instrprof_error::success:
37 case instrprof_error::eof:
39 case instrprof_error::unrecognized_format:
40 return "Unrecognized instrumentation profile encoding format";
41 case instrprof_error::bad_magic:
42 return "Invalid instrumentation profile data (bad magic)";
43 case instrprof_error::bad_header:
44 return "Invalid instrumentation profile data (file header is corrupt)";
45 case instrprof_error::unsupported_version:
46 return "Unsupported instrumentation profile format version";
47 case instrprof_error::unsupported_hash_type:
48 return "Unsupported instrumentation profile hash type";
49 case instrprof_error::too_large:
50 return "Too much profile data";
51 case instrprof_error::truncated:
52 return "Truncated profile data";
53 case instrprof_error::malformed:
54 return "Malformed instrumentation profile data";
55 case instrprof_error::unknown_function:
56 return "No profile data available for function";
57 case instrprof_error::hash_mismatch:
58 return "Function control flow change detected (hash mismatch)";
59 case instrprof_error::count_mismatch:
60 return "Function basic block count change detected (counter mismatch)";
61 case instrprof_error::counter_overflow:
62 return "Counter overflow";
63 case instrprof_error::value_site_count_mismatch:
64 return "Function value site count change detected (counter mismatch)";
66 llvm_unreachable("A value of instrprof_error has no message.");
69 } // end anonymous namespace
71 static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
73 const std::error_category &llvm::instrprof_category() {
74 return *ErrorCategory;
79 std::string getPGOFuncName(StringRef RawFuncName,
80 GlobalValue::LinkageTypes Linkage,
82 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
83 return Function::getGlobalIdentifier(RawFuncName, Linkage, FileName);
86 std::string getPGOFuncName(const Function &F, uint64_t Version) {
87 return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName(),
91 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
94 // Drop the file name including ':'. See also getPGOFuncName.
95 if (PGOFuncName.startswith(FileName))
96 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
100 // \p FuncName is the string used as profile lookup key for the function. A
101 // symbol is created to hold the name. Return the legalized symbol name.
102 static std::string getPGOFuncNameVarName(StringRef FuncName,
103 GlobalValue::LinkageTypes Linkage) {
104 std::string VarName = getInstrProfNameVarPrefix();
107 if (!GlobalValue::isLocalLinkage(Linkage))
110 // Now fix up illegal chars in local VarName that may upset the assembler.
111 const char *InvalidChars = "-:<>\"'";
112 size_t found = VarName.find_first_of(InvalidChars);
113 while (found != std::string::npos) {
114 VarName[found] = '_';
115 found = VarName.find_first_of(InvalidChars, found + 1);
120 GlobalVariable *createPGOFuncNameVar(Module &M,
121 GlobalValue::LinkageTypes Linkage,
122 StringRef FuncName) {
124 // We generally want to match the function's linkage, but available_externally
125 // and extern_weak both have the wrong semantics, and anything that doesn't
126 // need to link across compilation units doesn't need to be visible at all.
127 if (Linkage == GlobalValue::ExternalWeakLinkage)
128 Linkage = GlobalValue::LinkOnceAnyLinkage;
129 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
130 Linkage = GlobalValue::LinkOnceODRLinkage;
131 else if (Linkage == GlobalValue::InternalLinkage ||
132 Linkage == GlobalValue::ExternalLinkage)
133 Linkage = GlobalValue::PrivateLinkage;
135 auto *Value = ConstantDataArray::getString(M.getContext(), FuncName, false);
137 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
138 getPGOFuncNameVarName(FuncName, Linkage));
140 // Hide the symbol so that we correctly get a copy for each executable.
141 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
142 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
147 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName) {
148 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), FuncName);
151 void InstrProfSymtab::create(const Module &M) {
152 for (const Function &F : M)
153 addFuncName(getPGOFuncName(F));
158 int collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
159 bool doCompression, std::string &Result) {
160 uint8_t Header[16], *P = Header;
161 std::string UncompressedNameStrings =
162 join(NameStrs.begin(), NameStrs.end(), StringRef(" "));
164 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
167 auto WriteStringToResult = [&](size_t CompressedLen,
168 const std::string &InputStr) {
169 EncLen = encodeULEB128(CompressedLen, P);
171 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
172 unsigned HeaderLen = P - &Header[0];
173 Result.append(HeaderStr, HeaderLen);
179 return WriteStringToResult(0, UncompressedNameStrings);
181 SmallVector<char, 128> CompressedNameStrings;
182 zlib::Status Success =
183 zlib::compress(StringRef(UncompressedNameStrings), CompressedNameStrings,
184 zlib::BestSizeCompression);
186 if (Success != zlib::StatusOK)
189 return WriteStringToResult(
190 CompressedNameStrings.size(),
191 std::string(CompressedNameStrings.data(), CompressedNameStrings.size()));
194 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
195 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
197 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
201 int collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
202 std::string &Result, bool doCompression) {
203 std::vector<std::string> NameStrs;
204 for (auto *NameVar : NameVars) {
205 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
207 return collectPGOFuncNameStrings(
208 NameStrs, zlib::isAvailable() && doCompression, Result);
211 int readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
212 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
213 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
217 uint64_t UncompressedSize = decodeULEB128(P, &N);
219 uint64_t CompressedSize = decodeULEB128(P, &N);
221 bool isCompressed = (CompressedSize != 0);
222 SmallString<128> UncompressedNameStrings;
223 StringRef NameStrings;
225 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
227 if (zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
228 UncompressedSize) != zlib::StatusOK)
231 NameStrings = StringRef(UncompressedNameStrings.data(),
232 UncompressedNameStrings.size());
235 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
236 P += UncompressedSize;
238 // Now parse the name strings.
239 SmallVector<StringRef, 0> Names;
240 NameStrings.split(Names, ' ');
241 for (StringRef &Name : Names)
242 Symtab.addFuncName(Name);
244 while (P < EndP && *P == 0)
247 Symtab.finalizeSymtab();
251 instrprof_error InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
253 this->sortByTargetValues();
254 Input.sortByTargetValues();
255 auto I = ValueData.begin();
256 auto IE = ValueData.end();
257 instrprof_error Result = instrprof_error::success;
258 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
260 while (I != IE && I->Value < J->Value)
262 if (I != IE && I->Value == J->Value) {
264 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
266 Result = instrprof_error::counter_overflow;
270 ValueData.insert(I, *J);
275 instrprof_error InstrProfValueSiteRecord::scale(uint64_t Weight) {
276 instrprof_error Result = instrprof_error::success;
277 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
279 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
281 Result = instrprof_error::counter_overflow;
286 // Merge Value Profile data from Src record to this record for ValueKind.
287 // Scale merged value counts by \p Weight.
288 instrprof_error InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
289 InstrProfRecord &Src,
291 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
292 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
293 if (ThisNumValueSites != OtherNumValueSites)
294 return instrprof_error::value_site_count_mismatch;
295 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
296 getValueSitesForKind(ValueKind);
297 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
298 Src.getValueSitesForKind(ValueKind);
299 instrprof_error Result = instrprof_error::success;
300 for (uint32_t I = 0; I < ThisNumValueSites; I++)
301 MergeResult(Result, ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight));
305 instrprof_error InstrProfRecord::merge(InstrProfRecord &Other,
307 // If the number of counters doesn't match we either have bad data
308 // or a hash collision.
309 if (Counts.size() != Other.Counts.size())
310 return instrprof_error::count_mismatch;
312 instrprof_error Result = instrprof_error::success;
314 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
317 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
319 Result = instrprof_error::counter_overflow;
322 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
323 MergeResult(Result, mergeValueProfData(Kind, Other, Weight));
328 instrprof_error InstrProfRecord::scaleValueProfData(uint32_t ValueKind,
330 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
331 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
332 getValueSitesForKind(ValueKind);
333 instrprof_error Result = instrprof_error::success;
334 for (uint32_t I = 0; I < ThisNumValueSites; I++)
335 MergeResult(Result, ThisSiteRecords[I].scale(Weight));
339 instrprof_error InstrProfRecord::scale(uint64_t Weight) {
340 instrprof_error Result = instrprof_error::success;
341 for (auto &Count : this->Counts) {
343 Count = SaturatingMultiply(Count, Weight, &Overflowed);
344 if (Overflowed && Result == instrprof_error::success) {
345 Result = instrprof_error::counter_overflow;
348 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
349 MergeResult(Result, scaleValueProfData(Kind, Weight));
354 // Map indirect call target name hash to name string.
355 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
356 ValueMapType *ValueMap) {
360 case IPVK_IndirectCallTarget: {
362 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
363 [](const std::pair<uint64_t, uint64_t> &LHS,
364 uint64_t RHS) { return LHS.first < RHS; });
365 if (Result != ValueMap->end())
366 Value = (uint64_t)Result->second;
373 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
374 InstrProfValueData *VData, uint32_t N,
375 ValueMapType *ValueMap) {
376 for (uint32_t I = 0; I < N; I++) {
377 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
379 std::vector<InstrProfValueSiteRecord> &ValueSites =
380 getValueSitesForKind(ValueKind);
382 ValueSites.push_back(InstrProfValueSiteRecord());
384 ValueSites.emplace_back(VData, VData + N);
387 #define INSTR_PROF_COMMON_API_IMPL
388 #include "llvm/ProfileData/InstrProfData.inc"
391 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
392 * class. These C wrappers are used as adaptors so that C++ code can be
393 * invoked as callbacks.
395 uint32_t getNumValueKindsInstrProf(const void *Record) {
396 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
399 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
400 return reinterpret_cast<const InstrProfRecord *>(Record)
401 ->getNumValueSites(VKind);
404 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
405 return reinterpret_cast<const InstrProfRecord *>(Record)
406 ->getNumValueData(VKind);
409 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
411 return reinterpret_cast<const InstrProfRecord *>(R)
412 ->getNumValueDataForSite(VK, S);
415 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
416 uint32_t K, uint32_t S) {
417 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
421 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
423 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
424 memset(VD, 0, TotalSizeInBytes);
428 static ValueProfRecordClosure InstrProfRecordClosure = {
430 getNumValueKindsInstrProf,
431 getNumValueSitesInstrProf,
432 getNumValueDataInstrProf,
433 getNumValueDataForSiteInstrProf,
435 getValueForSiteInstrProf,
436 allocValueProfDataInstrProf};
438 // Wrapper implementation using the closure mechanism.
439 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
440 InstrProfRecordClosure.Record = &Record;
441 return getValueProfDataSize(&InstrProfRecordClosure);
444 // Wrapper implementation using the closure mechanism.
445 std::unique_ptr<ValueProfData>
446 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
447 InstrProfRecordClosure.Record = &Record;
449 std::unique_ptr<ValueProfData> VPD(
450 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
454 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
455 InstrProfRecord::ValueMapType *VMap) {
456 Record.reserveSites(Kind, NumValueSites);
458 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
459 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
460 uint8_t ValueDataCount = this->SiteCountArray[VSite];
461 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
462 ValueData += ValueDataCount;
466 // For writing/serializing, Old is the host endianness, and New is
467 // byte order intended on disk. For Reading/deserialization, Old
468 // is the on-disk source endianness, and New is the host endianness.
469 void ValueProfRecord::swapBytes(support::endianness Old,
470 support::endianness New) {
471 using namespace support;
475 if (getHostEndianness() != Old) {
476 sys::swapByteOrder<uint32_t>(NumValueSites);
477 sys::swapByteOrder<uint32_t>(Kind);
479 uint32_t ND = getValueProfRecordNumValueData(this);
480 InstrProfValueData *VD = getValueProfRecordValueData(this);
482 // No need to swap byte array: SiteCountArrray.
483 for (uint32_t I = 0; I < ND; I++) {
484 sys::swapByteOrder<uint64_t>(VD[I].Value);
485 sys::swapByteOrder<uint64_t>(VD[I].Count);
487 if (getHostEndianness() == Old) {
488 sys::swapByteOrder<uint32_t>(NumValueSites);
489 sys::swapByteOrder<uint32_t>(Kind);
493 void ValueProfData::deserializeTo(InstrProfRecord &Record,
494 InstrProfRecord::ValueMapType *VMap) {
495 if (NumValueKinds == 0)
498 ValueProfRecord *VR = getFirstValueProfRecord(this);
499 for (uint32_t K = 0; K < NumValueKinds; K++) {
500 VR->deserializeTo(Record, VMap);
501 VR = getValueProfRecordNext(VR);
506 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
507 using namespace support;
509 return endian::readNext<T, little, unaligned>(D);
511 return endian::readNext<T, big, unaligned>(D);
514 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
515 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
519 instrprof_error ValueProfData::checkIntegrity() {
520 if (NumValueKinds > IPVK_Last + 1)
521 return instrprof_error::malformed;
522 // Total size needs to be mulltiple of quadword size.
523 if (TotalSize % sizeof(uint64_t))
524 return instrprof_error::malformed;
526 ValueProfRecord *VR = getFirstValueProfRecord(this);
527 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
528 if (VR->Kind > IPVK_Last)
529 return instrprof_error::malformed;
530 VR = getValueProfRecordNext(VR);
531 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
532 return instrprof_error::malformed;
534 return instrprof_error::success;
537 ErrorOr<std::unique_ptr<ValueProfData>>
538 ValueProfData::getValueProfData(const unsigned char *D,
539 const unsigned char *const BufferEnd,
540 support::endianness Endianness) {
541 using namespace support;
542 if (D + sizeof(ValueProfData) > BufferEnd)
543 return instrprof_error::truncated;
545 const unsigned char *Header = D;
546 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
547 if (D + TotalSize > BufferEnd)
548 return instrprof_error::too_large;
550 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
551 memcpy(VPD.get(), D, TotalSize);
553 VPD->swapBytesToHost(Endianness);
555 instrprof_error EC = VPD->checkIntegrity();
556 if (EC != instrprof_error::success)
559 return std::move(VPD);
562 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
563 using namespace support;
564 if (Endianness == getHostEndianness())
567 sys::swapByteOrder<uint32_t>(TotalSize);
568 sys::swapByteOrder<uint32_t>(NumValueKinds);
570 ValueProfRecord *VR = getFirstValueProfRecord(this);
571 for (uint32_t K = 0; K < NumValueKinds; K++) {
572 VR->swapBytes(Endianness, getHostEndianness());
573 VR = getValueProfRecordNext(VR);
577 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
578 using namespace support;
579 if (Endianness == getHostEndianness())
582 ValueProfRecord *VR = getFirstValueProfRecord(this);
583 for (uint32_t K = 0; K < NumValueKinds; K++) {
584 ValueProfRecord *NVR = getValueProfRecordNext(VR);
585 VR->swapBytes(getHostEndianness(), Endianness);
588 sys::swapByteOrder<uint32_t>(TotalSize);
589 sys::swapByteOrder<uint32_t>(NumValueKinds);
592 void annotateValueSite(Module &M, Instruction &Inst,
593 const InstrProfRecord &InstrProfR,
594 InstrProfValueKind ValueKind, uint32_t SiteIdx,
595 uint32_t MaxMDCount) {
596 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
599 std::unique_ptr<InstrProfValueData[]> VD =
600 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
602 annotateValueSite(M, Inst, VD.get(), NV, Sum, ValueKind, MaxMDCount);
605 void annotateValueSite(Module &M, Instruction &Inst,
606 const InstrProfValueData VD[], uint32_t NV,
607 uint64_t Sum, InstrProfValueKind ValueKind,
608 uint32_t MaxMDCount) {
609 LLVMContext &Ctx = M.getContext();
610 MDBuilder MDHelper(Ctx);
611 SmallVector<Metadata *, 3> Vals;
613 Vals.push_back(MDHelper.createString("VP"));
615 Vals.push_back(MDHelper.createConstant(
616 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
619 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
621 // Value Profile Data
622 uint32_t MDCount = MaxMDCount;
623 for (uint32_t I = 0; I < NV; ++I) {
624 Vals.push_back(MDHelper.createConstant(
625 ConstantInt::get(Type::getInt64Ty(Ctx), VD[I].Value)));
626 Vals.push_back(MDHelper.createConstant(
627 ConstantInt::get(Type::getInt64Ty(Ctx), VD[I].Count)));
631 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
634 bool getValueProfDataFromInst(const Instruction &Inst,
635 InstrProfValueKind ValueKind,
636 uint32_t MaxNumValueData,
637 InstrProfValueData ValueData[],
638 uint32_t &ActualNumValueData, uint64_t &TotalC) {
639 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
643 unsigned NOps = MD->getNumOperands();
648 // Operand 0 is a string tag "VP":
649 MDString *Tag = cast<MDString>(MD->getOperand(0));
653 if (!Tag->getString().equals("VP"))
657 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
660 if (KindInt->getZExtValue() != ValueKind)
664 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
667 TotalC = TotalCInt->getZExtValue();
669 ActualNumValueData = 0;
671 for (unsigned I = 3; I < NOps; I += 2) {
672 if (ActualNumValueData >= MaxNumValueData)
674 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
676 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
677 if (!Value || !Count)
679 ValueData[ActualNumValueData].Value = Value->getZExtValue();
680 ValueData[ActualNumValueData].Count = Count->getZExtValue();
681 ActualNumValueData++;
685 } // end namespace llvm