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/ADT/ArrayRef.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/IR/Constant.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalValue.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/Instruction.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/MDBuilder.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/ProfileData/InstrProf.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Compression.h"
37 #include "llvm/Support/Endian.h"
38 #include "llvm/Support/Error.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/LEB128.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/SwapByteOrder.h"
52 #include <system_error>
58 static cl::opt<bool> StaticFuncFullModulePrefix(
59 "static-func-full-module-prefix", cl::init(true),
60 cl::desc("Use full module build paths in the profile counter names for "
61 "static functions."));
63 // This option is tailored to users that have different top-level directory in
64 // profile-gen and profile-use compilation. Users need to specific the number
65 // of levels to strip. A value larger than the number of directories in the
66 // source file will strip all the directory names and only leave the basename.
68 // Note current ThinLTO module importing for the indirect-calls assumes
69 // the source directory name not being stripped. A non-zero option value here
70 // can potentially prevent some inter-module indirect-call-promotions.
71 static cl::opt<unsigned> StaticFuncStripDirNamePrefix(
72 "static-func-strip-dirname-prefix", cl::init(0),
73 cl::desc("Strip specified level of directory name from source path in "
74 "the profile counter name for static functions."));
76 static std::string getInstrProfErrString(instrprof_error Err) {
78 case instrprof_error::success:
80 case instrprof_error::eof:
82 case instrprof_error::unrecognized_format:
83 return "Unrecognized instrumentation profile encoding format";
84 case instrprof_error::bad_magic:
85 return "Invalid instrumentation profile data (bad magic)";
86 case instrprof_error::bad_header:
87 return "Invalid instrumentation profile data (file header is corrupt)";
88 case instrprof_error::unsupported_version:
89 return "Unsupported instrumentation profile format version";
90 case instrprof_error::unsupported_hash_type:
91 return "Unsupported instrumentation profile hash type";
92 case instrprof_error::too_large:
93 return "Too much profile data";
94 case instrprof_error::truncated:
95 return "Truncated profile data";
96 case instrprof_error::malformed:
97 return "Malformed instrumentation profile data";
98 case instrprof_error::unknown_function:
99 return "No profile data available for function";
100 case instrprof_error::hash_mismatch:
101 return "Function control flow change detected (hash mismatch)";
102 case instrprof_error::count_mismatch:
103 return "Function basic block count change detected (counter mismatch)";
104 case instrprof_error::counter_overflow:
105 return "Counter overflow";
106 case instrprof_error::value_site_count_mismatch:
107 return "Function value site count change detected (counter mismatch)";
108 case instrprof_error::compress_failed:
109 return "Failed to compress data (zlib)";
110 case instrprof_error::uncompress_failed:
111 return "Failed to uncompress data (zlib)";
112 case instrprof_error::empty_raw_profile:
113 return "Empty raw profile file";
115 llvm_unreachable("A value of instrprof_error has no message.");
120 // FIXME: This class is only here to support the transition to llvm::Error. It
121 // will be removed once this transition is complete. Clients should prefer to
122 // deal with the Error value directly, rather than converting to error_code.
123 class InstrProfErrorCategoryType : public std::error_category {
124 const char *name() const noexcept override { return "llvm.instrprof"; }
126 std::string message(int IE) const override {
127 return getInstrProfErrString(static_cast<instrprof_error>(IE));
131 } // end anonymous namespace
133 static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
135 const std::error_category &llvm::instrprof_category() {
136 return *ErrorCategory;
141 const char *InstrProfSectNameCommon[] = {
142 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
144 #include "llvm/ProfileData/InstrProfData.inc"
147 const char *InstrProfSectNameCoff[] = {
148 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
150 #include "llvm/ProfileData/InstrProfData.inc"
153 const char *InstrProfSectNamePrefix[] = {
154 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
156 #include "llvm/ProfileData/InstrProfData.inc"
163 std::string getInstrProfSectionName(InstrProfSectKind IPSK,
164 Triple::ObjectFormatType OF,
165 bool AddSegmentInfo) {
166 std::string SectName;
168 if (OF == Triple::MachO && AddSegmentInfo)
169 SectName = InstrProfSectNamePrefix[IPSK];
171 if (OF == Triple::COFF)
172 SectName += InstrProfSectNameCoff[IPSK];
174 SectName += InstrProfSectNameCommon[IPSK];
176 if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
177 SectName += ",regular,live_support";
182 void SoftInstrProfErrors::addError(instrprof_error IE) {
183 if (IE == instrprof_error::success)
186 if (FirstError == instrprof_error::success)
190 case instrprof_error::hash_mismatch:
193 case instrprof_error::count_mismatch:
194 ++NumCountMismatches;
196 case instrprof_error::counter_overflow:
197 ++NumCounterOverflows;
199 case instrprof_error::value_site_count_mismatch:
200 ++NumValueSiteCountMismatches;
203 llvm_unreachable("Not a soft error");
207 std::string InstrProfError::message() const {
208 return getInstrProfErrString(Err);
211 char InstrProfError::ID = 0;
213 std::string getPGOFuncName(StringRef RawFuncName,
214 GlobalValue::LinkageTypes Linkage,
216 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
217 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
220 // Strip NumPrefix level of directory name from PathNameStr. If the number of
221 // directory separators is less than NumPrefix, strip all the directories and
222 // leave base file name only.
223 static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
224 uint32_t Count = NumPrefix;
225 uint32_t Pos = 0, LastPos = 0;
226 for (auto & CI : PathNameStr) {
228 if (llvm::sys::path::is_separator(CI)) {
235 return PathNameStr.substr(LastPos);
238 // Return the PGOFuncName. This function has some special handling when called
239 // in LTO optimization. The following only applies when calling in LTO passes
240 // (when \c InLTO is true): LTO's internalization privatizes many global linkage
241 // symbols. This happens after value profile annotation, but those internal
242 // linkage functions should not have a source prefix.
243 // Additionally, for ThinLTO mode, exported internal functions are promoted
244 // and renamed. We need to ensure that the original internal PGO name is
245 // used when computing the GUID that is compared against the profiled GUIDs.
246 // To differentiate compiler generated internal symbols from original ones,
247 // PGOFuncName meta data are created and attached to the original internal
248 // symbols in the value profile annotation step
249 // (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
250 // data, its original linkage must be non-internal.
251 std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
253 StringRef FileName = (StaticFuncFullModulePrefix
254 ? F.getParent()->getName()
255 : sys::path::filename(F.getParent()->getName()));
256 if (StaticFuncFullModulePrefix && StaticFuncStripDirNamePrefix != 0)
257 FileName = stripDirPrefix(FileName, StaticFuncStripDirNamePrefix);
258 return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
261 // In LTO mode (when InLTO is true), first check if there is a meta data.
262 if (MDNode *MD = getPGOFuncNameMetadata(F)) {
263 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
267 // If there is no meta data, the function must be a global before the value
268 // profile annotation pass. Its current linkage may be internal if it is
269 // internalized in LTO mode.
270 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
273 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
274 if (FileName.empty())
276 // Drop the file name including ':'. See also getPGOFuncName.
277 if (PGOFuncName.startswith(FileName))
278 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
282 // \p FuncName is the string used as profile lookup key for the function. A
283 // symbol is created to hold the name. Return the legalized symbol name.
284 std::string getPGOFuncNameVarName(StringRef FuncName,
285 GlobalValue::LinkageTypes Linkage) {
286 std::string VarName = getInstrProfNameVarPrefix();
289 if (!GlobalValue::isLocalLinkage(Linkage))
292 // Now fix up illegal chars in local VarName that may upset the assembler.
293 const char *InvalidChars = "-:<>/\"'";
294 size_t found = VarName.find_first_of(InvalidChars);
295 while (found != std::string::npos) {
296 VarName[found] = '_';
297 found = VarName.find_first_of(InvalidChars, found + 1);
302 GlobalVariable *createPGOFuncNameVar(Module &M,
303 GlobalValue::LinkageTypes Linkage,
304 StringRef PGOFuncName) {
305 // We generally want to match the function's linkage, but available_externally
306 // and extern_weak both have the wrong semantics, and anything that doesn't
307 // need to link across compilation units doesn't need to be visible at all.
308 if (Linkage == GlobalValue::ExternalWeakLinkage)
309 Linkage = GlobalValue::LinkOnceAnyLinkage;
310 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
311 Linkage = GlobalValue::LinkOnceODRLinkage;
312 else if (Linkage == GlobalValue::InternalLinkage ||
313 Linkage == GlobalValue::ExternalLinkage)
314 Linkage = GlobalValue::PrivateLinkage;
317 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
319 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
320 getPGOFuncNameVarName(PGOFuncName, Linkage));
322 // Hide the symbol so that we correctly get a copy for each executable.
323 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
324 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
329 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
330 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
333 void InstrProfSymtab::create(Module &M, bool InLTO) {
334 for (Function &F : M) {
335 // Function may not have a name: like using asm("") to overwrite the name.
336 // Ignore in this case.
339 const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
340 addFuncName(PGOFuncName);
341 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
342 // In ThinLTO, local function may have been promoted to global and have
343 // suffix added to the function name. We need to add the stripped function
344 // name to the symbol table so that we can find a match from profile.
346 auto pos = PGOFuncName.find('.');
347 if (pos != std::string::npos) {
348 const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
349 addFuncName(OtherFuncName);
350 MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F);
358 Error collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
359 bool doCompression, std::string &Result) {
360 assert(!NameStrs.empty() && "No name data to emit");
362 uint8_t Header[16], *P = Header;
363 std::string UncompressedNameStrings =
364 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
366 assert(StringRef(UncompressedNameStrings)
367 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
368 "PGO name is invalid (contains separator token)");
370 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
373 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
374 EncLen = encodeULEB128(CompressedLen, P);
376 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
377 unsigned HeaderLen = P - &Header[0];
378 Result.append(HeaderStr, HeaderLen);
380 return Error::success();
383 if (!doCompression) {
384 return WriteStringToResult(0, UncompressedNameStrings);
387 SmallString<128> CompressedNameStrings;
388 Error E = zlib::compress(StringRef(UncompressedNameStrings),
389 CompressedNameStrings, zlib::BestSizeCompression);
391 consumeError(std::move(E));
392 return make_error<InstrProfError>(instrprof_error::compress_failed);
395 return WriteStringToResult(CompressedNameStrings.size(),
396 CompressedNameStrings);
399 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
400 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
402 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
406 Error collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
407 std::string &Result, bool doCompression) {
408 std::vector<std::string> NameStrs;
409 for (auto *NameVar : NameVars) {
410 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
412 return collectPGOFuncNameStrings(
413 NameStrs, zlib::isAvailable() && doCompression, Result);
416 Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
417 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
418 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
422 uint64_t UncompressedSize = decodeULEB128(P, &N);
424 uint64_t CompressedSize = decodeULEB128(P, &N);
426 bool isCompressed = (CompressedSize != 0);
427 SmallString<128> UncompressedNameStrings;
428 StringRef NameStrings;
430 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
433 zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
435 consumeError(std::move(E));
436 return make_error<InstrProfError>(instrprof_error::uncompress_failed);
439 NameStrings = StringRef(UncompressedNameStrings.data(),
440 UncompressedNameStrings.size());
443 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
444 P += UncompressedSize;
446 // Now parse the name strings.
447 SmallVector<StringRef, 0> Names;
448 NameStrings.split(Names, getInstrProfNameSeparator());
449 for (StringRef &Name : Names)
450 Symtab.addFuncName(Name);
452 while (P < EndP && *P == 0)
455 Symtab.finalizeSymtab();
456 return Error::success();
459 void InstrProfValueSiteRecord::merge(SoftInstrProfErrors &SIPE,
460 InstrProfValueSiteRecord &Input,
462 this->sortByTargetValues();
463 Input.sortByTargetValues();
464 auto I = ValueData.begin();
465 auto IE = ValueData.end();
466 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
468 while (I != IE && I->Value < J->Value)
470 if (I != IE && I->Value == J->Value) {
472 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
474 SIPE.addError(instrprof_error::counter_overflow);
478 ValueData.insert(I, *J);
482 void InstrProfValueSiteRecord::scale(SoftInstrProfErrors &SIPE,
484 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
486 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
488 SIPE.addError(instrprof_error::counter_overflow);
492 // Merge Value Profile data from Src record to this record for ValueKind.
493 // Scale merged value counts by \p Weight.
494 void InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
495 InstrProfRecord &Src,
497 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
498 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
499 if (ThisNumValueSites != OtherNumValueSites) {
500 SIPE.addError(instrprof_error::value_site_count_mismatch);
503 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
504 getValueSitesForKind(ValueKind);
505 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
506 Src.getValueSitesForKind(ValueKind);
507 for (uint32_t I = 0; I < ThisNumValueSites; I++)
508 ThisSiteRecords[I].merge(SIPE, OtherSiteRecords[I], Weight);
511 void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight) {
512 // If the number of counters doesn't match we either have bad data
513 // or a hash collision.
514 if (Counts.size() != Other.Counts.size()) {
515 SIPE.addError(instrprof_error::count_mismatch);
519 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
522 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
524 SIPE.addError(instrprof_error::counter_overflow);
527 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
528 mergeValueProfData(Kind, Other, Weight);
531 void InstrProfRecord::scaleValueProfData(uint32_t ValueKind, uint64_t Weight) {
532 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
533 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
534 getValueSitesForKind(ValueKind);
535 for (uint32_t I = 0; I < ThisNumValueSites; I++)
536 ThisSiteRecords[I].scale(SIPE, Weight);
539 void InstrProfRecord::scale(uint64_t Weight) {
540 for (auto &Count : this->Counts) {
542 Count = SaturatingMultiply(Count, Weight, &Overflowed);
544 SIPE.addError(instrprof_error::counter_overflow);
546 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
547 scaleValueProfData(Kind, Weight);
550 // Map indirect call target name hash to name string.
551 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
552 ValueMapType *ValueMap) {
556 case IPVK_IndirectCallTarget: {
558 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
559 [](const std::pair<uint64_t, uint64_t> &LHS,
560 uint64_t RHS) { return LHS.first < RHS; });
561 // Raw function pointer collected by value profiler may be from
562 // external functions that are not instrumented. They won't have
563 // mapping data to be used by the deserializer. Force the value to
564 // be 0 in this case.
565 if (Result != ValueMap->end() && Result->first == Value)
566 Value = (uint64_t)Result->second;
575 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
576 InstrProfValueData *VData, uint32_t N,
577 ValueMapType *ValueMap) {
578 for (uint32_t I = 0; I < N; I++) {
579 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
581 std::vector<InstrProfValueSiteRecord> &ValueSites =
582 getValueSitesForKind(ValueKind);
584 ValueSites.emplace_back();
586 ValueSites.emplace_back(VData, VData + N);
589 #define INSTR_PROF_COMMON_API_IMPL
590 #include "llvm/ProfileData/InstrProfData.inc"
593 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
594 * class. These C wrappers are used as adaptors so that C++ code can be
595 * invoked as callbacks.
597 uint32_t getNumValueKindsInstrProf(const void *Record) {
598 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
601 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
602 return reinterpret_cast<const InstrProfRecord *>(Record)
603 ->getNumValueSites(VKind);
606 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
607 return reinterpret_cast<const InstrProfRecord *>(Record)
608 ->getNumValueData(VKind);
611 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
613 return reinterpret_cast<const InstrProfRecord *>(R)
614 ->getNumValueDataForSite(VK, S);
617 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
618 uint32_t K, uint32_t S) {
619 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
622 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
624 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
625 memset(VD, 0, TotalSizeInBytes);
629 static ValueProfRecordClosure InstrProfRecordClosure = {
631 getNumValueKindsInstrProf,
632 getNumValueSitesInstrProf,
633 getNumValueDataInstrProf,
634 getNumValueDataForSiteInstrProf,
636 getValueForSiteInstrProf,
637 allocValueProfDataInstrProf};
639 // Wrapper implementation using the closure mechanism.
640 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
641 InstrProfRecordClosure.Record = &Record;
642 return getValueProfDataSize(&InstrProfRecordClosure);
645 // Wrapper implementation using the closure mechanism.
646 std::unique_ptr<ValueProfData>
647 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
648 InstrProfRecordClosure.Record = &Record;
650 std::unique_ptr<ValueProfData> VPD(
651 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
655 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
656 InstrProfRecord::ValueMapType *VMap) {
657 Record.reserveSites(Kind, NumValueSites);
659 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
660 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
661 uint8_t ValueDataCount = this->SiteCountArray[VSite];
662 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
663 ValueData += ValueDataCount;
667 // For writing/serializing, Old is the host endianness, and New is
668 // byte order intended on disk. For Reading/deserialization, Old
669 // is the on-disk source endianness, and New is the host endianness.
670 void ValueProfRecord::swapBytes(support::endianness Old,
671 support::endianness New) {
672 using namespace support;
677 if (getHostEndianness() != Old) {
678 sys::swapByteOrder<uint32_t>(NumValueSites);
679 sys::swapByteOrder<uint32_t>(Kind);
681 uint32_t ND = getValueProfRecordNumValueData(this);
682 InstrProfValueData *VD = getValueProfRecordValueData(this);
684 // No need to swap byte array: SiteCountArrray.
685 for (uint32_t I = 0; I < ND; I++) {
686 sys::swapByteOrder<uint64_t>(VD[I].Value);
687 sys::swapByteOrder<uint64_t>(VD[I].Count);
689 if (getHostEndianness() == Old) {
690 sys::swapByteOrder<uint32_t>(NumValueSites);
691 sys::swapByteOrder<uint32_t>(Kind);
695 void ValueProfData::deserializeTo(InstrProfRecord &Record,
696 InstrProfRecord::ValueMapType *VMap) {
697 if (NumValueKinds == 0)
700 ValueProfRecord *VR = getFirstValueProfRecord(this);
701 for (uint32_t K = 0; K < NumValueKinds; K++) {
702 VR->deserializeTo(Record, VMap);
703 VR = getValueProfRecordNext(VR);
708 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
709 using namespace support;
712 return endian::readNext<T, little, unaligned>(D);
714 return endian::readNext<T, big, unaligned>(D);
717 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
718 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
722 Error ValueProfData::checkIntegrity() {
723 if (NumValueKinds > IPVK_Last + 1)
724 return make_error<InstrProfError>(instrprof_error::malformed);
725 // Total size needs to be mulltiple of quadword size.
726 if (TotalSize % sizeof(uint64_t))
727 return make_error<InstrProfError>(instrprof_error::malformed);
729 ValueProfRecord *VR = getFirstValueProfRecord(this);
730 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
731 if (VR->Kind > IPVK_Last)
732 return make_error<InstrProfError>(instrprof_error::malformed);
733 VR = getValueProfRecordNext(VR);
734 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
735 return make_error<InstrProfError>(instrprof_error::malformed);
737 return Error::success();
740 Expected<std::unique_ptr<ValueProfData>>
741 ValueProfData::getValueProfData(const unsigned char *D,
742 const unsigned char *const BufferEnd,
743 support::endianness Endianness) {
744 using namespace support;
746 if (D + sizeof(ValueProfData) > BufferEnd)
747 return make_error<InstrProfError>(instrprof_error::truncated);
749 const unsigned char *Header = D;
750 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
751 if (D + TotalSize > BufferEnd)
752 return make_error<InstrProfError>(instrprof_error::too_large);
754 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
755 memcpy(VPD.get(), D, TotalSize);
757 VPD->swapBytesToHost(Endianness);
759 Error E = VPD->checkIntegrity();
763 return std::move(VPD);
766 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
767 using namespace support;
769 if (Endianness == getHostEndianness())
772 sys::swapByteOrder<uint32_t>(TotalSize);
773 sys::swapByteOrder<uint32_t>(NumValueKinds);
775 ValueProfRecord *VR = getFirstValueProfRecord(this);
776 for (uint32_t K = 0; K < NumValueKinds; K++) {
777 VR->swapBytes(Endianness, getHostEndianness());
778 VR = getValueProfRecordNext(VR);
782 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
783 using namespace support;
785 if (Endianness == getHostEndianness())
788 ValueProfRecord *VR = getFirstValueProfRecord(this);
789 for (uint32_t K = 0; K < NumValueKinds; K++) {
790 ValueProfRecord *NVR = getValueProfRecordNext(VR);
791 VR->swapBytes(getHostEndianness(), Endianness);
794 sys::swapByteOrder<uint32_t>(TotalSize);
795 sys::swapByteOrder<uint32_t>(NumValueKinds);
798 void annotateValueSite(Module &M, Instruction &Inst,
799 const InstrProfRecord &InstrProfR,
800 InstrProfValueKind ValueKind, uint32_t SiteIdx,
801 uint32_t MaxMDCount) {
802 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
807 std::unique_ptr<InstrProfValueData[]> VD =
808 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
810 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
811 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
814 void annotateValueSite(Module &M, Instruction &Inst,
815 ArrayRef<InstrProfValueData> VDs,
816 uint64_t Sum, InstrProfValueKind ValueKind,
817 uint32_t MaxMDCount) {
818 LLVMContext &Ctx = M.getContext();
819 MDBuilder MDHelper(Ctx);
820 SmallVector<Metadata *, 3> Vals;
822 Vals.push_back(MDHelper.createString("VP"));
824 Vals.push_back(MDHelper.createConstant(
825 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
828 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
830 // Value Profile Data
831 uint32_t MDCount = MaxMDCount;
832 for (auto &VD : VDs) {
833 Vals.push_back(MDHelper.createConstant(
834 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
835 Vals.push_back(MDHelper.createConstant(
836 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
840 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
843 bool getValueProfDataFromInst(const Instruction &Inst,
844 InstrProfValueKind ValueKind,
845 uint32_t MaxNumValueData,
846 InstrProfValueData ValueData[],
847 uint32_t &ActualNumValueData, uint64_t &TotalC) {
848 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
852 unsigned NOps = MD->getNumOperands();
857 // Operand 0 is a string tag "VP":
858 MDString *Tag = cast<MDString>(MD->getOperand(0));
862 if (!Tag->getString().equals("VP"))
866 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
869 if (KindInt->getZExtValue() != ValueKind)
873 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
876 TotalC = TotalCInt->getZExtValue();
878 ActualNumValueData = 0;
880 for (unsigned I = 3; I < NOps; I += 2) {
881 if (ActualNumValueData >= MaxNumValueData)
883 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
885 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
886 if (!Value || !Count)
888 ValueData[ActualNumValueData].Value = Value->getZExtValue();
889 ValueData[ActualNumValueData].Count = Count->getZExtValue();
890 ActualNumValueData++;
895 MDNode *getPGOFuncNameMetadata(const Function &F) {
896 return F.getMetadata(getPGOFuncNameMetadataName());
899 void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
900 // Only for internal linkage functions.
901 if (PGOFuncName == F.getName())
903 // Don't create duplicated meta-data.
904 if (getPGOFuncNameMetadata(F))
906 LLVMContext &C = F.getContext();
907 MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
908 F.setMetadata(getPGOFuncNameMetadataName(), N);
911 bool needsComdatForCounter(const Function &F, const Module &M) {
915 Triple TT(M.getTargetTriple());
916 if (!TT.isOSBinFormatELF() && !TT.isOSBinFormatWasm())
919 // See createPGOFuncNameVar for more details. To avoid link errors, profile
920 // counters for function with available_externally linkage needs to be changed
921 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
922 // created. Without using comdat, duplicate entries won't be removed by the
923 // linker leading to increased data segement size and raw profile size. Even
924 // worse, since the referenced counter from profile per-function data object
925 // will be resolved to the common strong definition, the profile counts for
926 // available_externally functions will end up being duplicated in raw profile
927 // data. This can result in distorted profile as the counts of those dups
928 // will be accumulated by the profile merger.
929 GlobalValue::LinkageTypes Linkage = F.getLinkage();
930 if (Linkage != GlobalValue::ExternalWeakLinkage &&
931 Linkage != GlobalValue::AvailableExternallyLinkage)
937 // Check if INSTR_PROF_RAW_VERSION_VAR is defined.
938 bool isIRPGOFlagSet(const Module *M) {
940 M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
941 if (!IRInstrVar || IRInstrVar->isDeclaration() ||
942 IRInstrVar->hasLocalLinkage())
945 // Check if the flag is set.
946 if (!IRInstrVar->hasInitializer())
949 const Constant *InitVal = IRInstrVar->getInitializer();
953 return (dyn_cast<ConstantInt>(InitVal)->getZExtValue() &
954 VARIANT_MASK_IR_PROF) != 0;
957 // Check if we can safely rename this Comdat function.
958 bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
959 if (F.getName().empty())
961 if (!needsComdatForCounter(F, *(F.getParent())))
963 // Unsafe to rename the address-taken function (which can be used in
964 // function comparison).
965 if (CheckAddressTaken && F.hasAddressTaken())
967 // Only safe to do if this function may be discarded if it is not used
968 // in the compilation unit.
969 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
972 // For AvailableExternallyLinkage functions.
973 if (!F.hasComdat()) {
974 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
980 // Parse the value profile options.
981 void getMemOPSizeRangeFromOption(std::string MemOPSizeRange,
982 int64_t &RangeStart, int64_t &RangeLast) {
983 static const int64_t DefaultMemOPSizeRangeStart = 0;
984 static const int64_t DefaultMemOPSizeRangeLast = 8;
985 RangeStart = DefaultMemOPSizeRangeStart;
986 RangeLast = DefaultMemOPSizeRangeLast;
988 if (!MemOPSizeRange.empty()) {
989 auto Pos = MemOPSizeRange.find(":");
990 if (Pos != std::string::npos) {
992 RangeStart = atoi(MemOPSizeRange.substr(0, Pos).c_str());
993 if (Pos < MemOPSizeRange.size() - 1)
994 RangeLast = atoi(MemOPSizeRange.substr(Pos + 1).c_str());
996 RangeLast = atoi(MemOPSizeRange.c_str());
998 assert(RangeLast >= RangeStart);
1001 } // end namespace llvm