blob: 69cda2ccee212a4526f857519f3a3f01249ef6e2 [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"
Rong Xu97b68c52016-07-21 20:50:02 +000017#include "llvm/ADT/Triple.h"
Xinliang David Li441959d2015-11-09 00:01:22 +000018#include "llvm/IR/Constants.h"
19#include "llvm/IR/Function.h"
Xinliang David Li441959d2015-11-09 00:01:22 +000020#include "llvm/IR/GlobalVariable.h"
Xinliang David Li402477d2016-02-04 19:11:43 +000021#include "llvm/IR/MDBuilder.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000022#include "llvm/IR/Module.h"
23#include "llvm/Support/Compression.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000024#include "llvm/Support/ErrorHandling.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000025#include "llvm/Support/LEB128.h"
Chris Bieneman1efe8012014-09-19 23:19:24 +000026#include "llvm/Support/ManagedStatic.h"
Xinliang David Li9eb472b2016-07-12 17:14:51 +000027#include "llvm/Support/Path.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000028
29using namespace llvm;
30
Xinliang David Li9eb472b2016-07-12 17:14:51 +000031static cl::opt<bool> StaticFuncFullModulePrefix(
Rong Xua1a9f702017-02-25 00:00:36 +000032 "static-func-full-module-prefix", cl::init(true),
Xinliang David Li9eb472b2016-07-12 17:14:51 +000033 cl::desc("Use full module build paths in the profile counter names for "
34 "static functions."));
35
Rong Xua1a9f702017-02-25 00:00:36 +000036// This option is tailored to users that have different top-level directory in
37// profile-gen and profile-use compilation. Users need to specific the number
38// of levels to strip. A value larger than the number of directories in the
39// source file will strip all the directory names and only leave the basename.
40//
Rong Xu08d08402017-02-27 17:59:01 +000041// Note current ThinLTO module importing for the indirect-calls assumes
Rong Xua1a9f702017-02-25 00:00:36 +000042// the source directory name not being stripped. A non-zero option value here
43// can potentially prevent some inter-module indirect-call-promotions.
44static cl::opt<unsigned> StaticFuncStripDirNamePrefix(
45 "static-func-strip-dirname-prefix", cl::init(0),
46 cl::desc("Strip specified level of directory name from source path in "
47 "the profile counter name for static functions."));
48
Justin Bognerf8d79192014-03-21 17:24:48 +000049namespace {
Vedant Kumar9152fd12016-05-19 03:54:45 +000050std::string getInstrProfErrString(instrprof_error Err) {
51 switch (Err) {
52 case instrprof_error::success:
53 return "Success";
54 case instrprof_error::eof:
55 return "End of File";
56 case instrprof_error::unrecognized_format:
57 return "Unrecognized instrumentation profile encoding format";
58 case instrprof_error::bad_magic:
59 return "Invalid instrumentation profile data (bad magic)";
60 case instrprof_error::bad_header:
61 return "Invalid instrumentation profile data (file header is corrupt)";
62 case instrprof_error::unsupported_version:
63 return "Unsupported instrumentation profile format version";
64 case instrprof_error::unsupported_hash_type:
65 return "Unsupported instrumentation profile hash type";
66 case instrprof_error::too_large:
67 return "Too much profile data";
68 case instrprof_error::truncated:
69 return "Truncated profile data";
70 case instrprof_error::malformed:
71 return "Malformed instrumentation profile data";
72 case instrprof_error::unknown_function:
73 return "No profile data available for function";
74 case instrprof_error::hash_mismatch:
75 return "Function control flow change detected (hash mismatch)";
76 case instrprof_error::count_mismatch:
77 return "Function basic block count change detected (counter mismatch)";
78 case instrprof_error::counter_overflow:
79 return "Counter overflow";
80 case instrprof_error::value_site_count_mismatch:
81 return "Function value site count change detected (counter mismatch)";
82 case instrprof_error::compress_failed:
83 return "Failed to compress data (zlib)";
84 case instrprof_error::uncompress_failed:
85 return "Failed to uncompress data (zlib)";
Rong Xu2c684cf2016-10-19 22:51:17 +000086 case instrprof_error::empty_raw_profile:
87 return "Empty raw profile file";
Vedant Kumar9152fd12016-05-19 03:54:45 +000088 }
89 llvm_unreachable("A value of instrprof_error has no message.");
90}
91
Peter Collingbourne4718f8b2016-05-24 20:13:46 +000092// FIXME: This class is only here to support the transition to llvm::Error. It
93// will be removed once this transition is complete. Clients should prefer to
94// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +000095class InstrProfErrorCategoryType : public std::error_category {
Reid Kleckner990504e2016-10-19 23:52:38 +000096 const char *name() const noexcept override { return "llvm.instrprof"; }
Justin Bognerf8d79192014-03-21 17:24:48 +000097 std::string message(int IE) const override {
Vedant Kumar9152fd12016-05-19 03:54:45 +000098 return getInstrProfErrString(static_cast<instrprof_error>(IE));
Justin Bognerf8d79192014-03-21 17:24:48 +000099 }
Justin Bognerf8d79192014-03-21 17:24:48 +0000100};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000101} // end anonymous namespace
Justin Bognerf8d79192014-03-21 17:24:48 +0000102
Chris Bieneman1efe8012014-09-19 23:19:24 +0000103static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
104
Rafael Espindola25188c92014-06-12 01:45:43 +0000105const std::error_category &llvm::instrprof_category() {
Chris Bieneman1efe8012014-09-19 23:19:24 +0000106 return *ErrorCategory;
Justin Bognerf8d79192014-03-21 17:24:48 +0000107}
Xinliang David Li441959d2015-11-09 00:01:22 +0000108
109namespace llvm {
110
Vedant Kumar42369db2016-05-11 19:42:19 +0000111void SoftInstrProfErrors::addError(instrprof_error IE) {
112 if (IE == instrprof_error::success)
113 return;
114
115 if (FirstError == instrprof_error::success)
116 FirstError = IE;
117
118 switch (IE) {
119 case instrprof_error::hash_mismatch:
120 ++NumHashMismatches;
121 break;
122 case instrprof_error::count_mismatch:
123 ++NumCountMismatches;
124 break;
125 case instrprof_error::counter_overflow:
126 ++NumCounterOverflows;
127 break;
128 case instrprof_error::value_site_count_mismatch:
129 ++NumValueSiteCountMismatches;
130 break;
131 default:
132 llvm_unreachable("Not a soft error");
133 }
134}
135
Vedant Kumar9152fd12016-05-19 03:54:45 +0000136std::string InstrProfError::message() const {
137 return getInstrProfErrString(Err);
138}
139
140char InstrProfError::ID = 0;
141
Xinliang David Li441959d2015-11-09 00:01:22 +0000142std::string getPGOFuncName(StringRef RawFuncName,
143 GlobalValue::LinkageTypes Linkage,
Xinliang David Lia86545b2015-12-11 20:23:22 +0000144 StringRef FileName,
145 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
Teresa Johnsonb43027d2016-03-15 02:13:19 +0000146 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000147}
148
Rong Xua1a9f702017-02-25 00:00:36 +0000149// Strip NumPrefix level of directory name from PathNameStr. If the number of
150// directory separators is less than NumPrefix, strip all the directories and
151// leave base file name only.
152static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
153 uint32_t Count = NumPrefix;
154 uint32_t Pos = 0, LastPos = 0;
155 for (auto & CI : PathNameStr) {
156 ++Pos;
157 if (llvm::sys::path::is_separator(CI)) {
158 LastPos = Pos;
159 --Count;
160 }
161 if (Count == 0)
162 break;
163 }
164 return PathNameStr.substr(LastPos);
165}
166
Rong Xub5341662016-03-30 18:37:52 +0000167// Return the PGOFuncName. This function has some special handling when called
168// in LTO optimization. The following only applies when calling in LTO passes
169// (when \c InLTO is true): LTO's internalization privatizes many global linkage
170// symbols. This happens after value profile annotation, but those internal
171// linkage functions should not have a source prefix.
Teresa Johnson8c1bc982016-08-29 22:46:56 +0000172// Additionally, for ThinLTO mode, exported internal functions are promoted
173// and renamed. We need to ensure that the original internal PGO name is
174// used when computing the GUID that is compared against the profiled GUIDs.
Rong Xub5341662016-03-30 18:37:52 +0000175// To differentiate compiler generated internal symbols from original ones,
176// PGOFuncName meta data are created and attached to the original internal
177// symbols in the value profile annotation step
178// (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
179// data, its original linkage must be non-internal.
180std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
Xinliang David Li9eb472b2016-07-12 17:14:51 +0000181 if (!InLTO) {
182 StringRef FileName = (StaticFuncFullModulePrefix
183 ? F.getParent()->getName()
184 : sys::path::filename(F.getParent()->getName()));
Rong Xua1a9f702017-02-25 00:00:36 +0000185 if (StaticFuncFullModulePrefix && StaticFuncStripDirNamePrefix != 0)
186 FileName = stripDirPrefix(FileName, StaticFuncStripDirNamePrefix);
Xinliang David Li9eb472b2016-07-12 17:14:51 +0000187 return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
188 }
Rong Xub5341662016-03-30 18:37:52 +0000189
Rong Xu8e8fe852016-04-01 16:43:30 +0000190 // In LTO mode (when InLTO is true), first check if there is a meta data.
191 if (MDNode *MD = getPGOFuncNameMetadata(F)) {
Rong Xub5341662016-03-30 18:37:52 +0000192 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
193 return S.str();
194 }
195
196 // If there is no meta data, the function must be a global before the value
197 // profile annotation pass. Its current linkage may be internal if it is
198 // internalized in LTO mode.
Rong Xu8e8fe852016-04-01 16:43:30 +0000199 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
Xinliang David Li441959d2015-11-09 00:01:22 +0000200}
201
Xinliang David Li4ec40142015-12-15 19:44:45 +0000202StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
203 if (FileName.empty())
Vedant Kumar43a85652016-03-28 15:49:08 +0000204 return PGOFuncName;
Xinliang David Li4ec40142015-12-15 19:44:45 +0000205 // Drop the file name including ':'. See also getPGOFuncName.
206 if (PGOFuncName.startswith(FileName))
207 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
208 return PGOFuncName;
209}
210
Xinliang David Lid1bab962015-12-12 17:28:03 +0000211// \p FuncName is the string used as profile lookup key for the function. A
212// symbol is created to hold the name. Return the legalized symbol name.
Vedant Kumaraa0cae62016-03-16 20:49:26 +0000213std::string getPGOFuncNameVarName(StringRef FuncName,
214 GlobalValue::LinkageTypes Linkage) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000215 std::string VarName = getInstrProfNameVarPrefix();
216 VarName += FuncName;
217
218 if (!GlobalValue::isLocalLinkage(Linkage))
219 return VarName;
220
221 // Now fix up illegal chars in local VarName that may upset the assembler.
Xinliang David Lieeaf0bc2016-06-10 06:32:26 +0000222 const char *InvalidChars = "-:<>/\"'";
Xinliang David Lid1bab962015-12-12 17:28:03 +0000223 size_t found = VarName.find_first_of(InvalidChars);
224 while (found != std::string::npos) {
225 VarName[found] = '_';
226 found = VarName.find_first_of(InvalidChars, found + 1);
227 }
228 return VarName;
229}
230
Xinliang David Li441959d2015-11-09 00:01:22 +0000231GlobalVariable *createPGOFuncNameVar(Module &M,
232 GlobalValue::LinkageTypes Linkage,
Xinliang David Li897d2922016-03-16 22:13:41 +0000233 StringRef PGOFuncName) {
Xinliang David Li441959d2015-11-09 00:01:22 +0000234
235 // We generally want to match the function's linkage, but available_externally
236 // and extern_weak both have the wrong semantics, and anything that doesn't
237 // need to link across compilation units doesn't need to be visible at all.
238 if (Linkage == GlobalValue::ExternalWeakLinkage)
239 Linkage = GlobalValue::LinkOnceAnyLinkage;
240 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
241 Linkage = GlobalValue::LinkOnceODRLinkage;
242 else if (Linkage == GlobalValue::InternalLinkage ||
243 Linkage == GlobalValue::ExternalLinkage)
244 Linkage = GlobalValue::PrivateLinkage;
245
Xinliang David Li897d2922016-03-16 22:13:41 +0000246 auto *Value =
247 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
Xinliang David Li441959d2015-11-09 00:01:22 +0000248 auto FuncNameVar =
249 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
Xinliang David Li897d2922016-03-16 22:13:41 +0000250 getPGOFuncNameVarName(PGOFuncName, Linkage));
Xinliang David Li441959d2015-11-09 00:01:22 +0000251
252 // Hide the symbol so that we correctly get a copy for each executable.
253 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
254 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
255
256 return FuncNameVar;
257}
258
Xinliang David Li897d2922016-03-16 22:13:41 +0000259GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
260 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000261}
Xinliang David Liee415892015-11-10 00:24:45 +0000262
Rong Xub5341662016-03-30 18:37:52 +0000263void InstrProfSymtab::create(Module &M, bool InLTO) {
264 for (Function &F : M) {
265 // Function may not have a name: like using asm("") to overwrite the name.
266 // Ignore in this case.
267 if (!F.hasName())
268 continue;
269 const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
270 addFuncName(PGOFuncName);
Rong Xud5a57b52016-03-31 17:39:33 +0000271 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
Rong Xub5341662016-03-30 18:37:52 +0000272 }
Xinliang David Li59411db2016-01-20 01:26:34 +0000273
274 finalizeSymtab();
275}
276
Vedant Kumar9152fd12016-05-19 03:54:45 +0000277Error collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
278 bool doCompression, std::string &Result) {
Vedant Kumar86705ba2016-03-28 21:06:42 +0000279 assert(NameStrs.size() && "No name data to emit");
280
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000281 uint8_t Header[16], *P = Header;
Xinliang David Li0c677872016-01-04 21:31:09 +0000282 std::string UncompressedNameStrings =
Vedant Kumar86705ba2016-03-28 21:06:42 +0000283 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
284
285 assert(StringRef(UncompressedNameStrings)
286 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
287 "PGO name is invalid (contains separator token)");
Xinliang David Li13ea29b2016-01-04 20:26:05 +0000288
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000289 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
290 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000291
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000292 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000293 EncLen = encodeULEB128(CompressedLen, P);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000294 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000295 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
296 unsigned HeaderLen = P - &Header[0];
297 Result.append(HeaderStr, HeaderLen);
298 Result += InputStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000299 return Error::success();
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000300 };
301
Vedant Kumar9152fd12016-05-19 03:54:45 +0000302 if (!doCompression) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000303 return WriteStringToResult(0, UncompressedNameStrings);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000304 }
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000305
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000306 SmallString<128> CompressedNameStrings;
George Rimar167ca4a2017-01-17 15:45:07 +0000307 Error E = zlib::compress(StringRef(UncompressedNameStrings),
308 CompressedNameStrings, zlib::BestSizeCompression);
309 if (E) {
310 consumeError(std::move(E));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000311 return make_error<InstrProfError>(instrprof_error::compress_failed);
George Rimar167ca4a2017-01-17 15:45:07 +0000312 }
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000313
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000314 return WriteStringToResult(CompressedNameStrings.size(),
315 CompressedNameStrings);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000316}
317
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000318StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
Xinliang David Li37c1fa02016-01-03 04:38:13 +0000319 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
320 StringRef NameStr =
321 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
322 return NameStr;
323}
324
Vedant Kumar9152fd12016-05-19 03:54:45 +0000325Error collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
326 std::string &Result, bool doCompression) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000327 std::vector<std::string> NameStrs;
328 for (auto *NameVar : NameVars) {
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000329 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000330 }
Xinliang David Li73163752016-01-26 23:13:00 +0000331 return collectPGOFuncNameStrings(
332 NameStrs, zlib::isAvailable() && doCompression, Result);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000333}
334
Vedant Kumar9152fd12016-05-19 03:54:45 +0000335Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000336 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
337 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
338 NameStrings.size());
339 while (P < EndP) {
340 uint32_t N;
341 uint64_t UncompressedSize = decodeULEB128(P, &N);
342 P += N;
343 uint64_t CompressedSize = decodeULEB128(P, &N);
344 P += N;
345 bool isCompressed = (CompressedSize != 0);
346 SmallString<128> UncompressedNameStrings;
347 StringRef NameStrings;
348 if (isCompressed) {
349 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
350 CompressedSize);
George Rimar167ca4a2017-01-17 15:45:07 +0000351 if (Error E =
352 zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
353 UncompressedSize)) {
354 consumeError(std::move(E));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000355 return make_error<InstrProfError>(instrprof_error::uncompress_failed);
George Rimar167ca4a2017-01-17 15:45:07 +0000356 }
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000357 P += CompressedSize;
358 NameStrings = StringRef(UncompressedNameStrings.data(),
359 UncompressedNameStrings.size());
360 } else {
361 NameStrings =
362 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
363 P += UncompressedSize;
364 }
365 // Now parse the name strings.
Xinliang David Li204efe22016-01-04 22:09:26 +0000366 SmallVector<StringRef, 0> Names;
Vedant Kumar86705ba2016-03-28 21:06:42 +0000367 NameStrings.split(Names, getInstrProfNameSeparator());
Xinliang David Li204efe22016-01-04 22:09:26 +0000368 for (StringRef &Name : Names)
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000369 Symtab.addFuncName(Name);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000370
371 while (P < EndP && *P == 0)
372 P++;
373 }
374 Symtab.finalizeSymtab();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000375 return Error::success();
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000376}
377
Vedant Kumar42369db2016-05-11 19:42:19 +0000378void InstrProfValueSiteRecord::merge(SoftInstrProfErrors &SIPE,
379 InstrProfValueSiteRecord &Input,
380 uint64_t Weight) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000381 this->sortByTargetValues();
382 Input.sortByTargetValues();
383 auto I = ValueData.begin();
384 auto IE = ValueData.end();
Xinliang David Li5c24da52015-12-20 05:15:45 +0000385 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
386 ++J) {
387 while (I != IE && I->Value < J->Value)
388 ++I;
389 if (I != IE && I->Value == J->Value) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000390 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000391 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000392 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000393 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000394 ++I;
395 continue;
396 }
397 ValueData.insert(I, *J);
398 }
Xinliang David Li5c24da52015-12-20 05:15:45 +0000399}
400
Vedant Kumar42369db2016-05-11 19:42:19 +0000401void InstrProfValueSiteRecord::scale(SoftInstrProfErrors &SIPE,
402 uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000403 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
404 bool Overflowed;
405 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
406 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000407 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000408 }
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000409}
410
Xinliang David Li020f22d2015-12-18 23:06:37 +0000411// Merge Value Profile data from Src record to this record for ValueKind.
412// Scale merged value counts by \p Weight.
Vedant Kumar42369db2016-05-11 19:42:19 +0000413void InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
414 InstrProfRecord &Src,
415 uint64_t Weight) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000416 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
417 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
Vedant Kumar42369db2016-05-11 19:42:19 +0000418 if (ThisNumValueSites != OtherNumValueSites) {
419 SIPE.addError(instrprof_error::value_site_count_mismatch);
420 return;
421 }
Xinliang David Li020f22d2015-12-18 23:06:37 +0000422 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
423 getValueSitesForKind(ValueKind);
424 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
425 Src.getValueSitesForKind(ValueKind);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000426 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Vedant Kumar42369db2016-05-11 19:42:19 +0000427 ThisSiteRecords[I].merge(SIPE, OtherSiteRecords[I], Weight);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000428}
429
Vedant Kumar42369db2016-05-11 19:42:19 +0000430void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000431 // If the number of counters doesn't match we either have bad data
432 // or a hash collision.
Vedant Kumar42369db2016-05-11 19:42:19 +0000433 if (Counts.size() != Other.Counts.size()) {
434 SIPE.addError(instrprof_error::count_mismatch);
435 return;
436 }
Xinliang David Li020f22d2015-12-18 23:06:37 +0000437
438 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
439 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000440 Counts[I] =
441 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000442 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000443 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000444 }
445
446 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Vedant Kumar42369db2016-05-11 19:42:19 +0000447 mergeValueProfData(Kind, Other, Weight);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000448}
Xinliang David Lia716cc52015-12-20 06:22:13 +0000449
Vedant Kumar42369db2016-05-11 19:42:19 +0000450void InstrProfRecord::scaleValueProfData(uint32_t ValueKind, uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000451 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
452 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
453 getValueSitesForKind(ValueKind);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000454 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Vedant Kumar42369db2016-05-11 19:42:19 +0000455 ThisSiteRecords[I].scale(SIPE, Weight);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000456}
457
Vedant Kumar42369db2016-05-11 19:42:19 +0000458void InstrProfRecord::scale(uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000459 for (auto &Count : this->Counts) {
460 bool Overflowed;
461 Count = SaturatingMultiply(Count, Weight, &Overflowed);
Vedant Kumar42369db2016-05-11 19:42:19 +0000462 if (Overflowed)
463 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000464 }
465 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Vedant Kumar42369db2016-05-11 19:42:19 +0000466 scaleValueProfData(Kind, Weight);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000467}
468
Xinliang David Li020f22d2015-12-18 23:06:37 +0000469// Map indirect call target name hash to name string.
470uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000471 ValueMapType *ValueMap) {
472 if (!ValueMap)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000473 return Value;
474 switch (ValueKind) {
475 case IPVK_IndirectCallTarget: {
476 auto Result =
Xinliang David Lia716cc52015-12-20 06:22:13 +0000477 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
478 [](const std::pair<uint64_t, uint64_t> &LHS,
Xinliang David Li020f22d2015-12-18 23:06:37 +0000479 uint64_t RHS) { return LHS.first < RHS; });
Xinliang David Li8dd4ca82016-04-11 17:13:08 +0000480 // Raw function pointer collected by value profiler may be from
481 // external functions that are not instrumented. They won't have
482 // mapping data to be used by the deserializer. Force the value to
483 // be 0 in this case.
Xinliang David Li28464482016-04-10 03:32:02 +0000484 if (Result != ValueMap->end() && Result->first == Value)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000485 Value = (uint64_t)Result->second;
Xinliang David Li28464482016-04-10 03:32:02 +0000486 else
487 Value = 0;
Xinliang David Li020f22d2015-12-18 23:06:37 +0000488 break;
489 }
490 }
491 return Value;
492}
493
Xinliang David Li020f22d2015-12-18 23:06:37 +0000494void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
495 InstrProfValueData *VData, uint32_t N,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000496 ValueMapType *ValueMap) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000497 for (uint32_t I = 0; I < N; I++) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000498 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000499 }
500 std::vector<InstrProfValueSiteRecord> &ValueSites =
501 getValueSitesForKind(ValueKind);
502 if (N == 0)
Vedant Kumar6b22ba62016-05-11 16:03:02 +0000503 ValueSites.emplace_back();
Xinliang David Li020f22d2015-12-18 23:06:37 +0000504 else
505 ValueSites.emplace_back(VData, VData + N);
506}
507
Xinliang David Lib75544a2015-11-28 19:07:09 +0000508#define INSTR_PROF_COMMON_API_IMPL
509#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Liee415892015-11-10 00:24:45 +0000510
Xinliang David Li020f22d2015-12-18 23:06:37 +0000511/*!
Xinliang David Lib75544a2015-11-28 19:07:09 +0000512 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
Xinliang David Lied966772015-11-25 23:31:18 +0000513 * class. These C wrappers are used as adaptors so that C++ code can be
514 * invoked as callbacks.
515 */
Xinliang David Lif47cf552015-11-25 06:23:38 +0000516uint32_t getNumValueKindsInstrProf(const void *Record) {
517 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
518}
519
520uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
521 return reinterpret_cast<const InstrProfRecord *>(Record)
522 ->getNumValueSites(VKind);
523}
524
525uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
526 return reinterpret_cast<const InstrProfRecord *>(Record)
527 ->getNumValueData(VKind);
528}
529
530uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
531 uint32_t S) {
532 return reinterpret_cast<const InstrProfRecord *>(R)
533 ->getNumValueDataForSite(VK, S);
534}
535
536void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
Xinliang David Li1e4c8092016-02-04 05:29:51 +0000537 uint32_t K, uint32_t S) {
538 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
Xinliang David Lie8092312015-11-25 19:13:00 +0000539}
540
Xinliang David Lif47cf552015-11-25 06:23:38 +0000541ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
Xinliang David Li38b9a322015-12-15 21:57:08 +0000542 ValueProfData *VD =
543 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
544 memset(VD, 0, TotalSizeInBytes);
545 return VD;
Xinliang David Lif47cf552015-11-25 06:23:38 +0000546}
547
548static ValueProfRecordClosure InstrProfRecordClosure = {
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000549 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000550 getNumValueKindsInstrProf,
551 getNumValueSitesInstrProf,
552 getNumValueDataInstrProf,
553 getNumValueDataForSiteInstrProf,
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000554 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000555 getValueForSiteInstrProf,
Xinliang David Li38b9a322015-12-15 21:57:08 +0000556 allocValueProfDataInstrProf};
Xinliang David Lif47cf552015-11-25 06:23:38 +0000557
Xinliang David Lie8092312015-11-25 19:13:00 +0000558// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000559uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
560 InstrProfRecordClosure.Record = &Record;
561 return getValueProfDataSize(&InstrProfRecordClosure);
562}
563
Xinliang David Lie8092312015-11-25 19:13:00 +0000564// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000565std::unique_ptr<ValueProfData>
566ValueProfData::serializeFrom(const InstrProfRecord &Record) {
567 InstrProfRecordClosure.Record = &Record;
568
569 std::unique_ptr<ValueProfData> VPD(
Xinliang David Li0e6a36e2015-12-01 19:47:32 +0000570 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
Xinliang David Lif47cf552015-11-25 06:23:38 +0000571 return VPD;
572}
573
Xinliang David Lie8092312015-11-25 19:13:00 +0000574void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
575 InstrProfRecord::ValueMapType *VMap) {
576 Record.reserveSites(Kind, NumValueSites);
577
578 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
579 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
580 uint8_t ValueDataCount = this->SiteCountArray[VSite];
581 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
582 ValueData += ValueDataCount;
583 }
584}
Xinliang David Lied966772015-11-25 23:31:18 +0000585
Xinliang David Lie8092312015-11-25 19:13:00 +0000586// For writing/serializing, Old is the host endianness, and New is
587// byte order intended on disk. For Reading/deserialization, Old
588// is the on-disk source endianness, and New is the host endianness.
589void ValueProfRecord::swapBytes(support::endianness Old,
590 support::endianness New) {
591 using namespace support;
592 if (Old == New)
593 return;
594
595 if (getHostEndianness() != Old) {
596 sys::swapByteOrder<uint32_t>(NumValueSites);
597 sys::swapByteOrder<uint32_t>(Kind);
598 }
599 uint32_t ND = getValueProfRecordNumValueData(this);
600 InstrProfValueData *VD = getValueProfRecordValueData(this);
601
602 // No need to swap byte array: SiteCountArrray.
603 for (uint32_t I = 0; I < ND; I++) {
604 sys::swapByteOrder<uint64_t>(VD[I].Value);
605 sys::swapByteOrder<uint64_t>(VD[I].Count);
606 }
607 if (getHostEndianness() == Old) {
608 sys::swapByteOrder<uint32_t>(NumValueSites);
609 sys::swapByteOrder<uint32_t>(Kind);
610 }
611}
612
613void ValueProfData::deserializeTo(InstrProfRecord &Record,
614 InstrProfRecord::ValueMapType *VMap) {
615 if (NumValueKinds == 0)
616 return;
617
618 ValueProfRecord *VR = getFirstValueProfRecord(this);
619 for (uint32_t K = 0; K < NumValueKinds; K++) {
620 VR->deserializeTo(Record, VMap);
621 VR = getValueProfRecordNext(VR);
622 }
623}
624
625template <class T>
626static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
627 using namespace support;
628 if (Orig == little)
629 return endian::readNext<T, little, unaligned>(D);
630 else
631 return endian::readNext<T, big, unaligned>(D);
632}
633
634static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
635 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
636 ValueProfData());
637}
638
Vedant Kumar9152fd12016-05-19 03:54:45 +0000639Error ValueProfData::checkIntegrity() {
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000640 if (NumValueKinds > IPVK_Last + 1)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000641 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000642 // Total size needs to be mulltiple of quadword size.
643 if (TotalSize % sizeof(uint64_t))
Vedant Kumar9152fd12016-05-19 03:54:45 +0000644 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000645
646 ValueProfRecord *VR = getFirstValueProfRecord(this);
647 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
648 if (VR->Kind > IPVK_Last)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000649 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000650 VR = getValueProfRecordNext(VR);
651 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000652 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000653 }
Vedant Kumar9152fd12016-05-19 03:54:45 +0000654 return Error::success();
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000655}
656
Vedant Kumar9152fd12016-05-19 03:54:45 +0000657Expected<std::unique_ptr<ValueProfData>>
Xinliang David Liee415892015-11-10 00:24:45 +0000658ValueProfData::getValueProfData(const unsigned char *D,
659 const unsigned char *const BufferEnd,
660 support::endianness Endianness) {
661 using namespace support;
662 if (D + sizeof(ValueProfData) > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000663 return make_error<InstrProfError>(instrprof_error::truncated);
Xinliang David Liee415892015-11-10 00:24:45 +0000664
Xinliang David Lib8c3ad12015-11-17 03:47:21 +0000665 const unsigned char *Header = D;
666 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
Xinliang David Liee415892015-11-10 00:24:45 +0000667 if (D + TotalSize > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000668 return make_error<InstrProfError>(instrprof_error::too_large);
Xinliang David Liee415892015-11-10 00:24:45 +0000669
Xinliang David Lif47cf552015-11-25 06:23:38 +0000670 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
Xinliang David Liee415892015-11-10 00:24:45 +0000671 memcpy(VPD.get(), D, TotalSize);
672 // Byte swap.
673 VPD->swapBytesToHost(Endianness);
674
Vedant Kumar9152fd12016-05-19 03:54:45 +0000675 Error E = VPD->checkIntegrity();
676 if (E)
677 return std::move(E);
Xinliang David Liee415892015-11-10 00:24:45 +0000678
Xinliang David Liee415892015-11-10 00:24:45 +0000679 return std::move(VPD);
680}
681
682void ValueProfData::swapBytesToHost(support::endianness Endianness) {
683 using namespace support;
684 if (Endianness == getHostEndianness())
685 return;
686
687 sys::swapByteOrder<uint32_t>(TotalSize);
688 sys::swapByteOrder<uint32_t>(NumValueKinds);
689
Xinliang David Lif47cf552015-11-25 06:23:38 +0000690 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000691 for (uint32_t K = 0; K < NumValueKinds; K++) {
692 VR->swapBytes(Endianness, getHostEndianness());
Xinliang David Liac5b8602015-11-25 04:29:24 +0000693 VR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000694 }
695}
696
697void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
698 using namespace support;
699 if (Endianness == getHostEndianness())
700 return;
701
Xinliang David Lif47cf552015-11-25 06:23:38 +0000702 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000703 for (uint32_t K = 0; K < NumValueKinds; K++) {
Xinliang David Liac5b8602015-11-25 04:29:24 +0000704 ValueProfRecord *NVR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000705 VR->swapBytes(getHostEndianness(), Endianness);
706 VR = NVR;
707 }
708 sys::swapByteOrder<uint32_t>(TotalSize);
709 sys::swapByteOrder<uint32_t>(NumValueKinds);
710}
Xinliang David Lie8092312015-11-25 19:13:00 +0000711
Xinliang David Li402477d2016-02-04 19:11:43 +0000712void annotateValueSite(Module &M, Instruction &Inst,
713 const InstrProfRecord &InstrProfR,
Rong Xu69683f12016-02-10 22:19:43 +0000714 InstrProfValueKind ValueKind, uint32_t SiteIdx,
715 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000716 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
Betul Buyukkurt4f1e8c92016-04-14 16:25:45 +0000717 if (!NV)
718 return;
Xinliang David Li402477d2016-02-04 19:11:43 +0000719
720 uint64_t Sum = 0;
721 std::unique_ptr<InstrProfValueData[]> VD =
722 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
723
Rong Xu311ada12016-03-30 16:56:31 +0000724 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
725 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
Rong Xubb494902016-02-12 21:36:17 +0000726}
727
728void annotateValueSite(Module &M, Instruction &Inst,
Rong Xu311ada12016-03-30 16:56:31 +0000729 ArrayRef<InstrProfValueData> VDs,
Rong Xubb494902016-02-12 21:36:17 +0000730 uint64_t Sum, InstrProfValueKind ValueKind,
731 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000732 LLVMContext &Ctx = M.getContext();
733 MDBuilder MDHelper(Ctx);
734 SmallVector<Metadata *, 3> Vals;
735 // Tag
736 Vals.push_back(MDHelper.createString("VP"));
737 // Value Kind
738 Vals.push_back(MDHelper.createConstant(
739 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
740 // Total Count
741 Vals.push_back(
742 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
743
744 // Value Profile Data
Rong Xu69683f12016-02-10 22:19:43 +0000745 uint32_t MDCount = MaxMDCount;
Rong Xu311ada12016-03-30 16:56:31 +0000746 for (auto &VD : VDs) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000747 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000748 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000749 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000750 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000751 if (--MDCount == 0)
752 break;
753 }
754 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
755}
756
757bool getValueProfDataFromInst(const Instruction &Inst,
758 InstrProfValueKind ValueKind,
759 uint32_t MaxNumValueData,
760 InstrProfValueData ValueData[],
761 uint32_t &ActualNumValueData, uint64_t &TotalC) {
762 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
763 if (!MD)
764 return false;
765
766 unsigned NOps = MD->getNumOperands();
767
768 if (NOps < 5)
769 return false;
770
771 // Operand 0 is a string tag "VP":
772 MDString *Tag = cast<MDString>(MD->getOperand(0));
773 if (!Tag)
774 return false;
775
776 if (!Tag->getString().equals("VP"))
777 return false;
778
779 // Now check kind:
780 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
781 if (!KindInt)
782 return false;
783 if (KindInt->getZExtValue() != ValueKind)
784 return false;
785
786 // Get total count
787 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
788 if (!TotalCInt)
789 return false;
790 TotalC = TotalCInt->getZExtValue();
791
792 ActualNumValueData = 0;
793
794 for (unsigned I = 3; I < NOps; I += 2) {
795 if (ActualNumValueData >= MaxNumValueData)
796 break;
797 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
798 ConstantInt *Count =
799 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
800 if (!Value || !Count)
801 return false;
802 ValueData[ActualNumValueData].Value = Value->getZExtValue();
803 ValueData[ActualNumValueData].Count = Count->getZExtValue();
804 ActualNumValueData++;
805 }
806 return true;
807}
Rong Xu8e8fe852016-04-01 16:43:30 +0000808
Rong Xu92c2eae2016-04-01 20:15:04 +0000809MDNode *getPGOFuncNameMetadata(const Function &F) {
810 return F.getMetadata(getPGOFuncNameMetadataName());
811}
812
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000813void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
Rong Xuf8f051c2016-04-22 21:00:17 +0000814 // Only for internal linkage functions.
815 if (PGOFuncName == F.getName())
816 return;
817 // Don't create duplicated meta-data.
818 if (getPGOFuncNameMetadata(F))
Rong Xu8e8fe852016-04-01 16:43:30 +0000819 return;
Rong Xu8e8fe852016-04-01 16:43:30 +0000820 LLVMContext &C = F.getContext();
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000821 MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
Rong Xu8e8fe852016-04-01 16:43:30 +0000822 F.setMetadata(getPGOFuncNameMetadataName(), N);
823}
824
Rong Xu97b68c52016-07-21 20:50:02 +0000825bool needsComdatForCounter(const Function &F, const Module &M) {
826 if (F.hasComdat())
827 return true;
828
829 Triple TT(M.getTargetTriple());
Dan Gohman1209c7a2017-01-17 20:34:09 +0000830 if (!TT.isOSBinFormatELF() && !TT.isOSBinFormatWasm())
Rong Xu97b68c52016-07-21 20:50:02 +0000831 return false;
832
833 // See createPGOFuncNameVar for more details. To avoid link errors, profile
834 // counters for function with available_externally linkage needs to be changed
835 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
836 // created. Without using comdat, duplicate entries won't be removed by the
837 // linker leading to increased data segement size and raw profile size. Even
838 // worse, since the referenced counter from profile per-function data object
839 // will be resolved to the common strong definition, the profile counts for
840 // available_externally functions will end up being duplicated in raw profile
841 // data. This can result in distorted profile as the counts of those dups
842 // will be accumulated by the profile merger.
843 GlobalValue::LinkageTypes Linkage = F.getLinkage();
844 if (Linkage != GlobalValue::ExternalWeakLinkage &&
845 Linkage != GlobalValue::AvailableExternallyLinkage)
846 return false;
847
848 return true;
849}
Rong Xu20f5df12017-01-11 20:19:41 +0000850
851// Check if INSTR_PROF_RAW_VERSION_VAR is defined.
852bool isIRPGOFlagSet(const Module *M) {
853 auto IRInstrVar =
854 M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
855 if (!IRInstrVar || IRInstrVar->isDeclaration() ||
856 IRInstrVar->hasLocalLinkage())
857 return false;
858
859 // Check if the flag is set.
860 if (!IRInstrVar->hasInitializer())
861 return false;
862
863 const Constant *InitVal = IRInstrVar->getInitializer();
864 if (!InitVal)
865 return false;
866
867 return (dyn_cast<ConstantInt>(InitVal)->getZExtValue() &
868 VARIANT_MASK_IR_PROF) != 0;
869}
870
871// Check if we can safely rename this Comdat function.
872bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
873 if (F.getName().empty())
874 return false;
875 if (!needsComdatForCounter(F, *(F.getParent())))
876 return false;
877 // Unsafe to rename the address-taken function (which can be used in
878 // function comparison).
879 if (CheckAddressTaken && F.hasAddressTaken())
880 return false;
881 // Only safe to do if this function may be discarded if it is not used
882 // in the compilation unit.
883 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
884 return false;
885
886 // For AvailableExternallyLinkage functions.
887 if (!F.hasComdat()) {
888 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
889 return true;
890 }
891 return true;
892}
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000893} // end namespace llvm