blob: 66ac03770e7474f664f41103b851972feea7897b [file] [log] [blame]
Justin Bognerf8d79192014-03-21 17:24:48 +00001//=-- InstrProf.cpp - Instrumented profiling format support -----------------=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains support for clang's instrumentation based PGO and
11// coverage.
12//
13//===----------------------------------------------------------------------===//
14
Xinliang David Lie413f1a2015-12-31 07:57:16 +000015#include "llvm/ProfileData/InstrProf.h"
Xinliang David Li0c677872016-01-04 21:31:09 +000016#include "llvm/ADT/StringExtras.h"
Xinliang David Li441959d2015-11-09 00:01:22 +000017#include "llvm/IR/Constants.h"
18#include "llvm/IR/Function.h"
Xinliang David Li441959d2015-11-09 00:01:22 +000019#include "llvm/IR/GlobalVariable.h"
Xinliang David Li402477d2016-02-04 19:11:43 +000020#include "llvm/IR/MDBuilder.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000021#include "llvm/IR/Module.h"
22#include "llvm/Support/Compression.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000023#include "llvm/Support/ErrorHandling.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000024#include "llvm/Support/LEB128.h"
Chris Bieneman1efe8012014-09-19 23:19:24 +000025#include "llvm/Support/ManagedStatic.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000026
27using namespace llvm;
28
29namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +000030class InstrProfErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +000031 const char *name() const LLVM_NOEXCEPT override { return "llvm.instrprof"; }
Justin Bognerf8d79192014-03-21 17:24:48 +000032 std::string message(int IE) const override {
Rafael Espindola92512e82014-06-03 05:12:33 +000033 instrprof_error E = static_cast<instrprof_error>(IE);
Justin Bognerf8d79192014-03-21 17:24:48 +000034 switch (E) {
35 case instrprof_error::success:
36 return "Success";
37 case instrprof_error::eof:
38 return "End of File";
Nathan Slingerland4f823662015-11-13 03:47:58 +000039 case instrprof_error::unrecognized_format:
40 return "Unrecognized instrumentation profile encoding format";
Justin Bognerf8d79192014-03-21 17:24:48 +000041 case instrprof_error::bad_magic:
Nathan Slingerland4f823662015-11-13 03:47:58 +000042 return "Invalid instrumentation profile data (bad magic)";
Duncan P. N. Exon Smith531bb482014-03-21 20:42:28 +000043 case instrprof_error::bad_header:
Nathan Slingerland4f823662015-11-13 03:47:58 +000044 return "Invalid instrumentation profile data (file header is corrupt)";
Justin Bognerf8d79192014-03-21 17:24:48 +000045 case instrprof_error::unsupported_version:
Nathan Slingerland4f823662015-11-13 03:47:58 +000046 return "Unsupported instrumentation profile format version";
Justin Bognerb7aa2632014-04-18 21:48:40 +000047 case instrprof_error::unsupported_hash_type:
Nathan Slingerland4f823662015-11-13 03:47:58 +000048 return "Unsupported instrumentation profile hash type";
Justin Bognerf8d79192014-03-21 17:24:48 +000049 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:
Nathan Slingerland4f823662015-11-13 03:47:58 +000054 return "Malformed instrumentation profile data";
Justin Bognerf8d79192014-03-21 17:24:48 +000055 case instrprof_error::unknown_function:
56 return "No profile data available for function";
Justin Bognerb9bd7f82014-03-21 17:46:22 +000057 case instrprof_error::hash_mismatch:
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000058 return "Function control flow change detected (hash mismatch)";
Justin Bognerb9bd7f82014-03-21 17:46:22 +000059 case instrprof_error::count_mismatch:
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000060 return "Function basic block count change detected (counter mismatch)";
Justin Bognerb9bd7f82014-03-21 17:46:22 +000061 case instrprof_error::counter_overflow:
62 return "Counter overflow";
Justin Bogner9e9a0572015-09-29 22:13:58 +000063 case instrprof_error::value_site_count_mismatch:
Nathan Slingerlande6e30d52015-11-17 22:08:53 +000064 return "Function value site count change detected (counter mismatch)";
Justin Bognerf8d79192014-03-21 17:24:48 +000065 }
66 llvm_unreachable("A value of instrprof_error has no message.");
67 }
Justin Bognerf8d79192014-03-21 17:24:48 +000068};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000069} // end anonymous namespace
Justin Bognerf8d79192014-03-21 17:24:48 +000070
Chris Bieneman1efe8012014-09-19 23:19:24 +000071static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
72
Rafael Espindola25188c92014-06-12 01:45:43 +000073const std::error_category &llvm::instrprof_category() {
Chris Bieneman1efe8012014-09-19 23:19:24 +000074 return *ErrorCategory;
Justin Bognerf8d79192014-03-21 17:24:48 +000075}
Xinliang David Li441959d2015-11-09 00:01:22 +000076
77namespace llvm {
78
79std::string getPGOFuncName(StringRef RawFuncName,
80 GlobalValue::LinkageTypes Linkage,
Xinliang David Lia86545b2015-12-11 20:23:22 +000081 StringRef FileName,
82 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
Teresa Johnsonb43027d2016-03-15 02:13:19 +000083 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
Xinliang David Li441959d2015-11-09 00:01:22 +000084}
85
Xinliang David Li307902e2015-12-05 05:16:36 +000086std::string getPGOFuncName(const Function &F, uint64_t Version) {
87 return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName(),
88 Version);
Xinliang David Li441959d2015-11-09 00:01:22 +000089}
90
Xinliang David Li4ec40142015-12-15 19:44:45 +000091StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
92 if (FileName.empty())
93 return PGOFuncName;
94 // Drop the file name including ':'. See also getPGOFuncName.
95 if (PGOFuncName.startswith(FileName))
96 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
97 return PGOFuncName;
98}
99
Xinliang David Lid1bab962015-12-12 17:28:03 +0000100// \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.
102static std::string getPGOFuncNameVarName(StringRef FuncName,
103 GlobalValue::LinkageTypes Linkage) {
104 std::string VarName = getInstrProfNameVarPrefix();
105 VarName += FuncName;
106
107 if (!GlobalValue::isLocalLinkage(Linkage))
108 return VarName;
109
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);
116 }
117 return VarName;
118}
119
Xinliang David Li441959d2015-11-09 00:01:22 +0000120GlobalVariable *createPGOFuncNameVar(Module &M,
121 GlobalValue::LinkageTypes Linkage,
122 StringRef FuncName) {
123
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;
134
135 auto *Value = ConstantDataArray::getString(M.getContext(), FuncName, false);
136 auto FuncNameVar =
137 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
Xinliang David Lid1bab962015-12-12 17:28:03 +0000138 getPGOFuncNameVarName(FuncName, Linkage));
Xinliang David Li441959d2015-11-09 00:01:22 +0000139
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);
143
144 return FuncNameVar;
145}
146
147GlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName) {
148 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), FuncName);
149}
Xinliang David Liee415892015-11-10 00:24:45 +0000150
Xinliang David Li59411db2016-01-20 01:26:34 +0000151void InstrProfSymtab::create(const Module &M) {
152 for (const Function &F : M)
153 addFuncName(getPGOFuncName(F));
154
155 finalizeSymtab();
156}
157
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000158int collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
159 bool doCompression, std::string &Result) {
160 uint8_t Header[16], *P = Header;
Xinliang David Li0c677872016-01-04 21:31:09 +0000161 std::string UncompressedNameStrings =
162 join(NameStrs.begin(), NameStrs.end(), StringRef(" "));
Xinliang David Li13ea29b2016-01-04 20:26:05 +0000163
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000164 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
165 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000166
167 auto WriteStringToResult = [&](size_t CompressedLen,
168 const std::string &InputStr) {
169 EncLen = encodeULEB128(CompressedLen, P);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000170 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000171 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
172 unsigned HeaderLen = P - &Header[0];
173 Result.append(HeaderStr, HeaderLen);
174 Result += InputStr;
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000175 return 0;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000176 };
177
178 if (!doCompression)
179 return WriteStringToResult(0, UncompressedNameStrings);
180
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000181 SmallVector<char, 128> CompressedNameStrings;
182 zlib::Status Success =
183 zlib::compress(StringRef(UncompressedNameStrings), CompressedNameStrings,
184 zlib::BestSizeCompression);
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000185
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000186 if (Success != zlib::StatusOK)
187 return 1;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000188
189 return WriteStringToResult(
190 CompressedNameStrings.size(),
191 std::string(CompressedNameStrings.data(), CompressedNameStrings.size()));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000192}
193
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000194StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
Xinliang David Li37c1fa02016-01-03 04:38:13 +0000195 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
196 StringRef NameStr =
197 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
198 return NameStr;
199}
200
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000201int collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
Xinliang David Li73163752016-01-26 23:13:00 +0000202 std::string &Result, bool doCompression) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000203 std::vector<std::string> NameStrs;
204 for (auto *NameVar : NameVars) {
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000205 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000206 }
Xinliang David Li73163752016-01-26 23:13:00 +0000207 return collectPGOFuncNameStrings(
208 NameStrs, zlib::isAvailable() && doCompression, Result);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000209}
210
211int 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() +
214 NameStrings.size());
215 while (P < EndP) {
216 uint32_t N;
217 uint64_t UncompressedSize = decodeULEB128(P, &N);
218 P += N;
219 uint64_t CompressedSize = decodeULEB128(P, &N);
220 P += N;
221 bool isCompressed = (CompressedSize != 0);
222 SmallString<128> UncompressedNameStrings;
223 StringRef NameStrings;
224 if (isCompressed) {
225 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
226 CompressedSize);
227 if (zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
228 UncompressedSize) != zlib::StatusOK)
229 return 1;
230 P += CompressedSize;
231 NameStrings = StringRef(UncompressedNameStrings.data(),
232 UncompressedNameStrings.size());
233 } else {
234 NameStrings =
235 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
236 P += UncompressedSize;
237 }
238 // Now parse the name strings.
Xinliang David Li204efe22016-01-04 22:09:26 +0000239 SmallVector<StringRef, 0> Names;
240 NameStrings.split(Names, ' ');
241 for (StringRef &Name : Names)
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000242 Symtab.addFuncName(Name);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000243
244 while (P < EndP && *P == 0)
245 P++;
246 }
247 Symtab.finalizeSymtab();
248 return 0;
249}
250
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000251instrprof_error InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
252 uint64_t Weight) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000253 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;
259 ++J) {
260 while (I != IE && I->Value < J->Value)
261 ++I;
262 if (I != IE && I->Value == J->Value) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000263 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000264 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000265 if (Overflowed)
266 Result = instrprof_error::counter_overflow;
267 ++I;
268 continue;
269 }
270 ValueData.insert(I, *J);
271 }
272 return Result;
273}
274
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000275instrprof_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) {
278 bool Overflowed;
279 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
280 if (Overflowed)
281 Result = instrprof_error::counter_overflow;
282 }
283 return Result;
284}
285
Xinliang David Li020f22d2015-12-18 23:06:37 +0000286// Merge Value Profile data from Src record to this record for ValueKind.
287// Scale merged value counts by \p Weight.
288instrprof_error InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
289 InstrProfRecord &Src,
290 uint64_t Weight) {
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++)
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000301 MergeResult(Result, ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight));
Xinliang David Li020f22d2015-12-18 23:06:37 +0000302 return Result;
303}
304
305instrprof_error InstrProfRecord::merge(InstrProfRecord &Other,
306 uint64_t Weight) {
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;
311
312 instrprof_error Result = instrprof_error::success;
313
314 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
315 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000316 Counts[I] =
317 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000318 if (Overflowed)
319 Result = instrprof_error::counter_overflow;
320 }
321
322 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
323 MergeResult(Result, mergeValueProfData(Kind, Other, Weight));
324
325 return Result;
326}
Xinliang David Lia716cc52015-12-20 06:22:13 +0000327
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000328instrprof_error InstrProfRecord::scaleValueProfData(uint32_t ValueKind,
329 uint64_t Weight) {
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));
336 return Result;
337}
338
339instrprof_error InstrProfRecord::scale(uint64_t Weight) {
340 instrprof_error Result = instrprof_error::success;
341 for (auto &Count : this->Counts) {
342 bool Overflowed;
343 Count = SaturatingMultiply(Count, Weight, &Overflowed);
344 if (Overflowed && Result == instrprof_error::success) {
345 Result = instrprof_error::counter_overflow;
346 }
347 }
348 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
349 MergeResult(Result, scaleValueProfData(Kind, Weight));
350
351 return Result;
352}
353
Xinliang David Li020f22d2015-12-18 23:06:37 +0000354// Map indirect call target name hash to name string.
355uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000356 ValueMapType *ValueMap) {
357 if (!ValueMap)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000358 return Value;
359 switch (ValueKind) {
360 case IPVK_IndirectCallTarget: {
361 auto Result =
Xinliang David Lia716cc52015-12-20 06:22:13 +0000362 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
363 [](const std::pair<uint64_t, uint64_t> &LHS,
Xinliang David Li020f22d2015-12-18 23:06:37 +0000364 uint64_t RHS) { return LHS.first < RHS; });
Xinliang David Lia716cc52015-12-20 06:22:13 +0000365 if (Result != ValueMap->end())
Xinliang David Li020f22d2015-12-18 23:06:37 +0000366 Value = (uint64_t)Result->second;
367 break;
368 }
369 }
370 return Value;
371}
372
Xinliang David Li020f22d2015-12-18 23:06:37 +0000373void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
374 InstrProfValueData *VData, uint32_t N,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000375 ValueMapType *ValueMap) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000376 for (uint32_t I = 0; I < N; I++) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000377 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000378 }
379 std::vector<InstrProfValueSiteRecord> &ValueSites =
380 getValueSitesForKind(ValueKind);
381 if (N == 0)
382 ValueSites.push_back(InstrProfValueSiteRecord());
383 else
384 ValueSites.emplace_back(VData, VData + N);
385}
386
Xinliang David Lib75544a2015-11-28 19:07:09 +0000387#define INSTR_PROF_COMMON_API_IMPL
388#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Liee415892015-11-10 00:24:45 +0000389
Xinliang David Li020f22d2015-12-18 23:06:37 +0000390/*!
Xinliang David Lib75544a2015-11-28 19:07:09 +0000391 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
Xinliang David Lied966772015-11-25 23:31:18 +0000392 * class. These C wrappers are used as adaptors so that C++ code can be
393 * invoked as callbacks.
394 */
Xinliang David Lif47cf552015-11-25 06:23:38 +0000395uint32_t getNumValueKindsInstrProf(const void *Record) {
396 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
397}
398
399uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
400 return reinterpret_cast<const InstrProfRecord *>(Record)
401 ->getNumValueSites(VKind);
402}
403
404uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
405 return reinterpret_cast<const InstrProfRecord *>(Record)
406 ->getNumValueData(VKind);
407}
408
409uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
410 uint32_t S) {
411 return reinterpret_cast<const InstrProfRecord *>(R)
412 ->getNumValueDataForSite(VK, S);
413}
414
415void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
Xinliang David Li1e4c8092016-02-04 05:29:51 +0000416 uint32_t K, uint32_t S) {
417 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
418 return;
Xinliang David Lie8092312015-11-25 19:13:00 +0000419}
420
Xinliang David Lif47cf552015-11-25 06:23:38 +0000421ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
Xinliang David Li38b9a322015-12-15 21:57:08 +0000422 ValueProfData *VD =
423 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
424 memset(VD, 0, TotalSizeInBytes);
425 return VD;
Xinliang David Lif47cf552015-11-25 06:23:38 +0000426}
427
428static ValueProfRecordClosure InstrProfRecordClosure = {
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000429 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000430 getNumValueKindsInstrProf,
431 getNumValueSitesInstrProf,
432 getNumValueDataInstrProf,
433 getNumValueDataForSiteInstrProf,
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000434 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000435 getValueForSiteInstrProf,
Xinliang David Li38b9a322015-12-15 21:57:08 +0000436 allocValueProfDataInstrProf};
Xinliang David Lif47cf552015-11-25 06:23:38 +0000437
Xinliang David Lie8092312015-11-25 19:13:00 +0000438// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000439uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
440 InstrProfRecordClosure.Record = &Record;
441 return getValueProfDataSize(&InstrProfRecordClosure);
442}
443
Xinliang David Lie8092312015-11-25 19:13:00 +0000444// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000445std::unique_ptr<ValueProfData>
446ValueProfData::serializeFrom(const InstrProfRecord &Record) {
447 InstrProfRecordClosure.Record = &Record;
448
449 std::unique_ptr<ValueProfData> VPD(
Xinliang David Li0e6a36e2015-12-01 19:47:32 +0000450 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
Xinliang David Lif47cf552015-11-25 06:23:38 +0000451 return VPD;
452}
453
Xinliang David Lie8092312015-11-25 19:13:00 +0000454void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
455 InstrProfRecord::ValueMapType *VMap) {
456 Record.reserveSites(Kind, NumValueSites);
457
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;
463 }
464}
Xinliang David Lied966772015-11-25 23:31:18 +0000465
Xinliang David Lie8092312015-11-25 19:13:00 +0000466// 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.
469void ValueProfRecord::swapBytes(support::endianness Old,
470 support::endianness New) {
471 using namespace support;
472 if (Old == New)
473 return;
474
475 if (getHostEndianness() != Old) {
476 sys::swapByteOrder<uint32_t>(NumValueSites);
477 sys::swapByteOrder<uint32_t>(Kind);
478 }
479 uint32_t ND = getValueProfRecordNumValueData(this);
480 InstrProfValueData *VD = getValueProfRecordValueData(this);
481
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);
486 }
487 if (getHostEndianness() == Old) {
488 sys::swapByteOrder<uint32_t>(NumValueSites);
489 sys::swapByteOrder<uint32_t>(Kind);
490 }
491}
492
493void ValueProfData::deserializeTo(InstrProfRecord &Record,
494 InstrProfRecord::ValueMapType *VMap) {
495 if (NumValueKinds == 0)
496 return;
497
498 ValueProfRecord *VR = getFirstValueProfRecord(this);
499 for (uint32_t K = 0; K < NumValueKinds; K++) {
500 VR->deserializeTo(Record, VMap);
501 VR = getValueProfRecordNext(VR);
502 }
503}
504
505template <class T>
506static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
507 using namespace support;
508 if (Orig == little)
509 return endian::readNext<T, little, unaligned>(D);
510 else
511 return endian::readNext<T, big, unaligned>(D);
512}
513
514static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
515 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
516 ValueProfData());
517}
518
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000519instrprof_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;
525
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;
533 }
534 return instrprof_error::success;
535}
536
Xinliang David Liee415892015-11-10 00:24:45 +0000537ErrorOr<std::unique_ptr<ValueProfData>>
538ValueProfData::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;
544
Xinliang David Lib8c3ad12015-11-17 03:47:21 +0000545 const unsigned char *Header = D;
546 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
Xinliang David Liee415892015-11-10 00:24:45 +0000547 if (D + TotalSize > BufferEnd)
548 return instrprof_error::too_large;
Xinliang David Liee415892015-11-10 00:24:45 +0000549
Xinliang David Lif47cf552015-11-25 06:23:38 +0000550 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
Xinliang David Liee415892015-11-10 00:24:45 +0000551 memcpy(VPD.get(), D, TotalSize);
552 // Byte swap.
553 VPD->swapBytesToHost(Endianness);
554
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000555 instrprof_error EC = VPD->checkIntegrity();
556 if (EC != instrprof_error::success)
557 return EC;
Xinliang David Liee415892015-11-10 00:24:45 +0000558
Xinliang David Liee415892015-11-10 00:24:45 +0000559 return std::move(VPD);
560}
561
562void ValueProfData::swapBytesToHost(support::endianness Endianness) {
563 using namespace support;
564 if (Endianness == getHostEndianness())
565 return;
566
567 sys::swapByteOrder<uint32_t>(TotalSize);
568 sys::swapByteOrder<uint32_t>(NumValueKinds);
569
Xinliang David Lif47cf552015-11-25 06:23:38 +0000570 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000571 for (uint32_t K = 0; K < NumValueKinds; K++) {
572 VR->swapBytes(Endianness, getHostEndianness());
Xinliang David Liac5b8602015-11-25 04:29:24 +0000573 VR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000574 }
575}
576
577void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
578 using namespace support;
579 if (Endianness == getHostEndianness())
580 return;
581
Xinliang David Lif47cf552015-11-25 06:23:38 +0000582 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000583 for (uint32_t K = 0; K < NumValueKinds; K++) {
Xinliang David Liac5b8602015-11-25 04:29:24 +0000584 ValueProfRecord *NVR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000585 VR->swapBytes(getHostEndianness(), Endianness);
586 VR = NVR;
587 }
588 sys::swapByteOrder<uint32_t>(TotalSize);
589 sys::swapByteOrder<uint32_t>(NumValueKinds);
590}
Xinliang David Lie8092312015-11-25 19:13:00 +0000591
Xinliang David Li402477d2016-02-04 19:11:43 +0000592void annotateValueSite(Module &M, Instruction &Inst,
593 const InstrProfRecord &InstrProfR,
Rong Xu69683f12016-02-10 22:19:43 +0000594 InstrProfValueKind ValueKind, uint32_t SiteIdx,
595 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000596 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
597
598 uint64_t Sum = 0;
599 std::unique_ptr<InstrProfValueData[]> VD =
600 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
601
Rong Xubb494902016-02-12 21:36:17 +0000602 annotateValueSite(M, Inst, VD.get(), NV, Sum, ValueKind, MaxMDCount);
603}
604
605void annotateValueSite(Module &M, Instruction &Inst,
606 const InstrProfValueData VD[], uint32_t NV,
607 uint64_t Sum, InstrProfValueKind ValueKind,
608 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000609 LLVMContext &Ctx = M.getContext();
610 MDBuilder MDHelper(Ctx);
611 SmallVector<Metadata *, 3> Vals;
612 // Tag
613 Vals.push_back(MDHelper.createString("VP"));
614 // Value Kind
615 Vals.push_back(MDHelper.createConstant(
616 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
617 // Total Count
618 Vals.push_back(
619 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
620
621 // Value Profile Data
Rong Xu69683f12016-02-10 22:19:43 +0000622 uint32_t MDCount = MaxMDCount;
Xinliang David Li402477d2016-02-04 19:11:43 +0000623 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)));
628 if (--MDCount == 0)
629 break;
630 }
631 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
632}
633
634bool 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);
640 if (!MD)
641 return false;
642
643 unsigned NOps = MD->getNumOperands();
644
645 if (NOps < 5)
646 return false;
647
648 // Operand 0 is a string tag "VP":
649 MDString *Tag = cast<MDString>(MD->getOperand(0));
650 if (!Tag)
651 return false;
652
653 if (!Tag->getString().equals("VP"))
654 return false;
655
656 // Now check kind:
657 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
658 if (!KindInt)
659 return false;
660 if (KindInt->getZExtValue() != ValueKind)
661 return false;
662
663 // Get total count
664 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
665 if (!TotalCInt)
666 return false;
667 TotalC = TotalCInt->getZExtValue();
668
669 ActualNumValueData = 0;
670
671 for (unsigned I = 3; I < NOps; I += 2) {
672 if (ActualNumValueData >= MaxNumValueData)
673 break;
674 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
675 ConstantInt *Count =
676 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
677 if (!Value || !Count)
678 return false;
679 ValueData[ActualNumValueData].Value = Value->getZExtValue();
680 ValueData[ActualNumValueData].Count = Count->getZExtValue();
681 ActualNumValueData++;
682 }
683 return true;
684}
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000685} // end namespace llvm