blob: a732bedc6fa47c86880733f2f6bebe4f1596b635 [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";
David Blaikieb8cc0542017-07-21 21:41:15 +0000114 case instrprof_error::zlib_unavailable:
115 return "Profile uses zlib compression but the profile reader was built without zlib support";
Vedant Kumar9152fd12016-05-19 03:54:45 +0000116 }
117 llvm_unreachable("A value of instrprof_error has no message.");
118}
119
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000120namespace {
121
Peter Collingbourne4718f8b2016-05-24 20:13:46 +0000122// FIXME: This class is only here to support the transition to llvm::Error. It
123// will be removed once this transition is complete. Clients should prefer to
124// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +0000125class InstrProfErrorCategoryType : public std::error_category {
Reid Kleckner990504e2016-10-19 23:52:38 +0000126 const char *name() const noexcept override { return "llvm.instrprof"; }
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000127
Justin Bognerf8d79192014-03-21 17:24:48 +0000128 std::string message(int IE) const override {
Vedant Kumar9152fd12016-05-19 03:54:45 +0000129 return getInstrProfErrString(static_cast<instrprof_error>(IE));
Justin Bognerf8d79192014-03-21 17:24:48 +0000130 }
Justin Bognerf8d79192014-03-21 17:24:48 +0000131};
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000132
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000133} // end anonymous namespace
Justin Bognerf8d79192014-03-21 17:24:48 +0000134
Chris Bieneman1efe8012014-09-19 23:19:24 +0000135static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
136
Rafael Espindola25188c92014-06-12 01:45:43 +0000137const std::error_category &llvm::instrprof_category() {
Chris Bieneman1efe8012014-09-19 23:19:24 +0000138 return *ErrorCategory;
Justin Bognerf8d79192014-03-21 17:24:48 +0000139}
Xinliang David Li441959d2015-11-09 00:01:22 +0000140
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000141namespace {
142
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000143const char *InstrProfSectNameCommon[] = {
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000144#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000145 SectNameCommon,
146#include "llvm/ProfileData/InstrProfData.inc"
147};
148
149const char *InstrProfSectNameCoff[] = {
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000150#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000151 SectNameCoff,
152#include "llvm/ProfileData/InstrProfData.inc"
153};
154
155const char *InstrProfSectNamePrefix[] = {
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000156#define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000157 Prefix,
158#include "llvm/ProfileData/InstrProfData.inc"
159};
160
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000161} // namespace
162
Xinliang David Li441959d2015-11-09 00:01:22 +0000163namespace llvm {
164
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000165std::string getInstrProfSectionName(InstrProfSectKind IPSK,
166 Triple::ObjectFormatType OF,
167 bool AddSegmentInfo) {
168 std::string SectName;
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000169
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000170 if (OF == Triple::MachO && AddSegmentInfo)
171 SectName = InstrProfSectNamePrefix[IPSK];
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000172
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000173 if (OF == Triple::COFF)
174 SectName += InstrProfSectNameCoff[IPSK];
175 else
176 SectName += InstrProfSectNameCommon[IPSK];
Xinliang David Li4a5ddf82017-04-14 17:48:40 +0000177
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000178 if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
179 SectName += ",regular,live_support";
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000180
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000181 return SectName;
Xinliang David Li4a5ddf82017-04-14 17:48:40 +0000182}
183
Vedant Kumar42369db2016-05-11 19:42:19 +0000184void SoftInstrProfErrors::addError(instrprof_error IE) {
185 if (IE == instrprof_error::success)
186 return;
187
188 if (FirstError == instrprof_error::success)
189 FirstError = IE;
190
191 switch (IE) {
192 case instrprof_error::hash_mismatch:
193 ++NumHashMismatches;
194 break;
195 case instrprof_error::count_mismatch:
196 ++NumCountMismatches;
197 break;
198 case instrprof_error::counter_overflow:
199 ++NumCounterOverflows;
200 break;
201 case instrprof_error::value_site_count_mismatch:
202 ++NumValueSiteCountMismatches;
203 break;
204 default:
205 llvm_unreachable("Not a soft error");
206 }
207}
208
Vedant Kumar9152fd12016-05-19 03:54:45 +0000209std::string InstrProfError::message() const {
210 return getInstrProfErrString(Err);
211}
212
213char InstrProfError::ID = 0;
214
Xinliang David Li441959d2015-11-09 00:01:22 +0000215std::string getPGOFuncName(StringRef RawFuncName,
216 GlobalValue::LinkageTypes Linkage,
Xinliang David Lia86545b2015-12-11 20:23:22 +0000217 StringRef FileName,
218 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
Teresa Johnsonb43027d2016-03-15 02:13:19 +0000219 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000220}
221
Rong Xua1a9f702017-02-25 00:00:36 +0000222// Strip NumPrefix level of directory name from PathNameStr. If the number of
223// directory separators is less than NumPrefix, strip all the directories and
224// leave base file name only.
225static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
226 uint32_t Count = NumPrefix;
227 uint32_t Pos = 0, LastPos = 0;
228 for (auto & CI : PathNameStr) {
229 ++Pos;
230 if (llvm::sys::path::is_separator(CI)) {
231 LastPos = Pos;
232 --Count;
233 }
234 if (Count == 0)
235 break;
236 }
237 return PathNameStr.substr(LastPos);
238}
239
Rong Xub5341662016-03-30 18:37:52 +0000240// Return the PGOFuncName. This function has some special handling when called
241// in LTO optimization. The following only applies when calling in LTO passes
242// (when \c InLTO is true): LTO's internalization privatizes many global linkage
243// symbols. This happens after value profile annotation, but those internal
244// linkage functions should not have a source prefix.
Teresa Johnson8c1bc982016-08-29 22:46:56 +0000245// Additionally, for ThinLTO mode, exported internal functions are promoted
246// and renamed. We need to ensure that the original internal PGO name is
247// used when computing the GUID that is compared against the profiled GUIDs.
Rong Xub5341662016-03-30 18:37:52 +0000248// To differentiate compiler generated internal symbols from original ones,
249// PGOFuncName meta data are created and attached to the original internal
250// symbols in the value profile annotation step
251// (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
252// data, its original linkage must be non-internal.
253std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
Xinliang David Li9eb472b2016-07-12 17:14:51 +0000254 if (!InLTO) {
255 StringRef FileName = (StaticFuncFullModulePrefix
256 ? F.getParent()->getName()
257 : sys::path::filename(F.getParent()->getName()));
Rong Xua1a9f702017-02-25 00:00:36 +0000258 if (StaticFuncFullModulePrefix && StaticFuncStripDirNamePrefix != 0)
259 FileName = stripDirPrefix(FileName, StaticFuncStripDirNamePrefix);
Xinliang David Li9eb472b2016-07-12 17:14:51 +0000260 return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
261 }
Rong Xub5341662016-03-30 18:37:52 +0000262
Rong Xu8e8fe852016-04-01 16:43:30 +0000263 // In LTO mode (when InLTO is true), first check if there is a meta data.
264 if (MDNode *MD = getPGOFuncNameMetadata(F)) {
Rong Xub5341662016-03-30 18:37:52 +0000265 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
266 return S.str();
267 }
268
269 // If there is no meta data, the function must be a global before the value
270 // profile annotation pass. Its current linkage may be internal if it is
271 // internalized in LTO mode.
Rong Xu8e8fe852016-04-01 16:43:30 +0000272 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
Xinliang David Li441959d2015-11-09 00:01:22 +0000273}
274
Xinliang David Li4ec40142015-12-15 19:44:45 +0000275StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
276 if (FileName.empty())
Vedant Kumar43a85652016-03-28 15:49:08 +0000277 return PGOFuncName;
Xinliang David Li4ec40142015-12-15 19:44:45 +0000278 // Drop the file name including ':'. See also getPGOFuncName.
279 if (PGOFuncName.startswith(FileName))
280 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
281 return PGOFuncName;
282}
283
Xinliang David Lid1bab962015-12-12 17:28:03 +0000284// \p FuncName is the string used as profile lookup key for the function. A
285// symbol is created to hold the name. Return the legalized symbol name.
Vedant Kumaraa0cae62016-03-16 20:49:26 +0000286std::string getPGOFuncNameVarName(StringRef FuncName,
287 GlobalValue::LinkageTypes Linkage) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000288 std::string VarName = getInstrProfNameVarPrefix();
289 VarName += FuncName;
290
291 if (!GlobalValue::isLocalLinkage(Linkage))
292 return VarName;
293
294 // Now fix up illegal chars in local VarName that may upset the assembler.
Xinliang David Lieeaf0bc2016-06-10 06:32:26 +0000295 const char *InvalidChars = "-:<>/\"'";
Xinliang David Lid1bab962015-12-12 17:28:03 +0000296 size_t found = VarName.find_first_of(InvalidChars);
297 while (found != std::string::npos) {
298 VarName[found] = '_';
299 found = VarName.find_first_of(InvalidChars, found + 1);
300 }
301 return VarName;
302}
303
Xinliang David Li441959d2015-11-09 00:01:22 +0000304GlobalVariable *createPGOFuncNameVar(Module &M,
305 GlobalValue::LinkageTypes Linkage,
Xinliang David Li897d2922016-03-16 22:13:41 +0000306 StringRef PGOFuncName) {
Xinliang David Li441959d2015-11-09 00:01:22 +0000307 // We generally want to match the function's linkage, but available_externally
308 // and extern_weak both have the wrong semantics, and anything that doesn't
309 // need to link across compilation units doesn't need to be visible at all.
310 if (Linkage == GlobalValue::ExternalWeakLinkage)
311 Linkage = GlobalValue::LinkOnceAnyLinkage;
312 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
313 Linkage = GlobalValue::LinkOnceODRLinkage;
314 else if (Linkage == GlobalValue::InternalLinkage ||
315 Linkage == GlobalValue::ExternalLinkage)
316 Linkage = GlobalValue::PrivateLinkage;
317
Xinliang David Li897d2922016-03-16 22:13:41 +0000318 auto *Value =
319 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
Xinliang David Li441959d2015-11-09 00:01:22 +0000320 auto FuncNameVar =
321 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
Xinliang David Li897d2922016-03-16 22:13:41 +0000322 getPGOFuncNameVarName(PGOFuncName, Linkage));
Xinliang David Li441959d2015-11-09 00:01:22 +0000323
324 // Hide the symbol so that we correctly get a copy for each executable.
325 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
326 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
327
328 return FuncNameVar;
329}
330
Xinliang David Li897d2922016-03-16 22:13:41 +0000331GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
332 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000333}
Xinliang David Liee415892015-11-10 00:24:45 +0000334
Vedant Kumarb5794ca2017-06-20 01:38:56 +0000335Error InstrProfSymtab::create(Module &M, bool InLTO) {
Rong Xub5341662016-03-30 18:37:52 +0000336 for (Function &F : M) {
337 // Function may not have a name: like using asm("") to overwrite the name.
338 // Ignore in this case.
339 if (!F.hasName())
340 continue;
341 const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
Vedant Kumarb5794ca2017-06-20 01:38:56 +0000342 if (Error E = addFuncName(PGOFuncName))
343 return E;
Rong Xud5a57b52016-03-31 17:39:33 +0000344 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
Dehao Chen4a435e02017-03-14 17:33:01 +0000345 // In ThinLTO, local function may have been promoted to global and have
346 // suffix added to the function name. We need to add the stripped function
347 // name to the symbol table so that we can find a match from profile.
348 if (InLTO) {
349 auto pos = PGOFuncName.find('.');
350 if (pos != std::string::npos) {
351 const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
Vedant Kumarb5794ca2017-06-20 01:38:56 +0000352 if (Error E = addFuncName(OtherFuncName))
353 return E;
Dehao Chen4a435e02017-03-14 17:33:01 +0000354 MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F);
355 }
356 }
Rong Xub5341662016-03-30 18:37:52 +0000357 }
Xinliang David Li59411db2016-01-20 01:26:34 +0000358
359 finalizeSymtab();
Vedant Kumarb5794ca2017-06-20 01:38:56 +0000360 return Error::success();
Xinliang David Li59411db2016-01-20 01:26:34 +0000361}
362
Benjamin Kramer9d8ed262017-05-28 13:23:02 +0000363Error collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs,
Vedant Kumar9152fd12016-05-19 03:54:45 +0000364 bool doCompression, std::string &Result) {
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000365 assert(!NameStrs.empty() && "No name data to emit");
Vedant Kumar86705ba2016-03-28 21:06:42 +0000366
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000367 uint8_t Header[16], *P = Header;
Xinliang David Li0c677872016-01-04 21:31:09 +0000368 std::string UncompressedNameStrings =
Vedant Kumar86705ba2016-03-28 21:06:42 +0000369 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
370
371 assert(StringRef(UncompressedNameStrings)
372 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
373 "PGO name is invalid (contains separator token)");
Xinliang David Li13ea29b2016-01-04 20:26:05 +0000374
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000375 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
376 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000377
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000378 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000379 EncLen = encodeULEB128(CompressedLen, P);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000380 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000381 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
382 unsigned HeaderLen = P - &Header[0];
383 Result.append(HeaderStr, HeaderLen);
384 Result += InputStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000385 return Error::success();
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000386 };
387
Vedant Kumar9152fd12016-05-19 03:54:45 +0000388 if (!doCompression) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000389 return WriteStringToResult(0, UncompressedNameStrings);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000390 }
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000391
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000392 SmallString<128> CompressedNameStrings;
George Rimar167ca4a2017-01-17 15:45:07 +0000393 Error E = zlib::compress(StringRef(UncompressedNameStrings),
394 CompressedNameStrings, zlib::BestSizeCompression);
395 if (E) {
396 consumeError(std::move(E));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000397 return make_error<InstrProfError>(instrprof_error::compress_failed);
George Rimar167ca4a2017-01-17 15:45:07 +0000398 }
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000399
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000400 return WriteStringToResult(CompressedNameStrings.size(),
401 CompressedNameStrings);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000402}
403
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000404StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
Xinliang David Li37c1fa02016-01-03 04:38:13 +0000405 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
406 StringRef NameStr =
407 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
408 return NameStr;
409}
410
Benjamin Kramer9d8ed262017-05-28 13:23:02 +0000411Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
Vedant Kumar9152fd12016-05-19 03:54:45 +0000412 std::string &Result, bool doCompression) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000413 std::vector<std::string> NameStrs;
414 for (auto *NameVar : NameVars) {
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000415 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000416 }
Xinliang David Li73163752016-01-26 23:13:00 +0000417 return collectPGOFuncNameStrings(
418 NameStrs, zlib::isAvailable() && doCompression, Result);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000419}
420
Vedant Kumar9152fd12016-05-19 03:54:45 +0000421Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000422 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
423 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
424 NameStrings.size());
425 while (P < EndP) {
426 uint32_t N;
427 uint64_t UncompressedSize = decodeULEB128(P, &N);
428 P += N;
429 uint64_t CompressedSize = decodeULEB128(P, &N);
430 P += N;
431 bool isCompressed = (CompressedSize != 0);
432 SmallString<128> UncompressedNameStrings;
433 StringRef NameStrings;
434 if (isCompressed) {
David Blaikieb8cc0542017-07-21 21:41:15 +0000435 if (!llvm::zlib::isAvailable())
436 return make_error<InstrProfError>(instrprof_error::zlib_unavailable);
437
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000438 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
439 CompressedSize);
George Rimar167ca4a2017-01-17 15:45:07 +0000440 if (Error E =
441 zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
442 UncompressedSize)) {
443 consumeError(std::move(E));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000444 return make_error<InstrProfError>(instrprof_error::uncompress_failed);
George Rimar167ca4a2017-01-17 15:45:07 +0000445 }
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000446 P += CompressedSize;
447 NameStrings = StringRef(UncompressedNameStrings.data(),
448 UncompressedNameStrings.size());
449 } else {
450 NameStrings =
451 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
452 P += UncompressedSize;
453 }
454 // Now parse the name strings.
Xinliang David Li204efe22016-01-04 22:09:26 +0000455 SmallVector<StringRef, 0> Names;
Vedant Kumar86705ba2016-03-28 21:06:42 +0000456 NameStrings.split(Names, getInstrProfNameSeparator());
Xinliang David Li204efe22016-01-04 22:09:26 +0000457 for (StringRef &Name : Names)
Vedant Kumarb5794ca2017-06-20 01:38:56 +0000458 if (Error E = Symtab.addFuncName(Name))
459 return E;
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000460
461 while (P < EndP && *P == 0)
462 P++;
463 }
464 Symtab.finalizeSymtab();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000465 return Error::success();
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000466}
467
David Blaikie98cce002017-07-10 03:04:59 +0000468void InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
469 uint64_t Weight,
470 function_ref<void(instrprof_error)> Warn) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000471 this->sortByTargetValues();
472 Input.sortByTargetValues();
473 auto I = ValueData.begin();
474 auto IE = ValueData.end();
Xinliang David Li5c24da52015-12-20 05:15:45 +0000475 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
476 ++J) {
477 while (I != IE && I->Value < J->Value)
478 ++I;
479 if (I != IE && I->Value == J->Value) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000480 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000481 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000482 if (Overflowed)
David Blaikie98cce002017-07-10 03:04:59 +0000483 Warn(instrprof_error::counter_overflow);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000484 ++I;
485 continue;
486 }
487 ValueData.insert(I, *J);
488 }
Xinliang David Li5c24da52015-12-20 05:15:45 +0000489}
490
David Blaikie98cce002017-07-10 03:04:59 +0000491void InstrProfValueSiteRecord::scale(uint64_t Weight,
492 function_ref<void(instrprof_error)> Warn) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000493 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
494 bool Overflowed;
495 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
496 if (Overflowed)
David Blaikie98cce002017-07-10 03:04:59 +0000497 Warn(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000498 }
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000499}
500
Xinliang David Li020f22d2015-12-18 23:06:37 +0000501// Merge Value Profile data from Src record to this record for ValueKind.
502// Scale merged value counts by \p Weight.
David Blaikie98cce002017-07-10 03:04:59 +0000503void InstrProfRecord::mergeValueProfData(
504 uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight,
505 function_ref<void(instrprof_error)> Warn) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000506 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
507 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
Vedant Kumar42369db2016-05-11 19:42:19 +0000508 if (ThisNumValueSites != OtherNumValueSites) {
David Blaikie98cce002017-07-10 03:04:59 +0000509 Warn(instrprof_error::value_site_count_mismatch);
Vedant Kumar42369db2016-05-11 19:42:19 +0000510 return;
511 }
David Blaikied16a61d2017-06-29 02:51:58 +0000512 if (!ThisNumValueSites)
513 return;
Xinliang David Li020f22d2015-12-18 23:06:37 +0000514 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
David Blaikied16a61d2017-06-29 02:51:58 +0000515 getOrCreateValueSitesForKind(ValueKind);
516 MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
Xinliang David Li020f22d2015-12-18 23:06:37 +0000517 Src.getValueSitesForKind(ValueKind);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000518 for (uint32_t I = 0; I < ThisNumValueSites; I++)
David Blaikie98cce002017-07-10 03:04:59 +0000519 ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000520}
521
David Blaikie98cce002017-07-10 03:04:59 +0000522void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight,
523 function_ref<void(instrprof_error)> Warn) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000524 // If the number of counters doesn't match we either have bad data
525 // or a hash collision.
Vedant Kumar42369db2016-05-11 19:42:19 +0000526 if (Counts.size() != Other.Counts.size()) {
David Blaikie98cce002017-07-10 03:04:59 +0000527 Warn(instrprof_error::count_mismatch);
Vedant Kumar42369db2016-05-11 19:42:19 +0000528 return;
529 }
Xinliang David Li020f22d2015-12-18 23:06:37 +0000530
531 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
532 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000533 Counts[I] =
534 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000535 if (Overflowed)
David Blaikie98cce002017-07-10 03:04:59 +0000536 Warn(instrprof_error::counter_overflow);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000537 }
538
539 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
David Blaikie98cce002017-07-10 03:04:59 +0000540 mergeValueProfData(Kind, Other, Weight, Warn);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000541}
Xinliang David Lia716cc52015-12-20 06:22:13 +0000542
David Blaikie98cce002017-07-10 03:04:59 +0000543void InstrProfRecord::scaleValueProfData(
544 uint32_t ValueKind, uint64_t Weight,
545 function_ref<void(instrprof_error)> Warn) {
David Blaikied16a61d2017-06-29 02:51:58 +0000546 for (auto &R : getValueSitesForKind(ValueKind))
David Blaikie98cce002017-07-10 03:04:59 +0000547 R.scale(Weight, Warn);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000548}
549
David Blaikie98cce002017-07-10 03:04:59 +0000550void InstrProfRecord::scale(uint64_t Weight,
551 function_ref<void(instrprof_error)> Warn) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000552 for (auto &Count : this->Counts) {
553 bool Overflowed;
554 Count = SaturatingMultiply(Count, Weight, &Overflowed);
Vedant Kumar42369db2016-05-11 19:42:19 +0000555 if (Overflowed)
David Blaikie98cce002017-07-10 03:04:59 +0000556 Warn(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000557 }
558 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
David Blaikie98cce002017-07-10 03:04:59 +0000559 scaleValueProfData(Kind, Weight, Warn);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000560}
561
Xinliang David Li020f22d2015-12-18 23:06:37 +0000562// Map indirect call target name hash to name string.
563uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000564 ValueMapType *ValueMap) {
565 if (!ValueMap)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000566 return Value;
567 switch (ValueKind) {
568 case IPVK_IndirectCallTarget: {
569 auto Result =
Xinliang David Lia716cc52015-12-20 06:22:13 +0000570 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
571 [](const std::pair<uint64_t, uint64_t> &LHS,
Xinliang David Li020f22d2015-12-18 23:06:37 +0000572 uint64_t RHS) { return LHS.first < RHS; });
Xinliang David Li8dd4ca82016-04-11 17:13:08 +0000573 // Raw function pointer collected by value profiler may be from
574 // external functions that are not instrumented. They won't have
575 // mapping data to be used by the deserializer. Force the value to
576 // be 0 in this case.
Xinliang David Li28464482016-04-10 03:32:02 +0000577 if (Result != ValueMap->end() && Result->first == Value)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000578 Value = (uint64_t)Result->second;
Xinliang David Li28464482016-04-10 03:32:02 +0000579 else
580 Value = 0;
Xinliang David Li020f22d2015-12-18 23:06:37 +0000581 break;
582 }
583 }
584 return Value;
585}
586
Xinliang David Li020f22d2015-12-18 23:06:37 +0000587void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
588 InstrProfValueData *VData, uint32_t N,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000589 ValueMapType *ValueMap) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000590 for (uint32_t I = 0; I < N; I++) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000591 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000592 }
593 std::vector<InstrProfValueSiteRecord> &ValueSites =
David Blaikied16a61d2017-06-29 02:51:58 +0000594 getOrCreateValueSitesForKind(ValueKind);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000595 if (N == 0)
Vedant Kumar6b22ba62016-05-11 16:03:02 +0000596 ValueSites.emplace_back();
Xinliang David Li020f22d2015-12-18 23:06:37 +0000597 else
598 ValueSites.emplace_back(VData, VData + N);
599}
600
Xinliang David Lib75544a2015-11-28 19:07:09 +0000601#define INSTR_PROF_COMMON_API_IMPL
602#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Liee415892015-11-10 00:24:45 +0000603
Xinliang David Li020f22d2015-12-18 23:06:37 +0000604/*!
Xinliang David Lib75544a2015-11-28 19:07:09 +0000605 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
Xinliang David Lied966772015-11-25 23:31:18 +0000606 * class. These C wrappers are used as adaptors so that C++ code can be
607 * invoked as callbacks.
608 */
Xinliang David Lif47cf552015-11-25 06:23:38 +0000609uint32_t getNumValueKindsInstrProf(const void *Record) {
610 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
611}
612
613uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
614 return reinterpret_cast<const InstrProfRecord *>(Record)
615 ->getNumValueSites(VKind);
616}
617
618uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
619 return reinterpret_cast<const InstrProfRecord *>(Record)
620 ->getNumValueData(VKind);
621}
622
623uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
624 uint32_t S) {
625 return reinterpret_cast<const InstrProfRecord *>(R)
626 ->getNumValueDataForSite(VK, S);
627}
628
629void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
Xinliang David Li1e4c8092016-02-04 05:29:51 +0000630 uint32_t K, uint32_t S) {
631 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
Xinliang David Lie8092312015-11-25 19:13:00 +0000632}
633
Xinliang David Lif47cf552015-11-25 06:23:38 +0000634ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
Xinliang David Li38b9a322015-12-15 21:57:08 +0000635 ValueProfData *VD =
636 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
637 memset(VD, 0, TotalSizeInBytes);
638 return VD;
Xinliang David Lif47cf552015-11-25 06:23:38 +0000639}
640
641static ValueProfRecordClosure InstrProfRecordClosure = {
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000642 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000643 getNumValueKindsInstrProf,
644 getNumValueSitesInstrProf,
645 getNumValueDataInstrProf,
646 getNumValueDataForSiteInstrProf,
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000647 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000648 getValueForSiteInstrProf,
Xinliang David Li38b9a322015-12-15 21:57:08 +0000649 allocValueProfDataInstrProf};
Xinliang David Lif47cf552015-11-25 06:23:38 +0000650
Xinliang David Lie8092312015-11-25 19:13:00 +0000651// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000652uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
Xinliang David Lid6f10a62017-06-27 17:21:51 +0000653 auto Closure = InstrProfRecordClosure;
654 Closure.Record = &Record;
655 return getValueProfDataSize(&Closure);
Xinliang David Lif47cf552015-11-25 06:23:38 +0000656}
657
Xinliang David Lie8092312015-11-25 19:13:00 +0000658// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000659std::unique_ptr<ValueProfData>
660ValueProfData::serializeFrom(const InstrProfRecord &Record) {
661 InstrProfRecordClosure.Record = &Record;
662
663 std::unique_ptr<ValueProfData> VPD(
Xinliang David Li0e6a36e2015-12-01 19:47:32 +0000664 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
Xinliang David Lif47cf552015-11-25 06:23:38 +0000665 return VPD;
666}
667
Xinliang David Lie8092312015-11-25 19:13:00 +0000668void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
669 InstrProfRecord::ValueMapType *VMap) {
670 Record.reserveSites(Kind, NumValueSites);
671
672 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
673 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
674 uint8_t ValueDataCount = this->SiteCountArray[VSite];
675 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
676 ValueData += ValueDataCount;
677 }
678}
Xinliang David Lied966772015-11-25 23:31:18 +0000679
Xinliang David Lie8092312015-11-25 19:13:00 +0000680// For writing/serializing, Old is the host endianness, and New is
681// byte order intended on disk. For Reading/deserialization, Old
682// is the on-disk source endianness, and New is the host endianness.
683void ValueProfRecord::swapBytes(support::endianness Old,
684 support::endianness New) {
685 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000686
Xinliang David Lie8092312015-11-25 19:13:00 +0000687 if (Old == New)
688 return;
689
690 if (getHostEndianness() != Old) {
691 sys::swapByteOrder<uint32_t>(NumValueSites);
692 sys::swapByteOrder<uint32_t>(Kind);
693 }
694 uint32_t ND = getValueProfRecordNumValueData(this);
695 InstrProfValueData *VD = getValueProfRecordValueData(this);
696
697 // No need to swap byte array: SiteCountArrray.
698 for (uint32_t I = 0; I < ND; I++) {
699 sys::swapByteOrder<uint64_t>(VD[I].Value);
700 sys::swapByteOrder<uint64_t>(VD[I].Count);
701 }
702 if (getHostEndianness() == Old) {
703 sys::swapByteOrder<uint32_t>(NumValueSites);
704 sys::swapByteOrder<uint32_t>(Kind);
705 }
706}
707
708void ValueProfData::deserializeTo(InstrProfRecord &Record,
709 InstrProfRecord::ValueMapType *VMap) {
710 if (NumValueKinds == 0)
711 return;
712
713 ValueProfRecord *VR = getFirstValueProfRecord(this);
714 for (uint32_t K = 0; K < NumValueKinds; K++) {
715 VR->deserializeTo(Record, VMap);
716 VR = getValueProfRecordNext(VR);
717 }
718}
719
720template <class T>
721static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
722 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000723
Xinliang David Lie8092312015-11-25 19:13:00 +0000724 if (Orig == little)
725 return endian::readNext<T, little, unaligned>(D);
726 else
727 return endian::readNext<T, big, unaligned>(D);
728}
729
730static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
731 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
732 ValueProfData());
733}
734
Vedant Kumar9152fd12016-05-19 03:54:45 +0000735Error ValueProfData::checkIntegrity() {
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000736 if (NumValueKinds > IPVK_Last + 1)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000737 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000738 // Total size needs to be mulltiple of quadword size.
739 if (TotalSize % sizeof(uint64_t))
Vedant Kumar9152fd12016-05-19 03:54:45 +0000740 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000741
742 ValueProfRecord *VR = getFirstValueProfRecord(this);
743 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
744 if (VR->Kind > IPVK_Last)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000745 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000746 VR = getValueProfRecordNext(VR);
747 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000748 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000749 }
Vedant Kumar9152fd12016-05-19 03:54:45 +0000750 return Error::success();
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000751}
752
Vedant Kumar9152fd12016-05-19 03:54:45 +0000753Expected<std::unique_ptr<ValueProfData>>
Xinliang David Liee415892015-11-10 00:24:45 +0000754ValueProfData::getValueProfData(const unsigned char *D,
755 const unsigned char *const BufferEnd,
756 support::endianness Endianness) {
757 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000758
Xinliang David Liee415892015-11-10 00:24:45 +0000759 if (D + sizeof(ValueProfData) > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000760 return make_error<InstrProfError>(instrprof_error::truncated);
Xinliang David Liee415892015-11-10 00:24:45 +0000761
Xinliang David Lib8c3ad12015-11-17 03:47:21 +0000762 const unsigned char *Header = D;
763 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
Xinliang David Liee415892015-11-10 00:24:45 +0000764 if (D + TotalSize > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000765 return make_error<InstrProfError>(instrprof_error::too_large);
Xinliang David Liee415892015-11-10 00:24:45 +0000766
Xinliang David Lif47cf552015-11-25 06:23:38 +0000767 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
Xinliang David Liee415892015-11-10 00:24:45 +0000768 memcpy(VPD.get(), D, TotalSize);
769 // Byte swap.
770 VPD->swapBytesToHost(Endianness);
771
Vedant Kumar9152fd12016-05-19 03:54:45 +0000772 Error E = VPD->checkIntegrity();
773 if (E)
774 return std::move(E);
Xinliang David Liee415892015-11-10 00:24:45 +0000775
Xinliang David Liee415892015-11-10 00:24:45 +0000776 return std::move(VPD);
777}
778
779void ValueProfData::swapBytesToHost(support::endianness Endianness) {
780 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000781
Xinliang David Liee415892015-11-10 00:24:45 +0000782 if (Endianness == getHostEndianness())
783 return;
784
785 sys::swapByteOrder<uint32_t>(TotalSize);
786 sys::swapByteOrder<uint32_t>(NumValueKinds);
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++) {
790 VR->swapBytes(Endianness, getHostEndianness());
Xinliang David Liac5b8602015-11-25 04:29:24 +0000791 VR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000792 }
793}
794
795void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
796 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000797
Xinliang David Liee415892015-11-10 00:24:45 +0000798 if (Endianness == getHostEndianness())
799 return;
800
Xinliang David Lif47cf552015-11-25 06:23:38 +0000801 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000802 for (uint32_t K = 0; K < NumValueKinds; K++) {
Xinliang David Liac5b8602015-11-25 04:29:24 +0000803 ValueProfRecord *NVR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000804 VR->swapBytes(getHostEndianness(), Endianness);
805 VR = NVR;
806 }
807 sys::swapByteOrder<uint32_t>(TotalSize);
808 sys::swapByteOrder<uint32_t>(NumValueKinds);
809}
Xinliang David Lie8092312015-11-25 19:13:00 +0000810
Xinliang David Li402477d2016-02-04 19:11:43 +0000811void annotateValueSite(Module &M, Instruction &Inst,
812 const InstrProfRecord &InstrProfR,
Rong Xu69683f12016-02-10 22:19:43 +0000813 InstrProfValueKind ValueKind, uint32_t SiteIdx,
814 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000815 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
Betul Buyukkurt4f1e8c92016-04-14 16:25:45 +0000816 if (!NV)
817 return;
Xinliang David Li402477d2016-02-04 19:11:43 +0000818
819 uint64_t Sum = 0;
820 std::unique_ptr<InstrProfValueData[]> VD =
821 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
822
Rong Xu311ada12016-03-30 16:56:31 +0000823 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
824 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
Rong Xubb494902016-02-12 21:36:17 +0000825}
826
827void annotateValueSite(Module &M, Instruction &Inst,
Rong Xu311ada12016-03-30 16:56:31 +0000828 ArrayRef<InstrProfValueData> VDs,
Rong Xubb494902016-02-12 21:36:17 +0000829 uint64_t Sum, InstrProfValueKind ValueKind,
830 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000831 LLVMContext &Ctx = M.getContext();
832 MDBuilder MDHelper(Ctx);
833 SmallVector<Metadata *, 3> Vals;
834 // Tag
835 Vals.push_back(MDHelper.createString("VP"));
836 // Value Kind
837 Vals.push_back(MDHelper.createConstant(
838 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
839 // Total Count
840 Vals.push_back(
841 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
842
843 // Value Profile Data
Rong Xu69683f12016-02-10 22:19:43 +0000844 uint32_t MDCount = MaxMDCount;
Rong Xu311ada12016-03-30 16:56:31 +0000845 for (auto &VD : VDs) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000846 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000847 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000848 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000849 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000850 if (--MDCount == 0)
851 break;
852 }
853 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
854}
855
856bool getValueProfDataFromInst(const Instruction &Inst,
857 InstrProfValueKind ValueKind,
858 uint32_t MaxNumValueData,
859 InstrProfValueData ValueData[],
860 uint32_t &ActualNumValueData, uint64_t &TotalC) {
861 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
862 if (!MD)
863 return false;
864
865 unsigned NOps = MD->getNumOperands();
866
867 if (NOps < 5)
868 return false;
869
870 // Operand 0 is a string tag "VP":
871 MDString *Tag = cast<MDString>(MD->getOperand(0));
872 if (!Tag)
873 return false;
874
875 if (!Tag->getString().equals("VP"))
876 return false;
877
878 // Now check kind:
879 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
880 if (!KindInt)
881 return false;
882 if (KindInt->getZExtValue() != ValueKind)
883 return false;
884
885 // Get total count
886 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
887 if (!TotalCInt)
888 return false;
889 TotalC = TotalCInt->getZExtValue();
890
891 ActualNumValueData = 0;
892
893 for (unsigned I = 3; I < NOps; I += 2) {
894 if (ActualNumValueData >= MaxNumValueData)
895 break;
896 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
897 ConstantInt *Count =
898 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
899 if (!Value || !Count)
900 return false;
901 ValueData[ActualNumValueData].Value = Value->getZExtValue();
902 ValueData[ActualNumValueData].Count = Count->getZExtValue();
903 ActualNumValueData++;
904 }
905 return true;
906}
Rong Xu8e8fe852016-04-01 16:43:30 +0000907
Rong Xu92c2eae2016-04-01 20:15:04 +0000908MDNode *getPGOFuncNameMetadata(const Function &F) {
909 return F.getMetadata(getPGOFuncNameMetadataName());
910}
911
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000912void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
Rong Xuf8f051c2016-04-22 21:00:17 +0000913 // Only for internal linkage functions.
914 if (PGOFuncName == F.getName())
915 return;
916 // Don't create duplicated meta-data.
917 if (getPGOFuncNameMetadata(F))
Rong Xu8e8fe852016-04-01 16:43:30 +0000918 return;
Rong Xu8e8fe852016-04-01 16:43:30 +0000919 LLVMContext &C = F.getContext();
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000920 MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
Rong Xu8e8fe852016-04-01 16:43:30 +0000921 F.setMetadata(getPGOFuncNameMetadataName(), N);
922}
923
Rong Xu97b68c52016-07-21 20:50:02 +0000924bool needsComdatForCounter(const Function &F, const Module &M) {
925 if (F.hasComdat())
926 return true;
927
928 Triple TT(M.getTargetTriple());
Dan Gohman1209c7a2017-01-17 20:34:09 +0000929 if (!TT.isOSBinFormatELF() && !TT.isOSBinFormatWasm())
Rong Xu97b68c52016-07-21 20:50:02 +0000930 return false;
931
932 // See createPGOFuncNameVar for more details. To avoid link errors, profile
933 // counters for function with available_externally linkage needs to be changed
934 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
935 // created. Without using comdat, duplicate entries won't be removed by the
936 // linker leading to increased data segement size and raw profile size. Even
937 // worse, since the referenced counter from profile per-function data object
938 // will be resolved to the common strong definition, the profile counts for
939 // available_externally functions will end up being duplicated in raw profile
940 // data. This can result in distorted profile as the counts of those dups
941 // will be accumulated by the profile merger.
942 GlobalValue::LinkageTypes Linkage = F.getLinkage();
943 if (Linkage != GlobalValue::ExternalWeakLinkage &&
944 Linkage != GlobalValue::AvailableExternallyLinkage)
945 return false;
946
947 return true;
948}
Rong Xu20f5df12017-01-11 20:19:41 +0000949
950// Check if INSTR_PROF_RAW_VERSION_VAR is defined.
951bool isIRPGOFlagSet(const Module *M) {
952 auto IRInstrVar =
953 M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
954 if (!IRInstrVar || IRInstrVar->isDeclaration() ||
955 IRInstrVar->hasLocalLinkage())
956 return false;
957
958 // Check if the flag is set.
959 if (!IRInstrVar->hasInitializer())
960 return false;
961
962 const Constant *InitVal = IRInstrVar->getInitializer();
963 if (!InitVal)
964 return false;
965
966 return (dyn_cast<ConstantInt>(InitVal)->getZExtValue() &
967 VARIANT_MASK_IR_PROF) != 0;
968}
969
970// Check if we can safely rename this Comdat function.
971bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
972 if (F.getName().empty())
973 return false;
974 if (!needsComdatForCounter(F, *(F.getParent())))
975 return false;
976 // Unsafe to rename the address-taken function (which can be used in
977 // function comparison).
978 if (CheckAddressTaken && F.hasAddressTaken())
979 return false;
980 // Only safe to do if this function may be discarded if it is not used
981 // in the compilation unit.
982 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
983 return false;
984
985 // For AvailableExternallyLinkage functions.
986 if (!F.hasComdat()) {
987 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
988 return true;
989 }
990 return true;
991}
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000992
Rong Xu48596b62017-04-04 16:42:20 +0000993// Parse the value profile options.
Benjamin Kramer9d8ed262017-05-28 13:23:02 +0000994void getMemOPSizeRangeFromOption(StringRef MemOPSizeRange, int64_t &RangeStart,
995 int64_t &RangeLast) {
Rong Xu48596b62017-04-04 16:42:20 +0000996 static const int64_t DefaultMemOPSizeRangeStart = 0;
997 static const int64_t DefaultMemOPSizeRangeLast = 8;
998 RangeStart = DefaultMemOPSizeRangeStart;
999 RangeLast = DefaultMemOPSizeRangeLast;
1000
1001 if (!MemOPSizeRange.empty()) {
Benjamin Kramer9d8ed262017-05-28 13:23:02 +00001002 auto Pos = MemOPSizeRange.find(':');
Rong Xu48596b62017-04-04 16:42:20 +00001003 if (Pos != std::string::npos) {
1004 if (Pos > 0)
Benjamin Kramer9d8ed262017-05-28 13:23:02 +00001005 MemOPSizeRange.substr(0, Pos).getAsInteger(10, RangeStart);
Rong Xu48596b62017-04-04 16:42:20 +00001006 if (Pos < MemOPSizeRange.size() - 1)
Benjamin Kramer9d8ed262017-05-28 13:23:02 +00001007 MemOPSizeRange.substr(Pos + 1).getAsInteger(10, RangeLast);
Rong Xu48596b62017-04-04 16:42:20 +00001008 } else
Benjamin Kramer9d8ed262017-05-28 13:23:02 +00001009 MemOPSizeRange.getAsInteger(10, RangeLast);
Rong Xu48596b62017-04-04 16:42:20 +00001010 }
1011 assert(RangeLast >= RangeStart);
1012}
1013
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001014} // end namespace llvm