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 GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
86 // Return the PGOFuncName. This function has some special handling when called
87 // in LTO optimization. The following only applies when calling in LTO passes
88 // (when \c InLTO is true): LTO's internalization privatizes many global linkage
89 // symbols. This happens after value profile annotation, but those internal
90 // linkage functions should not have a source prefix.
91 // To differentiate compiler generated internal symbols from original ones,
92 // PGOFuncName meta data are created and attached to the original internal
93 // symbols in the value profile annotation step
94 // (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
95 // data, its original linkage must be non-internal.
96 std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
98 return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName(),
101 // In LTO mode (when InLTO is true), first check if there is a meta data.
102 if (MDNode *MD = getPGOFuncNameMetadata(F)) {
103 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
107 // If there is no meta data, the function must be a global before the value
108 // profile annotation pass. Its current linkage may be internal if it is
109 // internalized in LTO mode.
110 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
113 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
114 if (FileName.empty())
116 // Drop the file name including ':'. See also getPGOFuncName.
117 if (PGOFuncName.startswith(FileName))
118 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
122 // \p FuncName is the string used as profile lookup key for the function. A
123 // symbol is created to hold the name. Return the legalized symbol name.
124 std::string getPGOFuncNameVarName(StringRef FuncName,
125 GlobalValue::LinkageTypes Linkage) {
126 std::string VarName = getInstrProfNameVarPrefix();
129 if (!GlobalValue::isLocalLinkage(Linkage))
132 // Now fix up illegal chars in local VarName that may upset the assembler.
133 const char *InvalidChars = "-:<>\"'";
134 size_t found = VarName.find_first_of(InvalidChars);
135 while (found != std::string::npos) {
136 VarName[found] = '_';
137 found = VarName.find_first_of(InvalidChars, found + 1);
142 GlobalVariable *createPGOFuncNameVar(Module &M,
143 GlobalValue::LinkageTypes Linkage,
144 StringRef PGOFuncName) {
146 // We generally want to match the function's linkage, but available_externally
147 // and extern_weak both have the wrong semantics, and anything that doesn't
148 // need to link across compilation units doesn't need to be visible at all.
149 if (Linkage == GlobalValue::ExternalWeakLinkage)
150 Linkage = GlobalValue::LinkOnceAnyLinkage;
151 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
152 Linkage = GlobalValue::LinkOnceODRLinkage;
153 else if (Linkage == GlobalValue::InternalLinkage ||
154 Linkage == GlobalValue::ExternalLinkage)
155 Linkage = GlobalValue::PrivateLinkage;
158 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
160 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
161 getPGOFuncNameVarName(PGOFuncName, Linkage));
163 // Hide the symbol so that we correctly get a copy for each executable.
164 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
165 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
170 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
171 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
174 void InstrProfSymtab::create(Module &M, bool InLTO) {
175 for (Function &F : M) {
176 // Function may not have a name: like using asm("") to overwrite the name.
177 // Ignore in this case.
180 const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
181 addFuncName(PGOFuncName);
182 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
188 int collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
189 bool doCompression, std::string &Result) {
190 assert(NameStrs.size() && "No name data to emit");
192 uint8_t Header[16], *P = Header;
193 std::string UncompressedNameStrings =
194 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
196 assert(StringRef(UncompressedNameStrings)
197 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
198 "PGO name is invalid (contains separator token)");
200 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
203 auto WriteStringToResult = [&](size_t CompressedLen,
204 const std::string &InputStr) {
205 EncLen = encodeULEB128(CompressedLen, P);
207 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
208 unsigned HeaderLen = P - &Header[0];
209 Result.append(HeaderStr, HeaderLen);
215 return WriteStringToResult(0, UncompressedNameStrings);
217 SmallVector<char, 128> CompressedNameStrings;
218 zlib::Status Success =
219 zlib::compress(StringRef(UncompressedNameStrings), CompressedNameStrings,
220 zlib::BestSizeCompression);
222 if (Success != zlib::StatusOK)
225 return WriteStringToResult(
226 CompressedNameStrings.size(),
227 std::string(CompressedNameStrings.data(), CompressedNameStrings.size()));
230 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
231 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
233 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
237 int collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
238 std::string &Result, bool doCompression) {
239 std::vector<std::string> NameStrs;
240 for (auto *NameVar : NameVars) {
241 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
243 return collectPGOFuncNameStrings(
244 NameStrs, zlib::isAvailable() && doCompression, Result);
247 int readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
248 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
249 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
253 uint64_t UncompressedSize = decodeULEB128(P, &N);
255 uint64_t CompressedSize = decodeULEB128(P, &N);
257 bool isCompressed = (CompressedSize != 0);
258 SmallString<128> UncompressedNameStrings;
259 StringRef NameStrings;
261 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
263 if (zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
264 UncompressedSize) != zlib::StatusOK)
267 NameStrings = StringRef(UncompressedNameStrings.data(),
268 UncompressedNameStrings.size());
271 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
272 P += UncompressedSize;
274 // Now parse the name strings.
275 SmallVector<StringRef, 0> Names;
276 NameStrings.split(Names, getInstrProfNameSeparator());
277 for (StringRef &Name : Names)
278 Symtab.addFuncName(Name);
280 while (P < EndP && *P == 0)
283 Symtab.finalizeSymtab();
287 instrprof_error InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
289 this->sortByTargetValues();
290 Input.sortByTargetValues();
291 auto I = ValueData.begin();
292 auto IE = ValueData.end();
293 instrprof_error Result = instrprof_error::success;
294 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
296 while (I != IE && I->Value < J->Value)
298 if (I != IE && I->Value == J->Value) {
300 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
302 Result = instrprof_error::counter_overflow;
306 ValueData.insert(I, *J);
311 instrprof_error InstrProfValueSiteRecord::scale(uint64_t Weight) {
312 instrprof_error Result = instrprof_error::success;
313 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
315 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
317 Result = instrprof_error::counter_overflow;
322 // Merge Value Profile data from Src record to this record for ValueKind.
323 // Scale merged value counts by \p Weight.
324 instrprof_error InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
325 InstrProfRecord &Src,
327 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
328 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
329 if (ThisNumValueSites != OtherNumValueSites)
330 return instrprof_error::value_site_count_mismatch;
331 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
332 getValueSitesForKind(ValueKind);
333 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
334 Src.getValueSitesForKind(ValueKind);
335 instrprof_error Result = instrprof_error::success;
336 for (uint32_t I = 0; I < ThisNumValueSites; I++)
337 MergeResult(Result, ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight));
341 instrprof_error InstrProfRecord::merge(InstrProfRecord &Other,
343 // If the number of counters doesn't match we either have bad data
344 // or a hash collision.
345 if (Counts.size() != Other.Counts.size())
346 return instrprof_error::count_mismatch;
348 instrprof_error Result = instrprof_error::success;
350 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
353 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
355 Result = instrprof_error::counter_overflow;
358 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
359 MergeResult(Result, mergeValueProfData(Kind, Other, Weight));
364 instrprof_error InstrProfRecord::scaleValueProfData(uint32_t ValueKind,
366 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
367 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
368 getValueSitesForKind(ValueKind);
369 instrprof_error Result = instrprof_error::success;
370 for (uint32_t I = 0; I < ThisNumValueSites; I++)
371 MergeResult(Result, ThisSiteRecords[I].scale(Weight));
375 instrprof_error InstrProfRecord::scale(uint64_t Weight) {
376 instrprof_error Result = instrprof_error::success;
377 for (auto &Count : this->Counts) {
379 Count = SaturatingMultiply(Count, Weight, &Overflowed);
380 if (Overflowed && Result == instrprof_error::success) {
381 Result = instrprof_error::counter_overflow;
384 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
385 MergeResult(Result, scaleValueProfData(Kind, Weight));
390 // Map indirect call target name hash to name string.
391 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
392 ValueMapType *ValueMap) {
396 case IPVK_IndirectCallTarget: {
398 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
399 [](const std::pair<uint64_t, uint64_t> &LHS,
400 uint64_t RHS) { return LHS.first < RHS; });
401 if (Result != ValueMap->end())
402 Value = (uint64_t)Result->second;
409 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
410 InstrProfValueData *VData, uint32_t N,
411 ValueMapType *ValueMap) {
412 for (uint32_t I = 0; I < N; I++) {
413 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
415 std::vector<InstrProfValueSiteRecord> &ValueSites =
416 getValueSitesForKind(ValueKind);
418 ValueSites.push_back(InstrProfValueSiteRecord());
420 ValueSites.emplace_back(VData, VData + N);
423 #define INSTR_PROF_COMMON_API_IMPL
424 #include "llvm/ProfileData/InstrProfData.inc"
427 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
428 * class. These C wrappers are used as adaptors so that C++ code can be
429 * invoked as callbacks.
431 uint32_t getNumValueKindsInstrProf(const void *Record) {
432 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
435 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
436 return reinterpret_cast<const InstrProfRecord *>(Record)
437 ->getNumValueSites(VKind);
440 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
441 return reinterpret_cast<const InstrProfRecord *>(Record)
442 ->getNumValueData(VKind);
445 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
447 return reinterpret_cast<const InstrProfRecord *>(R)
448 ->getNumValueDataForSite(VK, S);
451 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
452 uint32_t K, uint32_t S) {
453 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
457 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
459 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
460 memset(VD, 0, TotalSizeInBytes);
464 static ValueProfRecordClosure InstrProfRecordClosure = {
466 getNumValueKindsInstrProf,
467 getNumValueSitesInstrProf,
468 getNumValueDataInstrProf,
469 getNumValueDataForSiteInstrProf,
471 getValueForSiteInstrProf,
472 allocValueProfDataInstrProf};
474 // Wrapper implementation using the closure mechanism.
475 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
476 InstrProfRecordClosure.Record = &Record;
477 return getValueProfDataSize(&InstrProfRecordClosure);
480 // Wrapper implementation using the closure mechanism.
481 std::unique_ptr<ValueProfData>
482 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
483 InstrProfRecordClosure.Record = &Record;
485 std::unique_ptr<ValueProfData> VPD(
486 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
490 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
491 InstrProfRecord::ValueMapType *VMap) {
492 Record.reserveSites(Kind, NumValueSites);
494 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
495 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
496 uint8_t ValueDataCount = this->SiteCountArray[VSite];
497 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
498 ValueData += ValueDataCount;
502 // For writing/serializing, Old is the host endianness, and New is
503 // byte order intended on disk. For Reading/deserialization, Old
504 // is the on-disk source endianness, and New is the host endianness.
505 void ValueProfRecord::swapBytes(support::endianness Old,
506 support::endianness New) {
507 using namespace support;
511 if (getHostEndianness() != Old) {
512 sys::swapByteOrder<uint32_t>(NumValueSites);
513 sys::swapByteOrder<uint32_t>(Kind);
515 uint32_t ND = getValueProfRecordNumValueData(this);
516 InstrProfValueData *VD = getValueProfRecordValueData(this);
518 // No need to swap byte array: SiteCountArrray.
519 for (uint32_t I = 0; I < ND; I++) {
520 sys::swapByteOrder<uint64_t>(VD[I].Value);
521 sys::swapByteOrder<uint64_t>(VD[I].Count);
523 if (getHostEndianness() == Old) {
524 sys::swapByteOrder<uint32_t>(NumValueSites);
525 sys::swapByteOrder<uint32_t>(Kind);
529 void ValueProfData::deserializeTo(InstrProfRecord &Record,
530 InstrProfRecord::ValueMapType *VMap) {
531 if (NumValueKinds == 0)
534 ValueProfRecord *VR = getFirstValueProfRecord(this);
535 for (uint32_t K = 0; K < NumValueKinds; K++) {
536 VR->deserializeTo(Record, VMap);
537 VR = getValueProfRecordNext(VR);
542 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
543 using namespace support;
545 return endian::readNext<T, little, unaligned>(D);
547 return endian::readNext<T, big, unaligned>(D);
550 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
551 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
555 instrprof_error ValueProfData::checkIntegrity() {
556 if (NumValueKinds > IPVK_Last + 1)
557 return instrprof_error::malformed;
558 // Total size needs to be mulltiple of quadword size.
559 if (TotalSize % sizeof(uint64_t))
560 return instrprof_error::malformed;
562 ValueProfRecord *VR = getFirstValueProfRecord(this);
563 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
564 if (VR->Kind > IPVK_Last)
565 return instrprof_error::malformed;
566 VR = getValueProfRecordNext(VR);
567 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
568 return instrprof_error::malformed;
570 return instrprof_error::success;
573 ErrorOr<std::unique_ptr<ValueProfData>>
574 ValueProfData::getValueProfData(const unsigned char *D,
575 const unsigned char *const BufferEnd,
576 support::endianness Endianness) {
577 using namespace support;
578 if (D + sizeof(ValueProfData) > BufferEnd)
579 return instrprof_error::truncated;
581 const unsigned char *Header = D;
582 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
583 if (D + TotalSize > BufferEnd)
584 return instrprof_error::too_large;
586 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
587 memcpy(VPD.get(), D, TotalSize);
589 VPD->swapBytesToHost(Endianness);
591 instrprof_error EC = VPD->checkIntegrity();
592 if (EC != instrprof_error::success)
595 return std::move(VPD);
598 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
599 using namespace support;
600 if (Endianness == getHostEndianness())
603 sys::swapByteOrder<uint32_t>(TotalSize);
604 sys::swapByteOrder<uint32_t>(NumValueKinds);
606 ValueProfRecord *VR = getFirstValueProfRecord(this);
607 for (uint32_t K = 0; K < NumValueKinds; K++) {
608 VR->swapBytes(Endianness, getHostEndianness());
609 VR = getValueProfRecordNext(VR);
613 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
614 using namespace support;
615 if (Endianness == getHostEndianness())
618 ValueProfRecord *VR = getFirstValueProfRecord(this);
619 for (uint32_t K = 0; K < NumValueKinds; K++) {
620 ValueProfRecord *NVR = getValueProfRecordNext(VR);
621 VR->swapBytes(getHostEndianness(), Endianness);
624 sys::swapByteOrder<uint32_t>(TotalSize);
625 sys::swapByteOrder<uint32_t>(NumValueKinds);
628 void annotateValueSite(Module &M, Instruction &Inst,
629 const InstrProfRecord &InstrProfR,
630 InstrProfValueKind ValueKind, uint32_t SiteIdx,
631 uint32_t MaxMDCount) {
632 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
635 std::unique_ptr<InstrProfValueData[]> VD =
636 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
638 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
639 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
642 void annotateValueSite(Module &M, Instruction &Inst,
643 ArrayRef<InstrProfValueData> VDs,
644 uint64_t Sum, InstrProfValueKind ValueKind,
645 uint32_t MaxMDCount) {
646 LLVMContext &Ctx = M.getContext();
647 MDBuilder MDHelper(Ctx);
648 SmallVector<Metadata *, 3> Vals;
650 Vals.push_back(MDHelper.createString("VP"));
652 Vals.push_back(MDHelper.createConstant(
653 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
656 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
658 // Value Profile Data
659 uint32_t MDCount = MaxMDCount;
660 for (auto &VD : VDs) {
661 Vals.push_back(MDHelper.createConstant(
662 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
663 Vals.push_back(MDHelper.createConstant(
664 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
668 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
671 bool getValueProfDataFromInst(const Instruction &Inst,
672 InstrProfValueKind ValueKind,
673 uint32_t MaxNumValueData,
674 InstrProfValueData ValueData[],
675 uint32_t &ActualNumValueData, uint64_t &TotalC) {
676 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
680 unsigned NOps = MD->getNumOperands();
685 // Operand 0 is a string tag "VP":
686 MDString *Tag = cast<MDString>(MD->getOperand(0));
690 if (!Tag->getString().equals("VP"))
694 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
697 if (KindInt->getZExtValue() != ValueKind)
701 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
704 TotalC = TotalCInt->getZExtValue();
706 ActualNumValueData = 0;
708 for (unsigned I = 3; I < NOps; I += 2) {
709 if (ActualNumValueData >= MaxNumValueData)
711 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
713 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
714 if (!Value || !Count)
716 ValueData[ActualNumValueData].Value = Value->getZExtValue();
717 ValueData[ActualNumValueData].Count = Count->getZExtValue();
718 ActualNumValueData++;
723 MDNode *getPGOFuncNameMetadata(const Function &F) {
724 return F.getMetadata(getPGOFuncNameMetadataName());
727 void createPGOFuncNameMetadata(Function &F) {
728 const std::string &FuncName = getPGOFuncName(F);
729 if (FuncName == F.getName())
732 LLVMContext &C = F.getContext();
733 MDNode *N = MDNode::get(C, MDString::get(C, FuncName.c_str()));
734 F.setMetadata(getPGOFuncNameMetadataName(), N);
737 } // end namespace llvm