blob: c9b82c303e33807b7f95e91de3921c172aa2590e [file] [log] [blame]
Eugene Zelenkoe78d1312017-03-03 01:07:34 +00001//===- InstrProf.cpp - Instrumented profiling format support --------------===//
Justin Bognerf8d79192014-03-21 17:24:48 +00002//
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
Chandler Carruth6bda14b2017-06-06 11:49:48 +000015#include "llvm/ProfileData/InstrProf.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000016#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/SmallString.h"
18#include "llvm/ADT/SmallVector.h"
Xinliang David Li0c677872016-01-04 21:31:09 +000019#include "llvm/ADT/StringExtras.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000020#include "llvm/ADT/StringRef.h"
Rong Xu97b68c52016-07-21 20:50:02 +000021#include "llvm/ADT/Triple.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000022#include "llvm/IR/Constant.h"
Xinliang David Li441959d2015-11-09 00:01:22 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/Function.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000025#include "llvm/IR/GlobalValue.h"
Xinliang David Li441959d2015-11-09 00:01:22 +000026#include "llvm/IR/GlobalVariable.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000027#include "llvm/IR/Instruction.h"
28#include "llvm/IR/LLVMContext.h"
Xinliang David Li402477d2016-02-04 19:11:43 +000029#include "llvm/IR/MDBuilder.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000030#include "llvm/IR/Metadata.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000031#include "llvm/IR/Module.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000032#include "llvm/IR/Type.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000033#include "llvm/Support/Casting.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Compiler.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000036#include "llvm/Support/Compression.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000037#include "llvm/Support/Endian.h"
38#include "llvm/Support/Error.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000039#include "llvm/Support/ErrorHandling.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000040#include "llvm/Support/LEB128.h"
Chris Bieneman1efe8012014-09-19 23:19:24 +000041#include "llvm/Support/ManagedStatic.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000042#include "llvm/Support/MathExtras.h"
Xinliang David Li9eb472b2016-07-12 17:14:51 +000043#include "llvm/Support/Path.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000044#include "llvm/Support/SwapByteOrder.h"
45#include <algorithm>
46#include <cassert>
47#include <cstddef>
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000048#include <cstdint>
Chandler Carruth6bda14b2017-06-06 11:49:48 +000049#include <cstring>
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000050#include <memory>
51#include <string>
52#include <system_error>
53#include <utility>
54#include <vector>
Justin Bognerf8d79192014-03-21 17:24:48 +000055
56using namespace llvm;
57
Xinliang David Li9eb472b2016-07-12 17:14:51 +000058static cl::opt<bool> StaticFuncFullModulePrefix(
Rong Xua1a9f702017-02-25 00:00:36 +000059 "static-func-full-module-prefix", cl::init(true),
Xinliang David Li9eb472b2016-07-12 17:14:51 +000060 cl::desc("Use full module build paths in the profile counter names for "
61 "static functions."));
62
Rong Xua1a9f702017-02-25 00:00:36 +000063// This option is tailored to users that have different top-level directory in
64// profile-gen and profile-use compilation. Users need to specific the number
65// of levels to strip. A value larger than the number of directories in the
66// source file will strip all the directory names and only leave the basename.
67//
Rong Xu08d08402017-02-27 17:59:01 +000068// Note current ThinLTO module importing for the indirect-calls assumes
Rong Xua1a9f702017-02-25 00:00:36 +000069// the source directory name not being stripped. A non-zero option value here
70// can potentially prevent some inter-module indirect-call-promotions.
71static cl::opt<unsigned> StaticFuncStripDirNamePrefix(
72 "static-func-strip-dirname-prefix", cl::init(0),
73 cl::desc("Strip specified level of directory name from source path in "
74 "the profile counter name for static functions."));
75
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000076static std::string getInstrProfErrString(instrprof_error Err) {
Vedant Kumar9152fd12016-05-19 03:54:45 +000077 switch (Err) {
78 case instrprof_error::success:
79 return "Success";
80 case instrprof_error::eof:
81 return "End of File";
82 case instrprof_error::unrecognized_format:
83 return "Unrecognized instrumentation profile encoding format";
84 case instrprof_error::bad_magic:
85 return "Invalid instrumentation profile data (bad magic)";
86 case instrprof_error::bad_header:
87 return "Invalid instrumentation profile data (file header is corrupt)";
88 case instrprof_error::unsupported_version:
89 return "Unsupported instrumentation profile format version";
90 case instrprof_error::unsupported_hash_type:
91 return "Unsupported instrumentation profile hash type";
92 case instrprof_error::too_large:
93 return "Too much profile data";
94 case instrprof_error::truncated:
95 return "Truncated profile data";
96 case instrprof_error::malformed:
97 return "Malformed instrumentation profile data";
98 case instrprof_error::unknown_function:
99 return "No profile data available for function";
100 case instrprof_error::hash_mismatch:
101 return "Function control flow change detected (hash mismatch)";
102 case instrprof_error::count_mismatch:
103 return "Function basic block count change detected (counter mismatch)";
104 case instrprof_error::counter_overflow:
105 return "Counter overflow";
106 case instrprof_error::value_site_count_mismatch:
107 return "Function value site count change detected (counter mismatch)";
108 case instrprof_error::compress_failed:
109 return "Failed to compress data (zlib)";
110 case instrprof_error::uncompress_failed:
111 return "Failed to uncompress data (zlib)";
Rong Xu2c684cf2016-10-19 22:51:17 +0000112 case instrprof_error::empty_raw_profile:
113 return "Empty raw profile file";
Vedant Kumar9152fd12016-05-19 03:54:45 +0000114 }
115 llvm_unreachable("A value of instrprof_error has no message.");
116}
117
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000118namespace {
119
Peter Collingbourne4718f8b2016-05-24 20:13:46 +0000120// FIXME: This class is only here to support the transition to llvm::Error. It
121// will be removed once this transition is complete. Clients should prefer to
122// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +0000123class InstrProfErrorCategoryType : public std::error_category {
Reid Kleckner990504e2016-10-19 23:52:38 +0000124 const char *name() const noexcept override { return "llvm.instrprof"; }
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000125
Justin Bognerf8d79192014-03-21 17:24:48 +0000126 std::string message(int IE) const override {
Vedant Kumar9152fd12016-05-19 03:54:45 +0000127 return getInstrProfErrString(static_cast<instrprof_error>(IE));
Justin Bognerf8d79192014-03-21 17:24:48 +0000128 }
Justin Bognerf8d79192014-03-21 17:24:48 +0000129};
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000130
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000131} // end anonymous namespace
Justin Bognerf8d79192014-03-21 17:24:48 +0000132
Chris Bieneman1efe8012014-09-19 23:19:24 +0000133static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
134
Rafael Espindola25188c92014-06-12 01:45:43 +0000135const std::error_category &llvm::instrprof_category() {
Chris Bieneman1efe8012014-09-19 23:19:24 +0000136 return *ErrorCategory;
Justin Bognerf8d79192014-03-21 17:24:48 +0000137}
Xinliang David Li441959d2015-11-09 00:01:22 +0000138
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000139namespace {
140
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000141const char *InstrProfSectNameCommon[] = {
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000142#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000143 SectNameCommon,
144#include "llvm/ProfileData/InstrProfData.inc"
145};
146
147const char *InstrProfSectNameCoff[] = {
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000148#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000149 SectNameCoff,
150#include "llvm/ProfileData/InstrProfData.inc"
151};
152
153const char *InstrProfSectNamePrefix[] = {
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000154#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000155 Prefix,
156#include "llvm/ProfileData/InstrProfData.inc"
157};
158
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000159} // namespace
160
Xinliang David Li441959d2015-11-09 00:01:22 +0000161namespace llvm {
162
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000163std::string getInstrProfSectionName(InstrProfSectKind IPSK,
164 Triple::ObjectFormatType OF,
165 bool AddSegmentInfo) {
166 std::string SectName;
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000167
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000168 if (OF == Triple::MachO && AddSegmentInfo)
169 SectName = InstrProfSectNamePrefix[IPSK];
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000170
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000171 if (OF == Triple::COFF)
172 SectName += InstrProfSectNameCoff[IPSK];
173 else
174 SectName += InstrProfSectNameCommon[IPSK];
Xinliang David Li4a5ddf82017-04-14 17:48:40 +0000175
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000176 if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
177 SectName += ",regular,live_support";
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000178
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000179 return SectName;
Xinliang David Li4a5ddf82017-04-14 17:48:40 +0000180}
181
Vedant Kumar42369db2016-05-11 19:42:19 +0000182void SoftInstrProfErrors::addError(instrprof_error IE) {
183 if (IE == instrprof_error::success)
184 return;
185
186 if (FirstError == instrprof_error::success)
187 FirstError = IE;
188
189 switch (IE) {
190 case instrprof_error::hash_mismatch:
191 ++NumHashMismatches;
192 break;
193 case instrprof_error::count_mismatch:
194 ++NumCountMismatches;
195 break;
196 case instrprof_error::counter_overflow:
197 ++NumCounterOverflows;
198 break;
199 case instrprof_error::value_site_count_mismatch:
200 ++NumValueSiteCountMismatches;
201 break;
202 default:
203 llvm_unreachable("Not a soft error");
204 }
205}
206
Vedant Kumar9152fd12016-05-19 03:54:45 +0000207std::string InstrProfError::message() const {
208 return getInstrProfErrString(Err);
209}
210
211char InstrProfError::ID = 0;
212
Xinliang David Li441959d2015-11-09 00:01:22 +0000213std::string getPGOFuncName(StringRef RawFuncName,
214 GlobalValue::LinkageTypes Linkage,
Xinliang David Lia86545b2015-12-11 20:23:22 +0000215 StringRef FileName,
216 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
Teresa Johnsonb43027d2016-03-15 02:13:19 +0000217 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000218}
219
Rong Xua1a9f702017-02-25 00:00:36 +0000220// Strip NumPrefix level of directory name from PathNameStr. If the number of
221// directory separators is less than NumPrefix, strip all the directories and
222// leave base file name only.
223static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
224 uint32_t Count = NumPrefix;
225 uint32_t Pos = 0, LastPos = 0;
226 for (auto & CI : PathNameStr) {
227 ++Pos;
228 if (llvm::sys::path::is_separator(CI)) {
229 LastPos = Pos;
230 --Count;
231 }
232 if (Count == 0)
233 break;
234 }
235 return PathNameStr.substr(LastPos);
236}
237
Rong Xub5341662016-03-30 18:37:52 +0000238// Return the PGOFuncName. This function has some special handling when called
239// in LTO optimization. The following only applies when calling in LTO passes
240// (when \c InLTO is true): LTO's internalization privatizes many global linkage
241// symbols. This happens after value profile annotation, but those internal
242// linkage functions should not have a source prefix.
Teresa Johnson8c1bc982016-08-29 22:46:56 +0000243// Additionally, for ThinLTO mode, exported internal functions are promoted
244// and renamed. We need to ensure that the original internal PGO name is
245// used when computing the GUID that is compared against the profiled GUIDs.
Rong Xub5341662016-03-30 18:37:52 +0000246// To differentiate compiler generated internal symbols from original ones,
247// PGOFuncName meta data are created and attached to the original internal
248// symbols in the value profile annotation step
249// (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
250// data, its original linkage must be non-internal.
251std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
Xinliang David Li9eb472b2016-07-12 17:14:51 +0000252 if (!InLTO) {
253 StringRef FileName = (StaticFuncFullModulePrefix
254 ? F.getParent()->getName()
255 : sys::path::filename(F.getParent()->getName()));
Rong Xua1a9f702017-02-25 00:00:36 +0000256 if (StaticFuncFullModulePrefix && StaticFuncStripDirNamePrefix != 0)
257 FileName = stripDirPrefix(FileName, StaticFuncStripDirNamePrefix);
Xinliang David Li9eb472b2016-07-12 17:14:51 +0000258 return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
259 }
Rong Xub5341662016-03-30 18:37:52 +0000260
Rong Xu8e8fe852016-04-01 16:43:30 +0000261 // In LTO mode (when InLTO is true), first check if there is a meta data.
262 if (MDNode *MD = getPGOFuncNameMetadata(F)) {
Rong Xub5341662016-03-30 18:37:52 +0000263 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
264 return S.str();
265 }
266
267 // If there is no meta data, the function must be a global before the value
268 // profile annotation pass. Its current linkage may be internal if it is
269 // internalized in LTO mode.
Rong Xu8e8fe852016-04-01 16:43:30 +0000270 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
Xinliang David Li441959d2015-11-09 00:01:22 +0000271}
272
Xinliang David Li4ec40142015-12-15 19:44:45 +0000273StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
274 if (FileName.empty())
Vedant Kumar43a85652016-03-28 15:49:08 +0000275 return PGOFuncName;
Xinliang David Li4ec40142015-12-15 19:44:45 +0000276 // Drop the file name including ':'. See also getPGOFuncName.
277 if (PGOFuncName.startswith(FileName))
278 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
279 return PGOFuncName;
280}
281
Xinliang David Lid1bab962015-12-12 17:28:03 +0000282// \p FuncName is the string used as profile lookup key for the function. A
283// symbol is created to hold the name. Return the legalized symbol name.
Vedant Kumaraa0cae62016-03-16 20:49:26 +0000284std::string getPGOFuncNameVarName(StringRef FuncName,
285 GlobalValue::LinkageTypes Linkage) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000286 std::string VarName = getInstrProfNameVarPrefix();
287 VarName += FuncName;
288
289 if (!GlobalValue::isLocalLinkage(Linkage))
290 return VarName;
291
292 // Now fix up illegal chars in local VarName that may upset the assembler.
Xinliang David Lieeaf0bc2016-06-10 06:32:26 +0000293 const char *InvalidChars = "-:<>/\"'";
Xinliang David Lid1bab962015-12-12 17:28:03 +0000294 size_t found = VarName.find_first_of(InvalidChars);
295 while (found != std::string::npos) {
296 VarName[found] = '_';
297 found = VarName.find_first_of(InvalidChars, found + 1);
298 }
299 return VarName;
300}
301
Xinliang David Li441959d2015-11-09 00:01:22 +0000302GlobalVariable *createPGOFuncNameVar(Module &M,
303 GlobalValue::LinkageTypes Linkage,
Xinliang David Li897d2922016-03-16 22:13:41 +0000304 StringRef PGOFuncName) {
Xinliang David Li441959d2015-11-09 00:01:22 +0000305 // We generally want to match the function's linkage, but available_externally
306 // and extern_weak both have the wrong semantics, and anything that doesn't
307 // need to link across compilation units doesn't need to be visible at all.
308 if (Linkage == GlobalValue::ExternalWeakLinkage)
309 Linkage = GlobalValue::LinkOnceAnyLinkage;
310 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
311 Linkage = GlobalValue::LinkOnceODRLinkage;
312 else if (Linkage == GlobalValue::InternalLinkage ||
313 Linkage == GlobalValue::ExternalLinkage)
314 Linkage = GlobalValue::PrivateLinkage;
315
Xinliang David Li897d2922016-03-16 22:13:41 +0000316 auto *Value =
317 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
Xinliang David Li441959d2015-11-09 00:01:22 +0000318 auto FuncNameVar =
319 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
Xinliang David Li897d2922016-03-16 22:13:41 +0000320 getPGOFuncNameVarName(PGOFuncName, Linkage));
Xinliang David Li441959d2015-11-09 00:01:22 +0000321
322 // Hide the symbol so that we correctly get a copy for each executable.
323 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
324 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
325
326 return FuncNameVar;
327}
328
Xinliang David Li897d2922016-03-16 22:13:41 +0000329GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
330 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000331}
Xinliang David Liee415892015-11-10 00:24:45 +0000332
Rong Xub5341662016-03-30 18:37:52 +0000333void InstrProfSymtab::create(Module &M, bool InLTO) {
334 for (Function &F : M) {
335 // Function may not have a name: like using asm("") to overwrite the name.
336 // Ignore in this case.
337 if (!F.hasName())
338 continue;
339 const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
340 addFuncName(PGOFuncName);
Rong Xud5a57b52016-03-31 17:39:33 +0000341 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
Dehao Chen4a435e02017-03-14 17:33:01 +0000342 // In ThinLTO, local function may have been promoted to global and have
343 // suffix added to the function name. We need to add the stripped function
344 // name to the symbol table so that we can find a match from profile.
345 if (InLTO) {
346 auto pos = PGOFuncName.find('.');
347 if (pos != std::string::npos) {
348 const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
349 addFuncName(OtherFuncName);
350 MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F);
351 }
352 }
Rong Xub5341662016-03-30 18:37:52 +0000353 }
Xinliang David Li59411db2016-01-20 01:26:34 +0000354
355 finalizeSymtab();
356}
357
Benjamin Kramer9d8ed262017-05-28 13:23:02 +0000358Error collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs,
Vedant Kumar9152fd12016-05-19 03:54:45 +0000359 bool doCompression, std::string &Result) {
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000360 assert(!NameStrs.empty() && "No name data to emit");
Vedant Kumar86705ba2016-03-28 21:06:42 +0000361
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000362 uint8_t Header[16], *P = Header;
Xinliang David Li0c677872016-01-04 21:31:09 +0000363 std::string UncompressedNameStrings =
Vedant Kumar86705ba2016-03-28 21:06:42 +0000364 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
365
366 assert(StringRef(UncompressedNameStrings)
367 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
368 "PGO name is invalid (contains separator token)");
Xinliang David Li13ea29b2016-01-04 20:26:05 +0000369
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000370 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
371 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000372
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000373 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000374 EncLen = encodeULEB128(CompressedLen, P);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000375 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000376 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
377 unsigned HeaderLen = P - &Header[0];
378 Result.append(HeaderStr, HeaderLen);
379 Result += InputStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000380 return Error::success();
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000381 };
382
Vedant Kumar9152fd12016-05-19 03:54:45 +0000383 if (!doCompression) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000384 return WriteStringToResult(0, UncompressedNameStrings);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000385 }
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000386
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000387 SmallString<128> CompressedNameStrings;
George Rimar167ca4a2017-01-17 15:45:07 +0000388 Error E = zlib::compress(StringRef(UncompressedNameStrings),
389 CompressedNameStrings, zlib::BestSizeCompression);
390 if (E) {
391 consumeError(std::move(E));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000392 return make_error<InstrProfError>(instrprof_error::compress_failed);
George Rimar167ca4a2017-01-17 15:45:07 +0000393 }
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000394
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000395 return WriteStringToResult(CompressedNameStrings.size(),
396 CompressedNameStrings);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000397}
398
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000399StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
Xinliang David Li37c1fa02016-01-03 04:38:13 +0000400 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
401 StringRef NameStr =
402 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
403 return NameStr;
404}
405
Benjamin Kramer9d8ed262017-05-28 13:23:02 +0000406Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
Vedant Kumar9152fd12016-05-19 03:54:45 +0000407 std::string &Result, bool doCompression) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000408 std::vector<std::string> NameStrs;
409 for (auto *NameVar : NameVars) {
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000410 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000411 }
Xinliang David Li73163752016-01-26 23:13:00 +0000412 return collectPGOFuncNameStrings(
413 NameStrs, zlib::isAvailable() && doCompression, Result);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000414}
415
Vedant Kumar9152fd12016-05-19 03:54:45 +0000416Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000417 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
418 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
419 NameStrings.size());
420 while (P < EndP) {
421 uint32_t N;
422 uint64_t UncompressedSize = decodeULEB128(P, &N);
423 P += N;
424 uint64_t CompressedSize = decodeULEB128(P, &N);
425 P += N;
426 bool isCompressed = (CompressedSize != 0);
427 SmallString<128> UncompressedNameStrings;
428 StringRef NameStrings;
429 if (isCompressed) {
430 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
431 CompressedSize);
George Rimar167ca4a2017-01-17 15:45:07 +0000432 if (Error E =
433 zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
434 UncompressedSize)) {
435 consumeError(std::move(E));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000436 return make_error<InstrProfError>(instrprof_error::uncompress_failed);
George Rimar167ca4a2017-01-17 15:45:07 +0000437 }
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000438 P += CompressedSize;
439 NameStrings = StringRef(UncompressedNameStrings.data(),
440 UncompressedNameStrings.size());
441 } else {
442 NameStrings =
443 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
444 P += UncompressedSize;
445 }
446 // Now parse the name strings.
Xinliang David Li204efe22016-01-04 22:09:26 +0000447 SmallVector<StringRef, 0> Names;
Vedant Kumar86705ba2016-03-28 21:06:42 +0000448 NameStrings.split(Names, getInstrProfNameSeparator());
Xinliang David Li204efe22016-01-04 22:09:26 +0000449 for (StringRef &Name : Names)
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000450 Symtab.addFuncName(Name);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000451
452 while (P < EndP && *P == 0)
453 P++;
454 }
455 Symtab.finalizeSymtab();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000456 return Error::success();
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000457}
458
Vedant Kumar42369db2016-05-11 19:42:19 +0000459void InstrProfValueSiteRecord::merge(SoftInstrProfErrors &SIPE,
460 InstrProfValueSiteRecord &Input,
461 uint64_t Weight) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000462 this->sortByTargetValues();
463 Input.sortByTargetValues();
464 auto I = ValueData.begin();
465 auto IE = ValueData.end();
Xinliang David Li5c24da52015-12-20 05:15:45 +0000466 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
467 ++J) {
468 while (I != IE && I->Value < J->Value)
469 ++I;
470 if (I != IE && I->Value == J->Value) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000471 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000472 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000473 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000474 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000475 ++I;
476 continue;
477 }
478 ValueData.insert(I, *J);
479 }
Xinliang David Li5c24da52015-12-20 05:15:45 +0000480}
481
Vedant Kumar42369db2016-05-11 19:42:19 +0000482void InstrProfValueSiteRecord::scale(SoftInstrProfErrors &SIPE,
483 uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000484 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
485 bool Overflowed;
486 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
487 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000488 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000489 }
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000490}
491
Xinliang David Li020f22d2015-12-18 23:06:37 +0000492// Merge Value Profile data from Src record to this record for ValueKind.
493// Scale merged value counts by \p Weight.
Vedant Kumar42369db2016-05-11 19:42:19 +0000494void InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
495 InstrProfRecord &Src,
496 uint64_t Weight) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000497 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
498 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
Vedant Kumar42369db2016-05-11 19:42:19 +0000499 if (ThisNumValueSites != OtherNumValueSites) {
500 SIPE.addError(instrprof_error::value_site_count_mismatch);
501 return;
502 }
Xinliang David Li020f22d2015-12-18 23:06:37 +0000503 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
504 getValueSitesForKind(ValueKind);
505 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
506 Src.getValueSitesForKind(ValueKind);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000507 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Vedant Kumar42369db2016-05-11 19:42:19 +0000508 ThisSiteRecords[I].merge(SIPE, OtherSiteRecords[I], Weight);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000509}
510
Vedant Kumar42369db2016-05-11 19:42:19 +0000511void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000512 // If the number of counters doesn't match we either have bad data
513 // or a hash collision.
Vedant Kumar42369db2016-05-11 19:42:19 +0000514 if (Counts.size() != Other.Counts.size()) {
515 SIPE.addError(instrprof_error::count_mismatch);
516 return;
517 }
Xinliang David Li020f22d2015-12-18 23:06:37 +0000518
519 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
520 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000521 Counts[I] =
522 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000523 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000524 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000525 }
526
527 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Vedant Kumar42369db2016-05-11 19:42:19 +0000528 mergeValueProfData(Kind, Other, Weight);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000529}
Xinliang David Lia716cc52015-12-20 06:22:13 +0000530
Vedant Kumar42369db2016-05-11 19:42:19 +0000531void InstrProfRecord::scaleValueProfData(uint32_t ValueKind, uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000532 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
533 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
534 getValueSitesForKind(ValueKind);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000535 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Vedant Kumar42369db2016-05-11 19:42:19 +0000536 ThisSiteRecords[I].scale(SIPE, Weight);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000537}
538
Vedant Kumar42369db2016-05-11 19:42:19 +0000539void InstrProfRecord::scale(uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000540 for (auto &Count : this->Counts) {
541 bool Overflowed;
542 Count = SaturatingMultiply(Count, Weight, &Overflowed);
Vedant Kumar42369db2016-05-11 19:42:19 +0000543 if (Overflowed)
544 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000545 }
546 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Vedant Kumar42369db2016-05-11 19:42:19 +0000547 scaleValueProfData(Kind, Weight);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000548}
549
Xinliang David Li020f22d2015-12-18 23:06:37 +0000550// Map indirect call target name hash to name string.
551uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000552 ValueMapType *ValueMap) {
553 if (!ValueMap)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000554 return Value;
555 switch (ValueKind) {
556 case IPVK_IndirectCallTarget: {
557 auto Result =
Xinliang David Lia716cc52015-12-20 06:22:13 +0000558 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
559 [](const std::pair<uint64_t, uint64_t> &LHS,
Xinliang David Li020f22d2015-12-18 23:06:37 +0000560 uint64_t RHS) { return LHS.first < RHS; });
Xinliang David Li8dd4ca82016-04-11 17:13:08 +0000561 // Raw function pointer collected by value profiler may be from
562 // external functions that are not instrumented. They won't have
563 // mapping data to be used by the deserializer. Force the value to
564 // be 0 in this case.
Xinliang David Li28464482016-04-10 03:32:02 +0000565 if (Result != ValueMap->end() && Result->first == Value)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000566 Value = (uint64_t)Result->second;
Xinliang David Li28464482016-04-10 03:32:02 +0000567 else
568 Value = 0;
Xinliang David Li020f22d2015-12-18 23:06:37 +0000569 break;
570 }
571 }
572 return Value;
573}
574
Xinliang David Li020f22d2015-12-18 23:06:37 +0000575void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
576 InstrProfValueData *VData, uint32_t N,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000577 ValueMapType *ValueMap) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000578 for (uint32_t I = 0; I < N; I++) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000579 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000580 }
581 std::vector<InstrProfValueSiteRecord> &ValueSites =
582 getValueSitesForKind(ValueKind);
583 if (N == 0)
Vedant Kumar6b22ba62016-05-11 16:03:02 +0000584 ValueSites.emplace_back();
Xinliang David Li020f22d2015-12-18 23:06:37 +0000585 else
586 ValueSites.emplace_back(VData, VData + N);
587}
588
Xinliang David Lib75544a2015-11-28 19:07:09 +0000589#define INSTR_PROF_COMMON_API_IMPL
590#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Liee415892015-11-10 00:24:45 +0000591
Xinliang David Li020f22d2015-12-18 23:06:37 +0000592/*!
Xinliang David Lib75544a2015-11-28 19:07:09 +0000593 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
Xinliang David Lied966772015-11-25 23:31:18 +0000594 * class. These C wrappers are used as adaptors so that C++ code can be
595 * invoked as callbacks.
596 */
Xinliang David Lif47cf552015-11-25 06:23:38 +0000597uint32_t getNumValueKindsInstrProf(const void *Record) {
598 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
599}
600
601uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
602 return reinterpret_cast<const InstrProfRecord *>(Record)
603 ->getNumValueSites(VKind);
604}
605
606uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
607 return reinterpret_cast<const InstrProfRecord *>(Record)
608 ->getNumValueData(VKind);
609}
610
611uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
612 uint32_t S) {
613 return reinterpret_cast<const InstrProfRecord *>(R)
614 ->getNumValueDataForSite(VK, S);
615}
616
617void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
Xinliang David Li1e4c8092016-02-04 05:29:51 +0000618 uint32_t K, uint32_t S) {
619 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
Xinliang David Lie8092312015-11-25 19:13:00 +0000620}
621
Xinliang David Lif47cf552015-11-25 06:23:38 +0000622ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
Xinliang David Li38b9a322015-12-15 21:57:08 +0000623 ValueProfData *VD =
624 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
625 memset(VD, 0, TotalSizeInBytes);
626 return VD;
Xinliang David Lif47cf552015-11-25 06:23:38 +0000627}
628
629static ValueProfRecordClosure InstrProfRecordClosure = {
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000630 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000631 getNumValueKindsInstrProf,
632 getNumValueSitesInstrProf,
633 getNumValueDataInstrProf,
634 getNumValueDataForSiteInstrProf,
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000635 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000636 getValueForSiteInstrProf,
Xinliang David Li38b9a322015-12-15 21:57:08 +0000637 allocValueProfDataInstrProf};
Xinliang David Lif47cf552015-11-25 06:23:38 +0000638
Xinliang David Lie8092312015-11-25 19:13:00 +0000639// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000640uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
641 InstrProfRecordClosure.Record = &Record;
642 return getValueProfDataSize(&InstrProfRecordClosure);
643}
644
Xinliang David Lie8092312015-11-25 19:13:00 +0000645// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000646std::unique_ptr<ValueProfData>
647ValueProfData::serializeFrom(const InstrProfRecord &Record) {
648 InstrProfRecordClosure.Record = &Record;
649
650 std::unique_ptr<ValueProfData> VPD(
Xinliang David Li0e6a36e2015-12-01 19:47:32 +0000651 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
Xinliang David Lif47cf552015-11-25 06:23:38 +0000652 return VPD;
653}
654
Xinliang David Lie8092312015-11-25 19:13:00 +0000655void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
656 InstrProfRecord::ValueMapType *VMap) {
657 Record.reserveSites(Kind, NumValueSites);
658
659 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
660 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
661 uint8_t ValueDataCount = this->SiteCountArray[VSite];
662 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
663 ValueData += ValueDataCount;
664 }
665}
Xinliang David Lied966772015-11-25 23:31:18 +0000666
Xinliang David Lie8092312015-11-25 19:13:00 +0000667// For writing/serializing, Old is the host endianness, and New is
668// byte order intended on disk. For Reading/deserialization, Old
669// is the on-disk source endianness, and New is the host endianness.
670void ValueProfRecord::swapBytes(support::endianness Old,
671 support::endianness New) {
672 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000673
Xinliang David Lie8092312015-11-25 19:13:00 +0000674 if (Old == New)
675 return;
676
677 if (getHostEndianness() != Old) {
678 sys::swapByteOrder<uint32_t>(NumValueSites);
679 sys::swapByteOrder<uint32_t>(Kind);
680 }
681 uint32_t ND = getValueProfRecordNumValueData(this);
682 InstrProfValueData *VD = getValueProfRecordValueData(this);
683
684 // No need to swap byte array: SiteCountArrray.
685 for (uint32_t I = 0; I < ND; I++) {
686 sys::swapByteOrder<uint64_t>(VD[I].Value);
687 sys::swapByteOrder<uint64_t>(VD[I].Count);
688 }
689 if (getHostEndianness() == Old) {
690 sys::swapByteOrder<uint32_t>(NumValueSites);
691 sys::swapByteOrder<uint32_t>(Kind);
692 }
693}
694
695void ValueProfData::deserializeTo(InstrProfRecord &Record,
696 InstrProfRecord::ValueMapType *VMap) {
697 if (NumValueKinds == 0)
698 return;
699
700 ValueProfRecord *VR = getFirstValueProfRecord(this);
701 for (uint32_t K = 0; K < NumValueKinds; K++) {
702 VR->deserializeTo(Record, VMap);
703 VR = getValueProfRecordNext(VR);
704 }
705}
706
707template <class T>
708static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
709 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000710
Xinliang David Lie8092312015-11-25 19:13:00 +0000711 if (Orig == little)
712 return endian::readNext<T, little, unaligned>(D);
713 else
714 return endian::readNext<T, big, unaligned>(D);
715}
716
717static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
718 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
719 ValueProfData());
720}
721
Vedant Kumar9152fd12016-05-19 03:54:45 +0000722Error ValueProfData::checkIntegrity() {
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000723 if (NumValueKinds > IPVK_Last + 1)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000724 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000725 // Total size needs to be mulltiple of quadword size.
726 if (TotalSize % sizeof(uint64_t))
Vedant Kumar9152fd12016-05-19 03:54:45 +0000727 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000728
729 ValueProfRecord *VR = getFirstValueProfRecord(this);
730 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
731 if (VR->Kind > IPVK_Last)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000732 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000733 VR = getValueProfRecordNext(VR);
734 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000735 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000736 }
Vedant Kumar9152fd12016-05-19 03:54:45 +0000737 return Error::success();
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000738}
739
Vedant Kumar9152fd12016-05-19 03:54:45 +0000740Expected<std::unique_ptr<ValueProfData>>
Xinliang David Liee415892015-11-10 00:24:45 +0000741ValueProfData::getValueProfData(const unsigned char *D,
742 const unsigned char *const BufferEnd,
743 support::endianness Endianness) {
744 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000745
Xinliang David Liee415892015-11-10 00:24:45 +0000746 if (D + sizeof(ValueProfData) > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000747 return make_error<InstrProfError>(instrprof_error::truncated);
Xinliang David Liee415892015-11-10 00:24:45 +0000748
Xinliang David Lib8c3ad12015-11-17 03:47:21 +0000749 const unsigned char *Header = D;
750 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
Xinliang David Liee415892015-11-10 00:24:45 +0000751 if (D + TotalSize > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000752 return make_error<InstrProfError>(instrprof_error::too_large);
Xinliang David Liee415892015-11-10 00:24:45 +0000753
Xinliang David Lif47cf552015-11-25 06:23:38 +0000754 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
Xinliang David Liee415892015-11-10 00:24:45 +0000755 memcpy(VPD.get(), D, TotalSize);
756 // Byte swap.
757 VPD->swapBytesToHost(Endianness);
758
Vedant Kumar9152fd12016-05-19 03:54:45 +0000759 Error E = VPD->checkIntegrity();
760 if (E)
761 return std::move(E);
Xinliang David Liee415892015-11-10 00:24:45 +0000762
Xinliang David Liee415892015-11-10 00:24:45 +0000763 return std::move(VPD);
764}
765
766void ValueProfData::swapBytesToHost(support::endianness Endianness) {
767 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000768
Xinliang David Liee415892015-11-10 00:24:45 +0000769 if (Endianness == getHostEndianness())
770 return;
771
772 sys::swapByteOrder<uint32_t>(TotalSize);
773 sys::swapByteOrder<uint32_t>(NumValueKinds);
774
Xinliang David Lif47cf552015-11-25 06:23:38 +0000775 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000776 for (uint32_t K = 0; K < NumValueKinds; K++) {
777 VR->swapBytes(Endianness, getHostEndianness());
Xinliang David Liac5b8602015-11-25 04:29:24 +0000778 VR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000779 }
780}
781
782void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
783 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000784
Xinliang David Liee415892015-11-10 00:24:45 +0000785 if (Endianness == getHostEndianness())
786 return;
787
Xinliang David Lif47cf552015-11-25 06:23:38 +0000788 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000789 for (uint32_t K = 0; K < NumValueKinds; K++) {
Xinliang David Liac5b8602015-11-25 04:29:24 +0000790 ValueProfRecord *NVR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000791 VR->swapBytes(getHostEndianness(), Endianness);
792 VR = NVR;
793 }
794 sys::swapByteOrder<uint32_t>(TotalSize);
795 sys::swapByteOrder<uint32_t>(NumValueKinds);
796}
Xinliang David Lie8092312015-11-25 19:13:00 +0000797
Xinliang David Li402477d2016-02-04 19:11:43 +0000798void annotateValueSite(Module &M, Instruction &Inst,
799 const InstrProfRecord &InstrProfR,
Rong Xu69683f12016-02-10 22:19:43 +0000800 InstrProfValueKind ValueKind, uint32_t SiteIdx,
801 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000802 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
Betul Buyukkurt4f1e8c92016-04-14 16:25:45 +0000803 if (!NV)
804 return;
Xinliang David Li402477d2016-02-04 19:11:43 +0000805
806 uint64_t Sum = 0;
807 std::unique_ptr<InstrProfValueData[]> VD =
808 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
809
Rong Xu311ada12016-03-30 16:56:31 +0000810 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
811 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
Rong Xubb494902016-02-12 21:36:17 +0000812}
813
814void annotateValueSite(Module &M, Instruction &Inst,
Rong Xu311ada12016-03-30 16:56:31 +0000815 ArrayRef<InstrProfValueData> VDs,
Rong Xubb494902016-02-12 21:36:17 +0000816 uint64_t Sum, InstrProfValueKind ValueKind,
817 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000818 LLVMContext &Ctx = M.getContext();
819 MDBuilder MDHelper(Ctx);
820 SmallVector<Metadata *, 3> Vals;
821 // Tag
822 Vals.push_back(MDHelper.createString("VP"));
823 // Value Kind
824 Vals.push_back(MDHelper.createConstant(
825 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
826 // Total Count
827 Vals.push_back(
828 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
829
830 // Value Profile Data
Rong Xu69683f12016-02-10 22:19:43 +0000831 uint32_t MDCount = MaxMDCount;
Rong Xu311ada12016-03-30 16:56:31 +0000832 for (auto &VD : VDs) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000833 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000834 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000835 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000836 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000837 if (--MDCount == 0)
838 break;
839 }
840 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
841}
842
843bool getValueProfDataFromInst(const Instruction &Inst,
844 InstrProfValueKind ValueKind,
845 uint32_t MaxNumValueData,
846 InstrProfValueData ValueData[],
847 uint32_t &ActualNumValueData, uint64_t &TotalC) {
848 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
849 if (!MD)
850 return false;
851
852 unsigned NOps = MD->getNumOperands();
853
854 if (NOps < 5)
855 return false;
856
857 // Operand 0 is a string tag "VP":
858 MDString *Tag = cast<MDString>(MD->getOperand(0));
859 if (!Tag)
860 return false;
861
862 if (!Tag->getString().equals("VP"))
863 return false;
864
865 // Now check kind:
866 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
867 if (!KindInt)
868 return false;
869 if (KindInt->getZExtValue() != ValueKind)
870 return false;
871
872 // Get total count
873 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
874 if (!TotalCInt)
875 return false;
876 TotalC = TotalCInt->getZExtValue();
877
878 ActualNumValueData = 0;
879
880 for (unsigned I = 3; I < NOps; I += 2) {
881 if (ActualNumValueData >= MaxNumValueData)
882 break;
883 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
884 ConstantInt *Count =
885 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
886 if (!Value || !Count)
887 return false;
888 ValueData[ActualNumValueData].Value = Value->getZExtValue();
889 ValueData[ActualNumValueData].Count = Count->getZExtValue();
890 ActualNumValueData++;
891 }
892 return true;
893}
Rong Xu8e8fe852016-04-01 16:43:30 +0000894
Rong Xu92c2eae2016-04-01 20:15:04 +0000895MDNode *getPGOFuncNameMetadata(const Function &F) {
896 return F.getMetadata(getPGOFuncNameMetadataName());
897}
898
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000899void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
Rong Xuf8f051c2016-04-22 21:00:17 +0000900 // Only for internal linkage functions.
901 if (PGOFuncName == F.getName())
902 return;
903 // Don't create duplicated meta-data.
904 if (getPGOFuncNameMetadata(F))
Rong Xu8e8fe852016-04-01 16:43:30 +0000905 return;
Rong Xu8e8fe852016-04-01 16:43:30 +0000906 LLVMContext &C = F.getContext();
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000907 MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
Rong Xu8e8fe852016-04-01 16:43:30 +0000908 F.setMetadata(getPGOFuncNameMetadataName(), N);
909}
910
Rong Xu97b68c52016-07-21 20:50:02 +0000911bool needsComdatForCounter(const Function &F, const Module &M) {
912 if (F.hasComdat())
913 return true;
914
915 Triple TT(M.getTargetTriple());
Dan Gohman1209c7a2017-01-17 20:34:09 +0000916 if (!TT.isOSBinFormatELF() && !TT.isOSBinFormatWasm())
Rong Xu97b68c52016-07-21 20:50:02 +0000917 return false;
918
919 // See createPGOFuncNameVar for more details. To avoid link errors, profile
920 // counters for function with available_externally linkage needs to be changed
921 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
922 // created. Without using comdat, duplicate entries won't be removed by the
923 // linker leading to increased data segement size and raw profile size. Even
924 // worse, since the referenced counter from profile per-function data object
925 // will be resolved to the common strong definition, the profile counts for
926 // available_externally functions will end up being duplicated in raw profile
927 // data. This can result in distorted profile as the counts of those dups
928 // will be accumulated by the profile merger.
929 GlobalValue::LinkageTypes Linkage = F.getLinkage();
930 if (Linkage != GlobalValue::ExternalWeakLinkage &&
931 Linkage != GlobalValue::AvailableExternallyLinkage)
932 return false;
933
934 return true;
935}
Rong Xu20f5df12017-01-11 20:19:41 +0000936
937// Check if INSTR_PROF_RAW_VERSION_VAR is defined.
938bool isIRPGOFlagSet(const Module *M) {
939 auto IRInstrVar =
940 M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
941 if (!IRInstrVar || IRInstrVar->isDeclaration() ||
942 IRInstrVar->hasLocalLinkage())
943 return false;
944
945 // Check if the flag is set.
946 if (!IRInstrVar->hasInitializer())
947 return false;
948
949 const Constant *InitVal = IRInstrVar->getInitializer();
950 if (!InitVal)
951 return false;
952
953 return (dyn_cast<ConstantInt>(InitVal)->getZExtValue() &
954 VARIANT_MASK_IR_PROF) != 0;
955}
956
957// Check if we can safely rename this Comdat function.
958bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
959 if (F.getName().empty())
960 return false;
961 if (!needsComdatForCounter(F, *(F.getParent())))
962 return false;
963 // Unsafe to rename the address-taken function (which can be used in
964 // function comparison).
965 if (CheckAddressTaken && F.hasAddressTaken())
966 return false;
967 // Only safe to do if this function may be discarded if it is not used
968 // in the compilation unit.
969 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
970 return false;
971
972 // For AvailableExternallyLinkage functions.
973 if (!F.hasComdat()) {
974 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
975 return true;
976 }
977 return true;
978}
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000979
Rong Xu48596b62017-04-04 16:42:20 +0000980// Parse the value profile options.
Benjamin Kramer9d8ed262017-05-28 13:23:02 +0000981void getMemOPSizeRangeFromOption(StringRef MemOPSizeRange, int64_t &RangeStart,
982 int64_t &RangeLast) {
Rong Xu48596b62017-04-04 16:42:20 +0000983 static const int64_t DefaultMemOPSizeRangeStart = 0;
984 static const int64_t DefaultMemOPSizeRangeLast = 8;
985 RangeStart = DefaultMemOPSizeRangeStart;
986 RangeLast = DefaultMemOPSizeRangeLast;
987
988 if (!MemOPSizeRange.empty()) {
Benjamin Kramer9d8ed262017-05-28 13:23:02 +0000989 auto Pos = MemOPSizeRange.find(':');
Rong Xu48596b62017-04-04 16:42:20 +0000990 if (Pos != std::string::npos) {
991 if (Pos > 0)
Benjamin Kramer9d8ed262017-05-28 13:23:02 +0000992 MemOPSizeRange.substr(0, Pos).getAsInteger(10, RangeStart);
Rong Xu48596b62017-04-04 16:42:20 +0000993 if (Pos < MemOPSizeRange.size() - 1)
Benjamin Kramer9d8ed262017-05-28 13:23:02 +0000994 MemOPSizeRange.substr(Pos + 1).getAsInteger(10, RangeLast);
Rong Xu48596b62017-04-04 16:42:20 +0000995 } else
Benjamin Kramer9d8ed262017-05-28 13:23:02 +0000996 MemOPSizeRange.getAsInteger(10, RangeLast);
Rong Xu48596b62017-04-04 16:42:20 +0000997 }
998 assert(RangeLast >= RangeStart);
999}
1000
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001001} // end namespace llvm