1 //=-- InstrProf.cpp - Instrumented profiling format support -----------------=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for clang's instrumentation based PGO and
13 //===----------------------------------------------------------------------===//
15 #include "llvm/IR/Constants.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/IR/Module.h"
18 #include "llvm/IR/GlobalVariable.h"
19 #include "llvm/ProfileData/InstrProf.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/ManagedStatic.h"
26 class InstrProfErrorCategoryType : public std::error_category {
27 const char *name() const LLVM_NOEXCEPT override { return "llvm.instrprof"; }
28 std::string message(int IE) const override {
29 instrprof_error E = static_cast<instrprof_error>(IE);
31 case instrprof_error::success:
33 case instrprof_error::eof:
35 case instrprof_error::unrecognized_format:
36 return "Unrecognized instrumentation profile encoding format";
37 case instrprof_error::bad_magic:
38 return "Invalid instrumentation profile data (bad magic)";
39 case instrprof_error::bad_header:
40 return "Invalid instrumentation profile data (file header is corrupt)";
41 case instrprof_error::unsupported_version:
42 return "Unsupported instrumentation profile format version";
43 case instrprof_error::unsupported_hash_type:
44 return "Unsupported instrumentation profile hash type";
45 case instrprof_error::too_large:
46 return "Too much profile data";
47 case instrprof_error::truncated:
48 return "Truncated profile data";
49 case instrprof_error::malformed:
50 return "Malformed instrumentation profile data";
51 case instrprof_error::unknown_function:
52 return "No profile data available for function";
53 case instrprof_error::hash_mismatch:
54 return "Function control flow change detected (hash mismatch)";
55 case instrprof_error::count_mismatch:
56 return "Function basic block count change detected (counter mismatch)";
57 case instrprof_error::counter_overflow:
58 return "Counter overflow";
59 case instrprof_error::value_site_count_mismatch:
60 return "Function value site count change detected (counter mismatch)";
62 llvm_unreachable("A value of instrprof_error has no message.");
67 static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
69 const std::error_category &llvm::instrprof_category() {
70 return *ErrorCategory;
75 std::string getPGOFuncName(StringRef RawFuncName,
76 GlobalValue::LinkageTypes Linkage,
79 // Function names may be prefixed with a binary '1' to indicate
80 // that the backend should not modify the symbols due to any platform
81 // naming convention. Do not include that '1' in the PGO profile name.
82 if (RawFuncName[0] == '\1')
83 RawFuncName = RawFuncName.substr(1);
85 std::string FuncName = RawFuncName;
86 if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
87 // For local symbols, prepend the main file name to distinguish them.
88 // Do not include the full path in the file name since there's no guarantee
89 // that it will stay the same, e.g., if the files are checked out from
90 // version control in different locations.
92 FuncName = FuncName.insert(0, "<unknown>:");
94 FuncName = FuncName.insert(0, FileName.str() + ":");
99 std::string getPGOFuncName(const Function &F) {
100 return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName());
103 GlobalVariable *createPGOFuncNameVar(Module &M,
104 GlobalValue::LinkageTypes Linkage,
105 StringRef FuncName) {
107 // We generally want to match the function's linkage, but available_externally
108 // and extern_weak both have the wrong semantics, and anything that doesn't
109 // need to link across compilation units doesn't need to be visible at all.
110 if (Linkage == GlobalValue::ExternalWeakLinkage)
111 Linkage = GlobalValue::LinkOnceAnyLinkage;
112 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
113 Linkage = GlobalValue::LinkOnceODRLinkage;
114 else if (Linkage == GlobalValue::InternalLinkage ||
115 Linkage == GlobalValue::ExternalLinkage)
116 Linkage = GlobalValue::PrivateLinkage;
118 auto *Value = ConstantDataArray::getString(M.getContext(), FuncName, false);
120 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
121 Twine(getInstrProfNameVarPrefix()) + FuncName);
123 // Hide the symbol so that we correctly get a copy for each executable.
124 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
125 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
130 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName) {
131 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), FuncName);
134 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
135 InstrProfRecord::ValueMapType *VMap) {
136 Record.reserveSites(Kind, NumValueSites);
138 InstrProfValueData *ValueData = this->getValueData();
139 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
140 uint8_t ValueDataCount = this->SiteCountArray[VSite];
141 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
142 ValueData += ValueDataCount;
146 void ValueProfRecord::serializeFrom(const InstrProfRecord &Record,
148 uint32_t NumValueSites) {
150 this->NumValueSites = NumValueSites;
151 InstrProfValueData *DstVD = getValueData();
152 for (uint32_t S = 0; S < NumValueSites; S++) {
153 uint32_t ND = Record.getNumValueDataForSite(ValueKind, S);
154 SiteCountArray[S] = ND;
155 Record.getValueForSite(DstVD, ValueKind, S);
156 for (uint32_t I = 0; I < ND; I++) {
158 case IPVK_IndirectCallTarget:
159 DstVD[I].Value = IndexedInstrProf::ComputeHash(
160 IndexedInstrProf::HashType, (const char *)DstVD[I].Value);
163 llvm_unreachable("value kind not handled !");
171 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
172 using namespace support;
174 return endian::readNext<T, little, unaligned>(D);
176 return endian::readNext<T, big, unaligned>(D);
179 // For writing/serializing, Old is the host endianness, and New is
180 // byte order intended on disk. For Reading/deserialization, Old
181 // is the on-disk source endianness, and New is the host endianness.
182 void ValueProfRecord::swapBytes(support::endianness Old,
183 support::endianness New) {
184 using namespace support;
188 if (getHostEndianness() != Old) {
189 sys::swapByteOrder<uint32_t>(NumValueSites);
190 sys::swapByteOrder<uint32_t>(Kind);
192 uint32_t ND = getNumValueData();
193 InstrProfValueData *VD = getValueData();
195 // No need to swap byte array: SiteCountArrray.
196 for (uint32_t I = 0; I < ND; I++) {
197 sys::swapByteOrder<uint64_t>(VD[I].Value);
198 sys::swapByteOrder<uint64_t>(VD[I].Count);
200 if (getHostEndianness() == Old) {
201 sys::swapByteOrder<uint32_t>(NumValueSites);
202 sys::swapByteOrder<uint32_t>(Kind);
206 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
207 uint32_t TotalSize = sizeof(ValueProfData);
208 uint32_t NumValueKinds = Record.getNumValueKinds();
209 if (NumValueKinds == 0)
212 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; Kind++) {
213 uint32_t NumValueSites = Record.getNumValueSites(Kind);
217 getValueProfRecordSize(NumValueSites, Record.getNumValueData(Kind));
222 void ValueProfData::deserializeTo(InstrProfRecord &Record,
223 InstrProfRecord::ValueMapType *VMap) {
224 if (NumValueKinds == 0)
227 ValueProfRecord *VR = getFirstValueProfRecord();
228 for (uint32_t K = 0; K < NumValueKinds; K++) {
229 VR->deserializeTo(Record, VMap);
234 static std::unique_ptr<ValueProfData> AllocValueProfData(uint32_t TotalSize) {
235 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
239 std::unique_ptr<ValueProfData>
240 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
241 uint32_t TotalSize = getSize(Record);
243 std::unique_ptr<ValueProfData> VPD = AllocValueProfData(TotalSize);
245 VPD->TotalSize = TotalSize;
246 VPD->NumValueKinds = Record.getNumValueKinds();
247 ValueProfRecord *VR = VPD->getFirstValueProfRecord();
248 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; Kind++) {
249 uint32_t NumValueSites = Record.getNumValueSites(Kind);
252 VR->serializeFrom(Record, Kind, NumValueSites);
258 ErrorOr<std::unique_ptr<ValueProfData>>
259 ValueProfData::getValueProfData(const unsigned char *D,
260 const unsigned char *const BufferEnd,
261 support::endianness Endianness) {
262 using namespace support;
263 if (D + sizeof(ValueProfData) > BufferEnd)
264 return instrprof_error::truncated;
266 const unsigned char *Header = D;
267 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
268 uint32_t NumValueKinds = swapToHostOrder<uint32_t>(Header, Endianness);
270 if (D + TotalSize > BufferEnd)
271 return instrprof_error::too_large;
272 if (NumValueKinds > IPVK_Last + 1)
273 return instrprof_error::malformed;
274 // Total size needs to be mulltiple of quadword size.
275 if (TotalSize % sizeof(uint64_t))
276 return instrprof_error::malformed;
278 std::unique_ptr<ValueProfData> VPD = AllocValueProfData(TotalSize);
280 memcpy(VPD.get(), D, TotalSize);
282 VPD->swapBytesToHost(Endianness);
284 // Data integrety check:
285 ValueProfRecord *VR = VPD->getFirstValueProfRecord();
286 for (uint32_t K = 0; K < VPD->NumValueKinds; K++) {
287 if (VR->Kind > IPVK_Last)
288 return instrprof_error::malformed;
290 if ((char *)VR - (char *)VPD.get() > (ptrdiff_t)TotalSize)
291 return instrprof_error::malformed;
294 return std::move(VPD);
297 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
298 using namespace support;
299 if (Endianness == getHostEndianness())
302 sys::swapByteOrder<uint32_t>(TotalSize);
303 sys::swapByteOrder<uint32_t>(NumValueKinds);
305 ValueProfRecord *VR = getFirstValueProfRecord();
306 for (uint32_t K = 0; K < NumValueKinds; K++) {
307 VR->swapBytes(Endianness, getHostEndianness());
312 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
313 using namespace support;
314 if (Endianness == getHostEndianness())
317 ValueProfRecord *VR = getFirstValueProfRecord();
318 for (uint32_t K = 0; K < NumValueKinds; K++) {
319 ValueProfRecord *NVR = VR->getNext();
320 VR->swapBytes(getHostEndianness(), Endianness);
323 sys::swapByteOrder<uint32_t>(TotalSize);
324 sys::swapByteOrder<uint32_t>(NumValueKinds);
327 ValueProfRecord *ValueProfData::getFirstValueProfRecord() {
328 return reinterpret_cast<ValueProfRecord *>((char *)this +
329 sizeof(ValueProfData));
332 uint32_t ValueProfRecord::getNumValueData() const {
333 uint32_t NumValueData = 0;
334 for (uint32_t I = 0; I < NumValueSites; I++)
335 NumValueData += SiteCountArray[I];
339 ValueProfRecord *ValueProfRecord::getNext() {
340 return reinterpret_cast<ValueProfRecord *>((char *)this + getSize());
343 InstrProfValueData *ValueProfRecord::getValueData() {
344 return reinterpret_cast<InstrProfValueData *>(
345 (char *)this + getValueProfRecordHeaderSize(NumValueSites));