blob: 8514b44777e40f463a28dca2c9b9b403957e338b [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())
Vedant Kumar43a85652016-03-28 15:49:08 +000093 return PGOFuncName;
Xinliang David Li4ec40142015-12-15 19:44:45 +000094 // 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.
Vedant Kumaraa0cae62016-03-16 20:49:26 +0000102std::string getPGOFuncNameVarName(StringRef FuncName,
103 GlobalValue::LinkageTypes Linkage) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000104 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,
Xinliang David Li897d2922016-03-16 22:13:41 +0000122 StringRef PGOFuncName) {
Xinliang David Li441959d2015-11-09 00:01:22 +0000123
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
Xinliang David Li897d2922016-03-16 22:13:41 +0000135 auto *Value =
136 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
Xinliang David Li441959d2015-11-09 00:01:22 +0000137 auto FuncNameVar =
138 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
Xinliang David Li897d2922016-03-16 22:13:41 +0000139 getPGOFuncNameVarName(PGOFuncName, Linkage));
Xinliang David Li441959d2015-11-09 00:01:22 +0000140
141 // Hide the symbol so that we correctly get a copy for each executable.
142 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
143 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
144
145 return FuncNameVar;
146}
147
Xinliang David Li897d2922016-03-16 22:13:41 +0000148GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
149 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000150}
Xinliang David Liee415892015-11-10 00:24:45 +0000151
Xinliang David Li59411db2016-01-20 01:26:34 +0000152void InstrProfSymtab::create(const Module &M) {
153 for (const Function &F : M)
154 addFuncName(getPGOFuncName(F));
155
156 finalizeSymtab();
157}
158
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000159int collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
160 bool doCompression, std::string &Result) {
Vedant Kumar86705ba2016-03-28 21:06:42 +0000161 assert(NameStrs.size() && "No name data to emit");
162
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000163 uint8_t Header[16], *P = Header;
Xinliang David Li0c677872016-01-04 21:31:09 +0000164 std::string UncompressedNameStrings =
Vedant Kumar86705ba2016-03-28 21:06:42 +0000165 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
166
167 assert(StringRef(UncompressedNameStrings)
168 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
169 "PGO name is invalid (contains separator token)");
Xinliang David Li13ea29b2016-01-04 20:26:05 +0000170
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000171 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
172 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000173
174 auto WriteStringToResult = [&](size_t CompressedLen,
175 const std::string &InputStr) {
176 EncLen = encodeULEB128(CompressedLen, P);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000177 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000178 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
179 unsigned HeaderLen = P - &Header[0];
180 Result.append(HeaderStr, HeaderLen);
181 Result += InputStr;
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000182 return 0;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000183 };
184
185 if (!doCompression)
186 return WriteStringToResult(0, UncompressedNameStrings);
187
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000188 SmallVector<char, 128> CompressedNameStrings;
189 zlib::Status Success =
190 zlib::compress(StringRef(UncompressedNameStrings), CompressedNameStrings,
191 zlib::BestSizeCompression);
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000192
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000193 if (Success != zlib::StatusOK)
194 return 1;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000195
196 return WriteStringToResult(
197 CompressedNameStrings.size(),
198 std::string(CompressedNameStrings.data(), CompressedNameStrings.size()));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000199}
200
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000201StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
Xinliang David Li37c1fa02016-01-03 04:38:13 +0000202 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
203 StringRef NameStr =
204 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
205 return NameStr;
206}
207
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000208int collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
Xinliang David Li73163752016-01-26 23:13:00 +0000209 std::string &Result, bool doCompression) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000210 std::vector<std::string> NameStrs;
211 for (auto *NameVar : NameVars) {
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000212 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000213 }
Xinliang David Li73163752016-01-26 23:13:00 +0000214 return collectPGOFuncNameStrings(
215 NameStrs, zlib::isAvailable() && doCompression, Result);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000216}
217
218int readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
219 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
220 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
221 NameStrings.size());
222 while (P < EndP) {
223 uint32_t N;
224 uint64_t UncompressedSize = decodeULEB128(P, &N);
225 P += N;
226 uint64_t CompressedSize = decodeULEB128(P, &N);
227 P += N;
228 bool isCompressed = (CompressedSize != 0);
229 SmallString<128> UncompressedNameStrings;
230 StringRef NameStrings;
231 if (isCompressed) {
232 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
233 CompressedSize);
234 if (zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
235 UncompressedSize) != zlib::StatusOK)
236 return 1;
237 P += CompressedSize;
238 NameStrings = StringRef(UncompressedNameStrings.data(),
239 UncompressedNameStrings.size());
240 } else {
241 NameStrings =
242 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
243 P += UncompressedSize;
244 }
245 // Now parse the name strings.
Xinliang David Li204efe22016-01-04 22:09:26 +0000246 SmallVector<StringRef, 0> Names;
Vedant Kumar86705ba2016-03-28 21:06:42 +0000247 NameStrings.split(Names, getInstrProfNameSeparator());
Xinliang David Li204efe22016-01-04 22:09:26 +0000248 for (StringRef &Name : Names)
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000249 Symtab.addFuncName(Name);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000250
251 while (P < EndP && *P == 0)
252 P++;
253 }
254 Symtab.finalizeSymtab();
255 return 0;
256}
257
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000258instrprof_error InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
259 uint64_t Weight) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000260 this->sortByTargetValues();
261 Input.sortByTargetValues();
262 auto I = ValueData.begin();
263 auto IE = ValueData.end();
264 instrprof_error Result = instrprof_error::success;
265 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
266 ++J) {
267 while (I != IE && I->Value < J->Value)
268 ++I;
269 if (I != IE && I->Value == J->Value) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000270 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000271 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000272 if (Overflowed)
273 Result = instrprof_error::counter_overflow;
274 ++I;
275 continue;
276 }
277 ValueData.insert(I, *J);
278 }
279 return Result;
280}
281
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000282instrprof_error InstrProfValueSiteRecord::scale(uint64_t Weight) {
283 instrprof_error Result = instrprof_error::success;
284 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
285 bool Overflowed;
286 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
287 if (Overflowed)
288 Result = instrprof_error::counter_overflow;
289 }
290 return Result;
291}
292
Xinliang David Li020f22d2015-12-18 23:06:37 +0000293// Merge Value Profile data from Src record to this record for ValueKind.
294// Scale merged value counts by \p Weight.
295instrprof_error InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
296 InstrProfRecord &Src,
297 uint64_t Weight) {
298 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
299 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
300 if (ThisNumValueSites != OtherNumValueSites)
301 return instrprof_error::value_site_count_mismatch;
302 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
303 getValueSitesForKind(ValueKind);
304 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
305 Src.getValueSitesForKind(ValueKind);
306 instrprof_error Result = instrprof_error::success;
307 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000308 MergeResult(Result, ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight));
Xinliang David Li020f22d2015-12-18 23:06:37 +0000309 return Result;
310}
311
312instrprof_error InstrProfRecord::merge(InstrProfRecord &Other,
313 uint64_t Weight) {
314 // If the number of counters doesn't match we either have bad data
315 // or a hash collision.
316 if (Counts.size() != Other.Counts.size())
317 return instrprof_error::count_mismatch;
318
319 instrprof_error Result = instrprof_error::success;
320
321 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
322 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000323 Counts[I] =
324 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000325 if (Overflowed)
326 Result = instrprof_error::counter_overflow;
327 }
328
329 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
330 MergeResult(Result, mergeValueProfData(Kind, Other, Weight));
331
332 return Result;
333}
Xinliang David Lia716cc52015-12-20 06:22:13 +0000334
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000335instrprof_error InstrProfRecord::scaleValueProfData(uint32_t ValueKind,
336 uint64_t Weight) {
337 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
338 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
339 getValueSitesForKind(ValueKind);
340 instrprof_error Result = instrprof_error::success;
341 for (uint32_t I = 0; I < ThisNumValueSites; I++)
342 MergeResult(Result, ThisSiteRecords[I].scale(Weight));
343 return Result;
344}
345
346instrprof_error InstrProfRecord::scale(uint64_t Weight) {
347 instrprof_error Result = instrprof_error::success;
348 for (auto &Count : this->Counts) {
349 bool Overflowed;
350 Count = SaturatingMultiply(Count, Weight, &Overflowed);
351 if (Overflowed && Result == instrprof_error::success) {
352 Result = instrprof_error::counter_overflow;
353 }
354 }
355 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
356 MergeResult(Result, scaleValueProfData(Kind, Weight));
357
358 return Result;
359}
360
Xinliang David Li020f22d2015-12-18 23:06:37 +0000361// Map indirect call target name hash to name string.
362uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000363 ValueMapType *ValueMap) {
364 if (!ValueMap)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000365 return Value;
366 switch (ValueKind) {
367 case IPVK_IndirectCallTarget: {
368 auto Result =
Xinliang David Lia716cc52015-12-20 06:22:13 +0000369 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
370 [](const std::pair<uint64_t, uint64_t> &LHS,
Xinliang David Li020f22d2015-12-18 23:06:37 +0000371 uint64_t RHS) { return LHS.first < RHS; });
Xinliang David Lia716cc52015-12-20 06:22:13 +0000372 if (Result != ValueMap->end())
Xinliang David Li020f22d2015-12-18 23:06:37 +0000373 Value = (uint64_t)Result->second;
374 break;
375 }
376 }
377 return Value;
378}
379
Xinliang David Li020f22d2015-12-18 23:06:37 +0000380void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
381 InstrProfValueData *VData, uint32_t N,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000382 ValueMapType *ValueMap) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000383 for (uint32_t I = 0; I < N; I++) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000384 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000385 }
386 std::vector<InstrProfValueSiteRecord> &ValueSites =
387 getValueSitesForKind(ValueKind);
388 if (N == 0)
389 ValueSites.push_back(InstrProfValueSiteRecord());
390 else
391 ValueSites.emplace_back(VData, VData + N);
392}
393
Xinliang David Lib75544a2015-11-28 19:07:09 +0000394#define INSTR_PROF_COMMON_API_IMPL
395#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Liee415892015-11-10 00:24:45 +0000396
Xinliang David Li020f22d2015-12-18 23:06:37 +0000397/*!
Xinliang David Lib75544a2015-11-28 19:07:09 +0000398 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
Xinliang David Lied966772015-11-25 23:31:18 +0000399 * class. These C wrappers are used as adaptors so that C++ code can be
400 * invoked as callbacks.
401 */
Xinliang David Lif47cf552015-11-25 06:23:38 +0000402uint32_t getNumValueKindsInstrProf(const void *Record) {
403 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
404}
405
406uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
407 return reinterpret_cast<const InstrProfRecord *>(Record)
408 ->getNumValueSites(VKind);
409}
410
411uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
412 return reinterpret_cast<const InstrProfRecord *>(Record)
413 ->getNumValueData(VKind);
414}
415
416uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
417 uint32_t S) {
418 return reinterpret_cast<const InstrProfRecord *>(R)
419 ->getNumValueDataForSite(VK, S);
420}
421
422void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
Xinliang David Li1e4c8092016-02-04 05:29:51 +0000423 uint32_t K, uint32_t S) {
424 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
425 return;
Xinliang David Lie8092312015-11-25 19:13:00 +0000426}
427
Xinliang David Lif47cf552015-11-25 06:23:38 +0000428ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
Xinliang David Li38b9a322015-12-15 21:57:08 +0000429 ValueProfData *VD =
430 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
431 memset(VD, 0, TotalSizeInBytes);
432 return VD;
Xinliang David Lif47cf552015-11-25 06:23:38 +0000433}
434
435static ValueProfRecordClosure InstrProfRecordClosure = {
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000436 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000437 getNumValueKindsInstrProf,
438 getNumValueSitesInstrProf,
439 getNumValueDataInstrProf,
440 getNumValueDataForSiteInstrProf,
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000441 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000442 getValueForSiteInstrProf,
Xinliang David Li38b9a322015-12-15 21:57:08 +0000443 allocValueProfDataInstrProf};
Xinliang David Lif47cf552015-11-25 06:23:38 +0000444
Xinliang David Lie8092312015-11-25 19:13:00 +0000445// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000446uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
447 InstrProfRecordClosure.Record = &Record;
448 return getValueProfDataSize(&InstrProfRecordClosure);
449}
450
Xinliang David Lie8092312015-11-25 19:13:00 +0000451// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000452std::unique_ptr<ValueProfData>
453ValueProfData::serializeFrom(const InstrProfRecord &Record) {
454 InstrProfRecordClosure.Record = &Record;
455
456 std::unique_ptr<ValueProfData> VPD(
Xinliang David Li0e6a36e2015-12-01 19:47:32 +0000457 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
Xinliang David Lif47cf552015-11-25 06:23:38 +0000458 return VPD;
459}
460
Xinliang David Lie8092312015-11-25 19:13:00 +0000461void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
462 InstrProfRecord::ValueMapType *VMap) {
463 Record.reserveSites(Kind, NumValueSites);
464
465 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
466 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
467 uint8_t ValueDataCount = this->SiteCountArray[VSite];
468 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
469 ValueData += ValueDataCount;
470 }
471}
Xinliang David Lied966772015-11-25 23:31:18 +0000472
Xinliang David Lie8092312015-11-25 19:13:00 +0000473// For writing/serializing, Old is the host endianness, and New is
474// byte order intended on disk. For Reading/deserialization, Old
475// is the on-disk source endianness, and New is the host endianness.
476void ValueProfRecord::swapBytes(support::endianness Old,
477 support::endianness New) {
478 using namespace support;
479 if (Old == New)
480 return;
481
482 if (getHostEndianness() != Old) {
483 sys::swapByteOrder<uint32_t>(NumValueSites);
484 sys::swapByteOrder<uint32_t>(Kind);
485 }
486 uint32_t ND = getValueProfRecordNumValueData(this);
487 InstrProfValueData *VD = getValueProfRecordValueData(this);
488
489 // No need to swap byte array: SiteCountArrray.
490 for (uint32_t I = 0; I < ND; I++) {
491 sys::swapByteOrder<uint64_t>(VD[I].Value);
492 sys::swapByteOrder<uint64_t>(VD[I].Count);
493 }
494 if (getHostEndianness() == Old) {
495 sys::swapByteOrder<uint32_t>(NumValueSites);
496 sys::swapByteOrder<uint32_t>(Kind);
497 }
498}
499
500void ValueProfData::deserializeTo(InstrProfRecord &Record,
501 InstrProfRecord::ValueMapType *VMap) {
502 if (NumValueKinds == 0)
503 return;
504
505 ValueProfRecord *VR = getFirstValueProfRecord(this);
506 for (uint32_t K = 0; K < NumValueKinds; K++) {
507 VR->deserializeTo(Record, VMap);
508 VR = getValueProfRecordNext(VR);
509 }
510}
511
512template <class T>
513static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
514 using namespace support;
515 if (Orig == little)
516 return endian::readNext<T, little, unaligned>(D);
517 else
518 return endian::readNext<T, big, unaligned>(D);
519}
520
521static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
522 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
523 ValueProfData());
524}
525
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000526instrprof_error ValueProfData::checkIntegrity() {
527 if (NumValueKinds > IPVK_Last + 1)
528 return instrprof_error::malformed;
529 // Total size needs to be mulltiple of quadword size.
530 if (TotalSize % sizeof(uint64_t))
531 return instrprof_error::malformed;
532
533 ValueProfRecord *VR = getFirstValueProfRecord(this);
534 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
535 if (VR->Kind > IPVK_Last)
536 return instrprof_error::malformed;
537 VR = getValueProfRecordNext(VR);
538 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
539 return instrprof_error::malformed;
540 }
541 return instrprof_error::success;
542}
543
Xinliang David Liee415892015-11-10 00:24:45 +0000544ErrorOr<std::unique_ptr<ValueProfData>>
545ValueProfData::getValueProfData(const unsigned char *D,
546 const unsigned char *const BufferEnd,
547 support::endianness Endianness) {
548 using namespace support;
549 if (D + sizeof(ValueProfData) > BufferEnd)
550 return instrprof_error::truncated;
551
Xinliang David Lib8c3ad12015-11-17 03:47:21 +0000552 const unsigned char *Header = D;
553 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
Xinliang David Liee415892015-11-10 00:24:45 +0000554 if (D + TotalSize > BufferEnd)
555 return instrprof_error::too_large;
Xinliang David Liee415892015-11-10 00:24:45 +0000556
Xinliang David Lif47cf552015-11-25 06:23:38 +0000557 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
Xinliang David Liee415892015-11-10 00:24:45 +0000558 memcpy(VPD.get(), D, TotalSize);
559 // Byte swap.
560 VPD->swapBytesToHost(Endianness);
561
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000562 instrprof_error EC = VPD->checkIntegrity();
563 if (EC != instrprof_error::success)
564 return EC;
Xinliang David Liee415892015-11-10 00:24:45 +0000565
Xinliang David Liee415892015-11-10 00:24:45 +0000566 return std::move(VPD);
567}
568
569void ValueProfData::swapBytesToHost(support::endianness Endianness) {
570 using namespace support;
571 if (Endianness == getHostEndianness())
572 return;
573
574 sys::swapByteOrder<uint32_t>(TotalSize);
575 sys::swapByteOrder<uint32_t>(NumValueKinds);
576
Xinliang David Lif47cf552015-11-25 06:23:38 +0000577 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000578 for (uint32_t K = 0; K < NumValueKinds; K++) {
579 VR->swapBytes(Endianness, getHostEndianness());
Xinliang David Liac5b8602015-11-25 04:29:24 +0000580 VR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000581 }
582}
583
584void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
585 using namespace support;
586 if (Endianness == getHostEndianness())
587 return;
588
Xinliang David Lif47cf552015-11-25 06:23:38 +0000589 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000590 for (uint32_t K = 0; K < NumValueKinds; K++) {
Xinliang David Liac5b8602015-11-25 04:29:24 +0000591 ValueProfRecord *NVR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000592 VR->swapBytes(getHostEndianness(), Endianness);
593 VR = NVR;
594 }
595 sys::swapByteOrder<uint32_t>(TotalSize);
596 sys::swapByteOrder<uint32_t>(NumValueKinds);
597}
Xinliang David Lie8092312015-11-25 19:13:00 +0000598
Xinliang David Li402477d2016-02-04 19:11:43 +0000599void annotateValueSite(Module &M, Instruction &Inst,
600 const InstrProfRecord &InstrProfR,
Rong Xu69683f12016-02-10 22:19:43 +0000601 InstrProfValueKind ValueKind, uint32_t SiteIdx,
602 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000603 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
604
605 uint64_t Sum = 0;
606 std::unique_ptr<InstrProfValueData[]> VD =
607 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
608
Rong Xu311ada12016-03-30 16:56:31 +0000609 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
610 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
Rong Xubb494902016-02-12 21:36:17 +0000611}
612
613void annotateValueSite(Module &M, Instruction &Inst,
Rong Xu311ada12016-03-30 16:56:31 +0000614 ArrayRef<InstrProfValueData> VDs,
Rong Xubb494902016-02-12 21:36:17 +0000615 uint64_t Sum, InstrProfValueKind ValueKind,
616 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000617 LLVMContext &Ctx = M.getContext();
618 MDBuilder MDHelper(Ctx);
619 SmallVector<Metadata *, 3> Vals;
620 // Tag
621 Vals.push_back(MDHelper.createString("VP"));
622 // Value Kind
623 Vals.push_back(MDHelper.createConstant(
624 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
625 // Total Count
626 Vals.push_back(
627 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
628
629 // Value Profile Data
Rong Xu69683f12016-02-10 22:19:43 +0000630 uint32_t MDCount = MaxMDCount;
Rong Xu311ada12016-03-30 16:56:31 +0000631 for (auto &VD : VDs) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000632 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000633 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000634 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000635 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000636 if (--MDCount == 0)
637 break;
638 }
639 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
640}
641
642bool getValueProfDataFromInst(const Instruction &Inst,
643 InstrProfValueKind ValueKind,
644 uint32_t MaxNumValueData,
645 InstrProfValueData ValueData[],
646 uint32_t &ActualNumValueData, uint64_t &TotalC) {
647 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
648 if (!MD)
649 return false;
650
651 unsigned NOps = MD->getNumOperands();
652
653 if (NOps < 5)
654 return false;
655
656 // Operand 0 is a string tag "VP":
657 MDString *Tag = cast<MDString>(MD->getOperand(0));
658 if (!Tag)
659 return false;
660
661 if (!Tag->getString().equals("VP"))
662 return false;
663
664 // Now check kind:
665 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
666 if (!KindInt)
667 return false;
668 if (KindInt->getZExtValue() != ValueKind)
669 return false;
670
671 // Get total count
672 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
673 if (!TotalCInt)
674 return false;
675 TotalC = TotalCInt->getZExtValue();
676
677 ActualNumValueData = 0;
678
679 for (unsigned I = 3; I < NOps; I += 2) {
680 if (ActualNumValueData >= MaxNumValueData)
681 break;
682 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
683 ConstantInt *Count =
684 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
685 if (!Value || !Count)
686 return false;
687 ValueData[ActualNumValueData].Value = Value->getZExtValue();
688 ValueData[ActualNumValueData].Count = Count->getZExtValue();
689 ActualNumValueData++;
690 }
691 return true;
692}
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000693} // end namespace llvm