1 //===- InstrProf.cpp - Instrumented profiling format support --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for clang's instrumentation based PGO and
10 // coverage.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ProfileData/InstrProf.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Config/config.h"
22 #include "llvm/IR/Constant.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Instruction.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/MDBuilder.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/ProfileData/InstrProfReader.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Compression.h"
38 #include "llvm/Support/Endian.h"
39 #include "llvm/Support/Error.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/LEB128.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/SwapByteOrder.h"
45 #include <algorithm>
46 #include <cassert>
47 #include <cstddef>
48 #include <cstdint>
49 #include <cstring>
50 #include <memory>
51 #include <string>
52 #include <system_error>
53 #include <type_traits>
54 #include <utility>
55 #include <vector>
56
57 using namespace llvm;
58
59 static cl::opt<bool> StaticFuncFullModulePrefix(
60 "static-func-full-module-prefix", cl::init(true), cl::Hidden,
61 cl::desc("Use full module build paths in the profile counter names for "
62 "static functions."));
63
64 // This option is tailored to users that have different top-level directory in
65 // profile-gen and profile-use compilation. Users need to specific the number
66 // of levels to strip. A value larger than the number of directories in the
67 // source file will strip all the directory names and only leave the basename.
68 //
69 // Note current ThinLTO module importing for the indirect-calls assumes
70 // the source directory name not being stripped. A non-zero option value here
71 // can potentially prevent some inter-module indirect-call-promotions.
72 static cl::opt<unsigned> StaticFuncStripDirNamePrefix(
73 "static-func-strip-dirname-prefix", cl::init(0), cl::Hidden,
74 cl::desc("Strip specified level of directory name from source path in "
75 "the profile counter name for static functions."));
76
getInstrProfErrString(instrprof_error Err,const std::string & ErrMsg="")77 static std::string getInstrProfErrString(instrprof_error Err,
78 const std::string &ErrMsg = "") {
79 std::string Msg;
80 raw_string_ostream OS(Msg);
81
82 switch (Err) {
83 case instrprof_error::success:
84 OS << "success";
85 break;
86 case instrprof_error::eof:
87 OS << "end of File";
88 break;
89 case instrprof_error::unrecognized_format:
90 OS << "unrecognized instrumentation profile encoding format";
91 break;
92 case instrprof_error::bad_magic:
93 OS << "invalid instrumentation profile data (bad magic)";
94 break;
95 case instrprof_error::bad_header:
96 OS << "invalid instrumentation profile data (file header is corrupt)";
97 break;
98 case instrprof_error::unsupported_version:
99 OS << "unsupported instrumentation profile format version";
100 break;
101 case instrprof_error::unsupported_hash_type:
102 OS << "unsupported instrumentation profile hash type";
103 break;
104 case instrprof_error::too_large:
105 OS << "too much profile data";
106 break;
107 case instrprof_error::truncated:
108 OS << "truncated profile data";
109 break;
110 case instrprof_error::malformed:
111 OS << "malformed instrumentation profile data";
112 break;
113 case instrprof_error::missing_debug_info_for_correlation:
114 OS << "debug info for correlation is required";
115 break;
116 case instrprof_error::unexpected_debug_info_for_correlation:
117 OS << "debug info for correlation is not necessary";
118 break;
119 case instrprof_error::unable_to_correlate_profile:
120 OS << "unable to correlate profile";
121 break;
122 case instrprof_error::invalid_prof:
123 OS << "invalid profile created. Please file a bug "
124 "at: " BUG_REPORT_URL
125 " and include the profraw files that caused this error.";
126 break;
127 case instrprof_error::unknown_function:
128 OS << "no profile data available for function";
129 break;
130 case instrprof_error::hash_mismatch:
131 OS << "function control flow change detected (hash mismatch)";
132 break;
133 case instrprof_error::count_mismatch:
134 OS << "function basic block count change detected (counter mismatch)";
135 break;
136 case instrprof_error::counter_overflow:
137 OS << "counter overflow";
138 break;
139 case instrprof_error::value_site_count_mismatch:
140 OS << "function value site count change detected (counter mismatch)";
141 break;
142 case instrprof_error::compress_failed:
143 OS << "failed to compress data (zlib)";
144 break;
145 case instrprof_error::uncompress_failed:
146 OS << "failed to uncompress data (zlib)";
147 break;
148 case instrprof_error::empty_raw_profile:
149 OS << "empty raw profile file";
150 break;
151 case instrprof_error::zlib_unavailable:
152 OS << "profile uses zlib compression but the profile reader was built "
153 "without zlib support";
154 break;
155 }
156
157 // If optional error message is not empty, append it to the message.
158 if (!ErrMsg.empty())
159 OS << ": " << ErrMsg;
160
161 return OS.str();
162 }
163
164 namespace {
165
166 // FIXME: This class is only here to support the transition to llvm::Error. It
167 // will be removed once this transition is complete. Clients should prefer to
168 // deal with the Error value directly, rather than converting to error_code.
169 class InstrProfErrorCategoryType : public std::error_category {
name() const170 const char *name() const noexcept override { return "llvm.instrprof"; }
171
message(int IE) const172 std::string message(int IE) const override {
173 return getInstrProfErrString(static_cast<instrprof_error>(IE));
174 }
175 };
176
177 } // end anonymous namespace
178
instrprof_category()179 const std::error_category &llvm::instrprof_category() {
180 static InstrProfErrorCategoryType ErrorCategory;
181 return ErrorCategory;
182 }
183
184 namespace {
185
186 const char *InstrProfSectNameCommon[] = {
187 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
188 SectNameCommon,
189 #include "llvm/ProfileData/InstrProfData.inc"
190 };
191
192 const char *InstrProfSectNameCoff[] = {
193 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
194 SectNameCoff,
195 #include "llvm/ProfileData/InstrProfData.inc"
196 };
197
198 const char *InstrProfSectNamePrefix[] = {
199 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
200 Prefix,
201 #include "llvm/ProfileData/InstrProfData.inc"
202 };
203
204 } // namespace
205
206 namespace llvm {
207
208 cl::opt<bool> DoInstrProfNameCompression(
209 "enable-name-compression",
210 cl::desc("Enable name/filename string compression"), cl::init(true));
211
getInstrProfSectionName(InstrProfSectKind IPSK,Triple::ObjectFormatType OF,bool AddSegmentInfo)212 std::string getInstrProfSectionName(InstrProfSectKind IPSK,
213 Triple::ObjectFormatType OF,
214 bool AddSegmentInfo) {
215 std::string SectName;
216
217 if (OF == Triple::MachO && AddSegmentInfo)
218 SectName = InstrProfSectNamePrefix[IPSK];
219
220 if (OF == Triple::COFF)
221 SectName += InstrProfSectNameCoff[IPSK];
222 else
223 SectName += InstrProfSectNameCommon[IPSK];
224
225 if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
226 SectName += ",regular,live_support";
227
228 return SectName;
229 }
230
addError(instrprof_error IE)231 void SoftInstrProfErrors::addError(instrprof_error IE) {
232 if (IE == instrprof_error::success)
233 return;
234
235 if (FirstError == instrprof_error::success)
236 FirstError = IE;
237
238 switch (IE) {
239 case instrprof_error::hash_mismatch:
240 ++NumHashMismatches;
241 break;
242 case instrprof_error::count_mismatch:
243 ++NumCountMismatches;
244 break;
245 case instrprof_error::counter_overflow:
246 ++NumCounterOverflows;
247 break;
248 case instrprof_error::value_site_count_mismatch:
249 ++NumValueSiteCountMismatches;
250 break;
251 default:
252 llvm_unreachable("Not a soft error");
253 }
254 }
255
message() const256 std::string InstrProfError::message() const {
257 return getInstrProfErrString(Err, Msg);
258 }
259
260 char InstrProfError::ID = 0;
261
getPGOFuncName(StringRef RawFuncName,GlobalValue::LinkageTypes Linkage,StringRef FileName,uint64_t Version LLVM_ATTRIBUTE_UNUSED)262 std::string getPGOFuncName(StringRef RawFuncName,
263 GlobalValue::LinkageTypes Linkage,
264 StringRef FileName,
265 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
266 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
267 }
268
269 // Strip NumPrefix level of directory name from PathNameStr. If the number of
270 // directory separators is less than NumPrefix, strip all the directories and
271 // leave base file name only.
stripDirPrefix(StringRef PathNameStr,uint32_t NumPrefix)272 static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
273 uint32_t Count = NumPrefix;
274 uint32_t Pos = 0, LastPos = 0;
275 for (auto & CI : PathNameStr) {
276 ++Pos;
277 if (llvm::sys::path::is_separator(CI)) {
278 LastPos = Pos;
279 --Count;
280 }
281 if (Count == 0)
282 break;
283 }
284 return PathNameStr.substr(LastPos);
285 }
286
287 // Return the PGOFuncName. This function has some special handling when called
288 // in LTO optimization. The following only applies when calling in LTO passes
289 // (when \c InLTO is true): LTO's internalization privatizes many global linkage
290 // symbols. This happens after value profile annotation, but those internal
291 // linkage functions should not have a source prefix.
292 // Additionally, for ThinLTO mode, exported internal functions are promoted
293 // and renamed. We need to ensure that the original internal PGO name is
294 // used when computing the GUID that is compared against the profiled GUIDs.
295 // To differentiate compiler generated internal symbols from original ones,
296 // PGOFuncName meta data are created and attached to the original internal
297 // symbols in the value profile annotation step
298 // (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
299 // data, its original linkage must be non-internal.
getPGOFuncName(const Function & F,bool InLTO,uint64_t Version)300 std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
301 if (!InLTO) {
302 StringRef FileName(F.getParent()->getSourceFileName());
303 uint32_t StripLevel = StaticFuncFullModulePrefix ? 0 : (uint32_t)-1;
304 if (StripLevel < StaticFuncStripDirNamePrefix)
305 StripLevel = StaticFuncStripDirNamePrefix;
306 if (StripLevel)
307 FileName = stripDirPrefix(FileName, StripLevel);
308 return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
309 }
310
311 // In LTO mode (when InLTO is true), first check if there is a meta data.
312 if (MDNode *MD = getPGOFuncNameMetadata(F)) {
313 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
314 return S.str();
315 }
316
317 // If there is no meta data, the function must be a global before the value
318 // profile annotation pass. Its current linkage may be internal if it is
319 // internalized in LTO mode.
320 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
321 }
322
getFuncNameWithoutPrefix(StringRef PGOFuncName,StringRef FileName)323 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
324 if (FileName.empty())
325 return PGOFuncName;
326 // Drop the file name including ':'. See also getPGOFuncName.
327 if (PGOFuncName.startswith(FileName))
328 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
329 return PGOFuncName;
330 }
331
332 // \p FuncName is the string used as profile lookup key for the function. A
333 // symbol is created to hold the name. Return the legalized symbol name.
getPGOFuncNameVarName(StringRef FuncName,GlobalValue::LinkageTypes Linkage)334 std::string getPGOFuncNameVarName(StringRef FuncName,
335 GlobalValue::LinkageTypes Linkage) {
336 std::string VarName = std::string(getInstrProfNameVarPrefix());
337 VarName += FuncName;
338
339 if (!GlobalValue::isLocalLinkage(Linkage))
340 return VarName;
341
342 // Now fix up illegal chars in local VarName that may upset the assembler.
343 const char *InvalidChars = "-:<>/\"'";
344 size_t found = VarName.find_first_of(InvalidChars);
345 while (found != std::string::npos) {
346 VarName[found] = '_';
347 found = VarName.find_first_of(InvalidChars, found + 1);
348 }
349 return VarName;
350 }
351
createPGOFuncNameVar(Module & M,GlobalValue::LinkageTypes Linkage,StringRef PGOFuncName)352 GlobalVariable *createPGOFuncNameVar(Module &M,
353 GlobalValue::LinkageTypes Linkage,
354 StringRef PGOFuncName) {
355 // We generally want to match the function's linkage, but available_externally
356 // and extern_weak both have the wrong semantics, and anything that doesn't
357 // need to link across compilation units doesn't need to be visible at all.
358 if (Linkage == GlobalValue::ExternalWeakLinkage)
359 Linkage = GlobalValue::LinkOnceAnyLinkage;
360 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
361 Linkage = GlobalValue::LinkOnceODRLinkage;
362 else if (Linkage == GlobalValue::InternalLinkage ||
363 Linkage == GlobalValue::ExternalLinkage)
364 Linkage = GlobalValue::PrivateLinkage;
365
366 auto *Value =
367 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
368 auto FuncNameVar =
369 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
370 getPGOFuncNameVarName(PGOFuncName, Linkage));
371
372 // Hide the symbol so that we correctly get a copy for each executable.
373 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
374 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
375
376 return FuncNameVar;
377 }
378
createPGOFuncNameVar(Function & F,StringRef PGOFuncName)379 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
380 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
381 }
382
create(Module & M,bool InLTO)383 Error InstrProfSymtab::create(Module &M, bool InLTO) {
384 for (Function &F : M) {
385 // Function may not have a name: like using asm("") to overwrite the name.
386 // Ignore in this case.
387 if (!F.hasName())
388 continue;
389 const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
390 if (Error E = addFuncName(PGOFuncName))
391 return E;
392 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
393 // In ThinLTO, local function may have been promoted to global and have
394 // suffix ".llvm." added to the function name. We need to add the
395 // stripped function name to the symbol table so that we can find a match
396 // from profile.
397 //
398 // We may have other suffixes similar as ".llvm." which are needed to
399 // be stripped before the matching, but ".__uniq." suffix which is used
400 // to differentiate internal linkage functions in different modules
401 // should be kept. Now this is the only suffix with the pattern ".xxx"
402 // which is kept before matching.
403 const std::string UniqSuffix = ".__uniq.";
404 auto pos = PGOFuncName.find(UniqSuffix);
405 // Search '.' after ".__uniq." if ".__uniq." exists, otherwise
406 // search '.' from the beginning.
407 if (pos != std::string::npos)
408 pos += UniqSuffix.length();
409 else
410 pos = 0;
411 pos = PGOFuncName.find('.', pos);
412 if (pos != std::string::npos && pos != 0) {
413 const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
414 if (Error E = addFuncName(OtherFuncName))
415 return E;
416 MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F);
417 }
418 }
419 Sorted = false;
420 finalizeSymtab();
421 return Error::success();
422 }
423
getFunctionHashFromAddress(uint64_t Address)424 uint64_t InstrProfSymtab::getFunctionHashFromAddress(uint64_t Address) {
425 finalizeSymtab();
426 auto It = partition_point(AddrToMD5Map, [=](std::pair<uint64_t, uint64_t> A) {
427 return A.first < Address;
428 });
429 // Raw function pointer collected by value profiler may be from
430 // external functions that are not instrumented. They won't have
431 // mapping data to be used by the deserializer. Force the value to
432 // be 0 in this case.
433 if (It != AddrToMD5Map.end() && It->first == Address)
434 return (uint64_t)It->second;
435 return 0;
436 }
437
collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs,bool doCompression,std::string & Result)438 Error collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs,
439 bool doCompression, std::string &Result) {
440 assert(!NameStrs.empty() && "No name data to emit");
441
442 uint8_t Header[16], *P = Header;
443 std::string UncompressedNameStrings =
444 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
445
446 assert(StringRef(UncompressedNameStrings)
447 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
448 "PGO name is invalid (contains separator token)");
449
450 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
451 P += EncLen;
452
453 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
454 EncLen = encodeULEB128(CompressedLen, P);
455 P += EncLen;
456 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
457 unsigned HeaderLen = P - &Header[0];
458 Result.append(HeaderStr, HeaderLen);
459 Result += InputStr;
460 return Error::success();
461 };
462
463 if (!doCompression) {
464 return WriteStringToResult(0, UncompressedNameStrings);
465 }
466
467 SmallVector<uint8_t, 128> CompressedNameStrings;
468 compression::zlib::compress(arrayRefFromStringRef(UncompressedNameStrings),
469 CompressedNameStrings,
470 compression::zlib::BestSizeCompression);
471
472 return WriteStringToResult(CompressedNameStrings.size(),
473 toStringRef(CompressedNameStrings));
474 }
475
getPGOFuncNameVarInitializer(GlobalVariable * NameVar)476 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
477 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
478 StringRef NameStr =
479 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
480 return NameStr;
481 }
482
collectPGOFuncNameStrings(ArrayRef<GlobalVariable * > NameVars,std::string & Result,bool doCompression)483 Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
484 std::string &Result, bool doCompression) {
485 std::vector<std::string> NameStrs;
486 for (auto *NameVar : NameVars) {
487 NameStrs.push_back(std::string(getPGOFuncNameVarInitializer(NameVar)));
488 }
489 return collectPGOFuncNameStrings(
490 NameStrs, compression::zlib::isAvailable() && doCompression, Result);
491 }
492
readPGOFuncNameStrings(StringRef NameStrings,InstrProfSymtab & Symtab)493 Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
494 const uint8_t *P = NameStrings.bytes_begin();
495 const uint8_t *EndP = NameStrings.bytes_end();
496 while (P < EndP) {
497 uint32_t N;
498 uint64_t UncompressedSize = decodeULEB128(P, &N);
499 P += N;
500 uint64_t CompressedSize = decodeULEB128(P, &N);
501 P += N;
502 bool isCompressed = (CompressedSize != 0);
503 SmallVector<uint8_t, 128> UncompressedNameStrings;
504 StringRef NameStrings;
505 if (isCompressed) {
506 if (!llvm::compression::zlib::isAvailable())
507 return make_error<InstrProfError>(instrprof_error::zlib_unavailable);
508
509 if (Error E = compression::zlib::uncompress(
510 makeArrayRef(P, CompressedSize), UncompressedNameStrings,
511 UncompressedSize)) {
512 consumeError(std::move(E));
513 return make_error<InstrProfError>(instrprof_error::uncompress_failed);
514 }
515 P += CompressedSize;
516 NameStrings = toStringRef(UncompressedNameStrings);
517 } else {
518 NameStrings =
519 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
520 P += UncompressedSize;
521 }
522 // Now parse the name strings.
523 SmallVector<StringRef, 0> Names;
524 NameStrings.split(Names, getInstrProfNameSeparator());
525 for (StringRef &Name : Names)
526 if (Error E = Symtab.addFuncName(Name))
527 return E;
528
529 while (P < EndP && *P == 0)
530 P++;
531 }
532 return Error::success();
533 }
534
accumulateCounts(CountSumOrPercent & Sum) const535 void InstrProfRecord::accumulateCounts(CountSumOrPercent &Sum) const {
536 uint64_t FuncSum = 0;
537 Sum.NumEntries += Counts.size();
538 for (uint64_t Count : Counts)
539 FuncSum += Count;
540 Sum.CountSum += FuncSum;
541
542 for (uint32_t VK = IPVK_First; VK <= IPVK_Last; ++VK) {
543 uint64_t KindSum = 0;
544 uint32_t NumValueSites = getNumValueSites(VK);
545 for (size_t I = 0; I < NumValueSites; ++I) {
546 uint32_t NV = getNumValueDataForSite(VK, I);
547 std::unique_ptr<InstrProfValueData[]> VD = getValueForSite(VK, I);
548 for (uint32_t V = 0; V < NV; V++)
549 KindSum += VD[V].Count;
550 }
551 Sum.ValueCounts[VK] += KindSum;
552 }
553 }
554
overlap(InstrProfValueSiteRecord & Input,uint32_t ValueKind,OverlapStats & Overlap,OverlapStats & FuncLevelOverlap)555 void InstrProfValueSiteRecord::overlap(InstrProfValueSiteRecord &Input,
556 uint32_t ValueKind,
557 OverlapStats &Overlap,
558 OverlapStats &FuncLevelOverlap) {
559 this->sortByTargetValues();
560 Input.sortByTargetValues();
561 double Score = 0.0f, FuncLevelScore = 0.0f;
562 auto I = ValueData.begin();
563 auto IE = ValueData.end();
564 auto J = Input.ValueData.begin();
565 auto JE = Input.ValueData.end();
566 while (I != IE && J != JE) {
567 if (I->Value == J->Value) {
568 Score += OverlapStats::score(I->Count, J->Count,
569 Overlap.Base.ValueCounts[ValueKind],
570 Overlap.Test.ValueCounts[ValueKind]);
571 FuncLevelScore += OverlapStats::score(
572 I->Count, J->Count, FuncLevelOverlap.Base.ValueCounts[ValueKind],
573 FuncLevelOverlap.Test.ValueCounts[ValueKind]);
574 ++I;
575 } else if (I->Value < J->Value) {
576 ++I;
577 continue;
578 }
579 ++J;
580 }
581 Overlap.Overlap.ValueCounts[ValueKind] += Score;
582 FuncLevelOverlap.Overlap.ValueCounts[ValueKind] += FuncLevelScore;
583 }
584
585 // Return false on mismatch.
overlapValueProfData(uint32_t ValueKind,InstrProfRecord & Other,OverlapStats & Overlap,OverlapStats & FuncLevelOverlap)586 void InstrProfRecord::overlapValueProfData(uint32_t ValueKind,
587 InstrProfRecord &Other,
588 OverlapStats &Overlap,
589 OverlapStats &FuncLevelOverlap) {
590 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
591 assert(ThisNumValueSites == Other.getNumValueSites(ValueKind));
592 if (!ThisNumValueSites)
593 return;
594
595 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
596 getOrCreateValueSitesForKind(ValueKind);
597 MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
598 Other.getValueSitesForKind(ValueKind);
599 for (uint32_t I = 0; I < ThisNumValueSites; I++)
600 ThisSiteRecords[I].overlap(OtherSiteRecords[I], ValueKind, Overlap,
601 FuncLevelOverlap);
602 }
603
overlap(InstrProfRecord & Other,OverlapStats & Overlap,OverlapStats & FuncLevelOverlap,uint64_t ValueCutoff)604 void InstrProfRecord::overlap(InstrProfRecord &Other, OverlapStats &Overlap,
605 OverlapStats &FuncLevelOverlap,
606 uint64_t ValueCutoff) {
607 // FuncLevel CountSum for other should already computed and nonzero.
608 assert(FuncLevelOverlap.Test.CountSum >= 1.0f);
609 accumulateCounts(FuncLevelOverlap.Base);
610 bool Mismatch = (Counts.size() != Other.Counts.size());
611
612 // Check if the value profiles mismatch.
613 if (!Mismatch) {
614 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
615 uint32_t ThisNumValueSites = getNumValueSites(Kind);
616 uint32_t OtherNumValueSites = Other.getNumValueSites(Kind);
617 if (ThisNumValueSites != OtherNumValueSites) {
618 Mismatch = true;
619 break;
620 }
621 }
622 }
623 if (Mismatch) {
624 Overlap.addOneMismatch(FuncLevelOverlap.Test);
625 return;
626 }
627
628 // Compute overlap for value counts.
629 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
630 overlapValueProfData(Kind, Other, Overlap, FuncLevelOverlap);
631
632 double Score = 0.0;
633 uint64_t MaxCount = 0;
634 // Compute overlap for edge counts.
635 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
636 Score += OverlapStats::score(Counts[I], Other.Counts[I],
637 Overlap.Base.CountSum, Overlap.Test.CountSum);
638 MaxCount = std::max(Other.Counts[I], MaxCount);
639 }
640 Overlap.Overlap.CountSum += Score;
641 Overlap.Overlap.NumEntries += 1;
642
643 if (MaxCount >= ValueCutoff) {
644 double FuncScore = 0.0;
645 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I)
646 FuncScore += OverlapStats::score(Counts[I], Other.Counts[I],
647 FuncLevelOverlap.Base.CountSum,
648 FuncLevelOverlap.Test.CountSum);
649 FuncLevelOverlap.Overlap.CountSum = FuncScore;
650 FuncLevelOverlap.Overlap.NumEntries = Other.Counts.size();
651 FuncLevelOverlap.Valid = true;
652 }
653 }
654
merge(InstrProfValueSiteRecord & Input,uint64_t Weight,function_ref<void (instrprof_error)> Warn)655 void InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
656 uint64_t Weight,
657 function_ref<void(instrprof_error)> Warn) {
658 this->sortByTargetValues();
659 Input.sortByTargetValues();
660 auto I = ValueData.begin();
661 auto IE = ValueData.end();
662 for (const InstrProfValueData &J : Input.ValueData) {
663 while (I != IE && I->Value < J.Value)
664 ++I;
665 if (I != IE && I->Value == J.Value) {
666 bool Overflowed;
667 I->Count = SaturatingMultiplyAdd(J.Count, Weight, I->Count, &Overflowed);
668 if (Overflowed)
669 Warn(instrprof_error::counter_overflow);
670 ++I;
671 continue;
672 }
673 ValueData.insert(I, J);
674 }
675 }
676
scale(uint64_t N,uint64_t D,function_ref<void (instrprof_error)> Warn)677 void InstrProfValueSiteRecord::scale(uint64_t N, uint64_t D,
678 function_ref<void(instrprof_error)> Warn) {
679 for (InstrProfValueData &I : ValueData) {
680 bool Overflowed;
681 I.Count = SaturatingMultiply(I.Count, N, &Overflowed) / D;
682 if (Overflowed)
683 Warn(instrprof_error::counter_overflow);
684 }
685 }
686
687 // Merge Value Profile data from Src record to this record for ValueKind.
688 // Scale merged value counts by \p Weight.
mergeValueProfData(uint32_t ValueKind,InstrProfRecord & Src,uint64_t Weight,function_ref<void (instrprof_error)> Warn)689 void InstrProfRecord::mergeValueProfData(
690 uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight,
691 function_ref<void(instrprof_error)> Warn) {
692 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
693 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
694 if (ThisNumValueSites != OtherNumValueSites) {
695 Warn(instrprof_error::value_site_count_mismatch);
696 return;
697 }
698 if (!ThisNumValueSites)
699 return;
700 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
701 getOrCreateValueSitesForKind(ValueKind);
702 MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
703 Src.getValueSitesForKind(ValueKind);
704 for (uint32_t I = 0; I < ThisNumValueSites; I++)
705 ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn);
706 }
707
merge(InstrProfRecord & Other,uint64_t Weight,function_ref<void (instrprof_error)> Warn)708 void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight,
709 function_ref<void(instrprof_error)> Warn) {
710 // If the number of counters doesn't match we either have bad data
711 // or a hash collision.
712 if (Counts.size() != Other.Counts.size()) {
713 Warn(instrprof_error::count_mismatch);
714 return;
715 }
716
717 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
718 bool Overflowed;
719 Counts[I] =
720 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
721 if (Overflowed)
722 Warn(instrprof_error::counter_overflow);
723 }
724
725 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
726 mergeValueProfData(Kind, Other, Weight, Warn);
727 }
728
scaleValueProfData(uint32_t ValueKind,uint64_t N,uint64_t D,function_ref<void (instrprof_error)> Warn)729 void InstrProfRecord::scaleValueProfData(
730 uint32_t ValueKind, uint64_t N, uint64_t D,
731 function_ref<void(instrprof_error)> Warn) {
732 for (auto &R : getValueSitesForKind(ValueKind))
733 R.scale(N, D, Warn);
734 }
735
scale(uint64_t N,uint64_t D,function_ref<void (instrprof_error)> Warn)736 void InstrProfRecord::scale(uint64_t N, uint64_t D,
737 function_ref<void(instrprof_error)> Warn) {
738 assert(D != 0 && "D cannot be 0");
739 for (auto &Count : this->Counts) {
740 bool Overflowed;
741 Count = SaturatingMultiply(Count, N, &Overflowed) / D;
742 if (Overflowed)
743 Warn(instrprof_error::counter_overflow);
744 }
745 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
746 scaleValueProfData(Kind, N, D, Warn);
747 }
748
749 // Map indirect call target name hash to name string.
remapValue(uint64_t Value,uint32_t ValueKind,InstrProfSymtab * SymTab)750 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
751 InstrProfSymtab *SymTab) {
752 if (!SymTab)
753 return Value;
754
755 if (ValueKind == IPVK_IndirectCallTarget)
756 return SymTab->getFunctionHashFromAddress(Value);
757
758 return Value;
759 }
760
addValueData(uint32_t ValueKind,uint32_t Site,InstrProfValueData * VData,uint32_t N,InstrProfSymtab * ValueMap)761 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
762 InstrProfValueData *VData, uint32_t N,
763 InstrProfSymtab *ValueMap) {
764 for (uint32_t I = 0; I < N; I++) {
765 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
766 }
767 std::vector<InstrProfValueSiteRecord> &ValueSites =
768 getOrCreateValueSitesForKind(ValueKind);
769 if (N == 0)
770 ValueSites.emplace_back();
771 else
772 ValueSites.emplace_back(VData, VData + N);
773 }
774
775 #define INSTR_PROF_COMMON_API_IMPL
776 #include "llvm/ProfileData/InstrProfData.inc"
777
778 /*!
779 * ValueProfRecordClosure Interface implementation for InstrProfRecord
780 * class. These C wrappers are used as adaptors so that C++ code can be
781 * invoked as callbacks.
782 */
getNumValueKindsInstrProf(const void * Record)783 uint32_t getNumValueKindsInstrProf(const void *Record) {
784 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
785 }
786
getNumValueSitesInstrProf(const void * Record,uint32_t VKind)787 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
788 return reinterpret_cast<const InstrProfRecord *>(Record)
789 ->getNumValueSites(VKind);
790 }
791
getNumValueDataInstrProf(const void * Record,uint32_t VKind)792 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
793 return reinterpret_cast<const InstrProfRecord *>(Record)
794 ->getNumValueData(VKind);
795 }
796
getNumValueDataForSiteInstrProf(const void * R,uint32_t VK,uint32_t S)797 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
798 uint32_t S) {
799 return reinterpret_cast<const InstrProfRecord *>(R)
800 ->getNumValueDataForSite(VK, S);
801 }
802
getValueForSiteInstrProf(const void * R,InstrProfValueData * Dst,uint32_t K,uint32_t S)803 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
804 uint32_t K, uint32_t S) {
805 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
806 }
807
allocValueProfDataInstrProf(size_t TotalSizeInBytes)808 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
809 ValueProfData *VD =
810 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
811 memset(VD, 0, TotalSizeInBytes);
812 return VD;
813 }
814
815 static ValueProfRecordClosure InstrProfRecordClosure = {
816 nullptr,
817 getNumValueKindsInstrProf,
818 getNumValueSitesInstrProf,
819 getNumValueDataInstrProf,
820 getNumValueDataForSiteInstrProf,
821 nullptr,
822 getValueForSiteInstrProf,
823 allocValueProfDataInstrProf};
824
825 // Wrapper implementation using the closure mechanism.
getSize(const InstrProfRecord & Record)826 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
827 auto Closure = InstrProfRecordClosure;
828 Closure.Record = &Record;
829 return getValueProfDataSize(&Closure);
830 }
831
832 // Wrapper implementation using the closure mechanism.
833 std::unique_ptr<ValueProfData>
serializeFrom(const InstrProfRecord & Record)834 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
835 InstrProfRecordClosure.Record = &Record;
836
837 std::unique_ptr<ValueProfData> VPD(
838 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
839 return VPD;
840 }
841
deserializeTo(InstrProfRecord & Record,InstrProfSymtab * SymTab)842 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
843 InstrProfSymtab *SymTab) {
844 Record.reserveSites(Kind, NumValueSites);
845
846 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
847 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
848 uint8_t ValueDataCount = this->SiteCountArray[VSite];
849 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, SymTab);
850 ValueData += ValueDataCount;
851 }
852 }
853
854 // For writing/serializing, Old is the host endianness, and New is
855 // byte order intended on disk. For Reading/deserialization, Old
856 // is the on-disk source endianness, and New is the host endianness.
swapBytes(support::endianness Old,support::endianness New)857 void ValueProfRecord::swapBytes(support::endianness Old,
858 support::endianness New) {
859 using namespace support;
860
861 if (Old == New)
862 return;
863
864 if (getHostEndianness() != Old) {
865 sys::swapByteOrder<uint32_t>(NumValueSites);
866 sys::swapByteOrder<uint32_t>(Kind);
867 }
868 uint32_t ND = getValueProfRecordNumValueData(this);
869 InstrProfValueData *VD = getValueProfRecordValueData(this);
870
871 // No need to swap byte array: SiteCountArrray.
872 for (uint32_t I = 0; I < ND; I++) {
873 sys::swapByteOrder<uint64_t>(VD[I].Value);
874 sys::swapByteOrder<uint64_t>(VD[I].Count);
875 }
876 if (getHostEndianness() == Old) {
877 sys::swapByteOrder<uint32_t>(NumValueSites);
878 sys::swapByteOrder<uint32_t>(Kind);
879 }
880 }
881
deserializeTo(InstrProfRecord & Record,InstrProfSymtab * SymTab)882 void ValueProfData::deserializeTo(InstrProfRecord &Record,
883 InstrProfSymtab *SymTab) {
884 if (NumValueKinds == 0)
885 return;
886
887 ValueProfRecord *VR = getFirstValueProfRecord(this);
888 for (uint32_t K = 0; K < NumValueKinds; K++) {
889 VR->deserializeTo(Record, SymTab);
890 VR = getValueProfRecordNext(VR);
891 }
892 }
893
894 template <class T>
swapToHostOrder(const unsigned char * & D,support::endianness Orig)895 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
896 using namespace support;
897
898 if (Orig == little)
899 return endian::readNext<T, little, unaligned>(D);
900 else
901 return endian::readNext<T, big, unaligned>(D);
902 }
903
allocValueProfData(uint32_t TotalSize)904 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
905 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
906 ValueProfData());
907 }
908
checkIntegrity()909 Error ValueProfData::checkIntegrity() {
910 if (NumValueKinds > IPVK_Last + 1)
911 return make_error<InstrProfError>(
912 instrprof_error::malformed, "number of value profile kinds is invalid");
913 // Total size needs to be multiple of quadword size.
914 if (TotalSize % sizeof(uint64_t))
915 return make_error<InstrProfError>(
916 instrprof_error::malformed, "total size is not multiples of quardword");
917
918 ValueProfRecord *VR = getFirstValueProfRecord(this);
919 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
920 if (VR->Kind > IPVK_Last)
921 return make_error<InstrProfError>(instrprof_error::malformed,
922 "value kind is invalid");
923 VR = getValueProfRecordNext(VR);
924 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
925 return make_error<InstrProfError>(
926 instrprof_error::malformed,
927 "value profile address is greater than total size");
928 }
929 return Error::success();
930 }
931
932 Expected<std::unique_ptr<ValueProfData>>
getValueProfData(const unsigned char * D,const unsigned char * const BufferEnd,support::endianness Endianness)933 ValueProfData::getValueProfData(const unsigned char *D,
934 const unsigned char *const BufferEnd,
935 support::endianness Endianness) {
936 using namespace support;
937
938 if (D + sizeof(ValueProfData) > BufferEnd)
939 return make_error<InstrProfError>(instrprof_error::truncated);
940
941 const unsigned char *Header = D;
942 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
943 if (D + TotalSize > BufferEnd)
944 return make_error<InstrProfError>(instrprof_error::too_large);
945
946 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
947 memcpy(VPD.get(), D, TotalSize);
948 // Byte swap.
949 VPD->swapBytesToHost(Endianness);
950
951 Error E = VPD->checkIntegrity();
952 if (E)
953 return std::move(E);
954
955 return std::move(VPD);
956 }
957
swapBytesToHost(support::endianness Endianness)958 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
959 using namespace support;
960
961 if (Endianness == getHostEndianness())
962 return;
963
964 sys::swapByteOrder<uint32_t>(TotalSize);
965 sys::swapByteOrder<uint32_t>(NumValueKinds);
966
967 ValueProfRecord *VR = getFirstValueProfRecord(this);
968 for (uint32_t K = 0; K < NumValueKinds; K++) {
969 VR->swapBytes(Endianness, getHostEndianness());
970 VR = getValueProfRecordNext(VR);
971 }
972 }
973
swapBytesFromHost(support::endianness Endianness)974 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
975 using namespace support;
976
977 if (Endianness == getHostEndianness())
978 return;
979
980 ValueProfRecord *VR = getFirstValueProfRecord(this);
981 for (uint32_t K = 0; K < NumValueKinds; K++) {
982 ValueProfRecord *NVR = getValueProfRecordNext(VR);
983 VR->swapBytes(getHostEndianness(), Endianness);
984 VR = NVR;
985 }
986 sys::swapByteOrder<uint32_t>(TotalSize);
987 sys::swapByteOrder<uint32_t>(NumValueKinds);
988 }
989
annotateValueSite(Module & M,Instruction & Inst,const InstrProfRecord & InstrProfR,InstrProfValueKind ValueKind,uint32_t SiteIdx,uint32_t MaxMDCount)990 void annotateValueSite(Module &M, Instruction &Inst,
991 const InstrProfRecord &InstrProfR,
992 InstrProfValueKind ValueKind, uint32_t SiteIdx,
993 uint32_t MaxMDCount) {
994 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
995 if (!NV)
996 return;
997
998 uint64_t Sum = 0;
999 std::unique_ptr<InstrProfValueData[]> VD =
1000 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
1001
1002 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
1003 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
1004 }
1005
annotateValueSite(Module & M,Instruction & Inst,ArrayRef<InstrProfValueData> VDs,uint64_t Sum,InstrProfValueKind ValueKind,uint32_t MaxMDCount)1006 void annotateValueSite(Module &M, Instruction &Inst,
1007 ArrayRef<InstrProfValueData> VDs,
1008 uint64_t Sum, InstrProfValueKind ValueKind,
1009 uint32_t MaxMDCount) {
1010 LLVMContext &Ctx = M.getContext();
1011 MDBuilder MDHelper(Ctx);
1012 SmallVector<Metadata *, 3> Vals;
1013 // Tag
1014 Vals.push_back(MDHelper.createString("VP"));
1015 // Value Kind
1016 Vals.push_back(MDHelper.createConstant(
1017 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
1018 // Total Count
1019 Vals.push_back(
1020 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
1021
1022 // Value Profile Data
1023 uint32_t MDCount = MaxMDCount;
1024 for (auto &VD : VDs) {
1025 Vals.push_back(MDHelper.createConstant(
1026 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
1027 Vals.push_back(MDHelper.createConstant(
1028 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
1029 if (--MDCount == 0)
1030 break;
1031 }
1032 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
1033 }
1034
getValueProfDataFromInst(const Instruction & Inst,InstrProfValueKind ValueKind,uint32_t MaxNumValueData,InstrProfValueData ValueData[],uint32_t & ActualNumValueData,uint64_t & TotalC,bool GetNoICPValue)1035 bool getValueProfDataFromInst(const Instruction &Inst,
1036 InstrProfValueKind ValueKind,
1037 uint32_t MaxNumValueData,
1038 InstrProfValueData ValueData[],
1039 uint32_t &ActualNumValueData, uint64_t &TotalC,
1040 bool GetNoICPValue) {
1041 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
1042 if (!MD)
1043 return false;
1044
1045 unsigned NOps = MD->getNumOperands();
1046
1047 if (NOps < 5)
1048 return false;
1049
1050 // Operand 0 is a string tag "VP":
1051 MDString *Tag = cast<MDString>(MD->getOperand(0));
1052 if (!Tag)
1053 return false;
1054
1055 if (!Tag->getString().equals("VP"))
1056 return false;
1057
1058 // Now check kind:
1059 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
1060 if (!KindInt)
1061 return false;
1062 if (KindInt->getZExtValue() != ValueKind)
1063 return false;
1064
1065 // Get total count
1066 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
1067 if (!TotalCInt)
1068 return false;
1069 TotalC = TotalCInt->getZExtValue();
1070
1071 ActualNumValueData = 0;
1072
1073 for (unsigned I = 3; I < NOps; I += 2) {
1074 if (ActualNumValueData >= MaxNumValueData)
1075 break;
1076 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
1077 ConstantInt *Count =
1078 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
1079 if (!Value || !Count)
1080 return false;
1081 uint64_t CntValue = Count->getZExtValue();
1082 if (!GetNoICPValue && (CntValue == NOMORE_ICP_MAGICNUM))
1083 continue;
1084 ValueData[ActualNumValueData].Value = Value->getZExtValue();
1085 ValueData[ActualNumValueData].Count = CntValue;
1086 ActualNumValueData++;
1087 }
1088 return true;
1089 }
1090
getPGOFuncNameMetadata(const Function & F)1091 MDNode *getPGOFuncNameMetadata(const Function &F) {
1092 return F.getMetadata(getPGOFuncNameMetadataName());
1093 }
1094
createPGOFuncNameMetadata(Function & F,StringRef PGOFuncName)1095 void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
1096 // Only for internal linkage functions.
1097 if (PGOFuncName == F.getName())
1098 return;
1099 // Don't create duplicated meta-data.
1100 if (getPGOFuncNameMetadata(F))
1101 return;
1102 LLVMContext &C = F.getContext();
1103 MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
1104 F.setMetadata(getPGOFuncNameMetadataName(), N);
1105 }
1106
needsComdatForCounter(const Function & F,const Module & M)1107 bool needsComdatForCounter(const Function &F, const Module &M) {
1108 if (F.hasComdat())
1109 return true;
1110
1111 if (!Triple(M.getTargetTriple()).supportsCOMDAT())
1112 return false;
1113
1114 // See createPGOFuncNameVar for more details. To avoid link errors, profile
1115 // counters for function with available_externally linkage needs to be changed
1116 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
1117 // created. Without using comdat, duplicate entries won't be removed by the
1118 // linker leading to increased data segement size and raw profile size. Even
1119 // worse, since the referenced counter from profile per-function data object
1120 // will be resolved to the common strong definition, the profile counts for
1121 // available_externally functions will end up being duplicated in raw profile
1122 // data. This can result in distorted profile as the counts of those dups
1123 // will be accumulated by the profile merger.
1124 GlobalValue::LinkageTypes Linkage = F.getLinkage();
1125 if (Linkage != GlobalValue::ExternalWeakLinkage &&
1126 Linkage != GlobalValue::AvailableExternallyLinkage)
1127 return false;
1128
1129 return true;
1130 }
1131
1132 // Check if INSTR_PROF_RAW_VERSION_VAR is defined.
isIRPGOFlagSet(const Module * M)1133 bool isIRPGOFlagSet(const Module *M) {
1134 auto IRInstrVar =
1135 M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1136 if (!IRInstrVar || IRInstrVar->hasLocalLinkage())
1137 return false;
1138
1139 // For CSPGO+LTO, this variable might be marked as non-prevailing and we only
1140 // have the decl.
1141 if (IRInstrVar->isDeclaration())
1142 return true;
1143
1144 // Check if the flag is set.
1145 if (!IRInstrVar->hasInitializer())
1146 return false;
1147
1148 auto *InitVal = dyn_cast_or_null<ConstantInt>(IRInstrVar->getInitializer());
1149 if (!InitVal)
1150 return false;
1151 return (InitVal->getZExtValue() & VARIANT_MASK_IR_PROF) != 0;
1152 }
1153
1154 // Check if we can safely rename this Comdat function.
canRenameComdatFunc(const Function & F,bool CheckAddressTaken)1155 bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
1156 if (F.getName().empty())
1157 return false;
1158 if (!needsComdatForCounter(F, *(F.getParent())))
1159 return false;
1160 // Unsafe to rename the address-taken function (which can be used in
1161 // function comparison).
1162 if (CheckAddressTaken && F.hasAddressTaken())
1163 return false;
1164 // Only safe to do if this function may be discarded if it is not used
1165 // in the compilation unit.
1166 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
1167 return false;
1168
1169 // For AvailableExternallyLinkage functions.
1170 if (!F.hasComdat()) {
1171 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
1172 return true;
1173 }
1174 return true;
1175 }
1176
1177 // Create the variable for the profile file name.
createProfileFileNameVar(Module & M,StringRef InstrProfileOutput)1178 void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput) {
1179 if (InstrProfileOutput.empty())
1180 return;
1181 Constant *ProfileNameConst =
1182 ConstantDataArray::getString(M.getContext(), InstrProfileOutput, true);
1183 GlobalVariable *ProfileNameVar = new GlobalVariable(
1184 M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
1185 ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
1186 Triple TT(M.getTargetTriple());
1187 if (TT.supportsCOMDAT()) {
1188 ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
1189 ProfileNameVar->setComdat(M.getOrInsertComdat(
1190 StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
1191 }
1192 }
1193
accumulateCounts(const std::string & BaseFilename,const std::string & TestFilename,bool IsCS)1194 Error OverlapStats::accumulateCounts(const std::string &BaseFilename,
1195 const std::string &TestFilename,
1196 bool IsCS) {
1197 auto getProfileSum = [IsCS](const std::string &Filename,
1198 CountSumOrPercent &Sum) -> Error {
1199 auto ReaderOrErr = InstrProfReader::create(Filename);
1200 if (Error E = ReaderOrErr.takeError()) {
1201 return E;
1202 }
1203 auto Reader = std::move(ReaderOrErr.get());
1204 Reader->accumulateCounts(Sum, IsCS);
1205 return Error::success();
1206 };
1207 auto Ret = getProfileSum(BaseFilename, Base);
1208 if (Ret)
1209 return Ret;
1210 Ret = getProfileSum(TestFilename, Test);
1211 if (Ret)
1212 return Ret;
1213 this->BaseFilename = &BaseFilename;
1214 this->TestFilename = &TestFilename;
1215 Valid = true;
1216 return Error::success();
1217 }
1218
addOneMismatch(const CountSumOrPercent & MismatchFunc)1219 void OverlapStats::addOneMismatch(const CountSumOrPercent &MismatchFunc) {
1220 Mismatch.NumEntries += 1;
1221 Mismatch.CountSum += MismatchFunc.CountSum / Test.CountSum;
1222 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1223 if (Test.ValueCounts[I] >= 1.0f)
1224 Mismatch.ValueCounts[I] +=
1225 MismatchFunc.ValueCounts[I] / Test.ValueCounts[I];
1226 }
1227 }
1228
addOneUnique(const CountSumOrPercent & UniqueFunc)1229 void OverlapStats::addOneUnique(const CountSumOrPercent &UniqueFunc) {
1230 Unique.NumEntries += 1;
1231 Unique.CountSum += UniqueFunc.CountSum / Test.CountSum;
1232 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1233 if (Test.ValueCounts[I] >= 1.0f)
1234 Unique.ValueCounts[I] += UniqueFunc.ValueCounts[I] / Test.ValueCounts[I];
1235 }
1236 }
1237
dump(raw_fd_ostream & OS) const1238 void OverlapStats::dump(raw_fd_ostream &OS) const {
1239 if (!Valid)
1240 return;
1241
1242 const char *EntryName =
1243 (Level == ProgramLevel ? "functions" : "edge counters");
1244 if (Level == ProgramLevel) {
1245 OS << "Profile overlap infomation for base_profile: " << *BaseFilename
1246 << " and test_profile: " << *TestFilename << "\nProgram level:\n";
1247 } else {
1248 OS << "Function level:\n"
1249 << " Function: " << FuncName << " (Hash=" << FuncHash << ")\n";
1250 }
1251
1252 OS << " # of " << EntryName << " overlap: " << Overlap.NumEntries << "\n";
1253 if (Mismatch.NumEntries)
1254 OS << " # of " << EntryName << " mismatch: " << Mismatch.NumEntries
1255 << "\n";
1256 if (Unique.NumEntries)
1257 OS << " # of " << EntryName
1258 << " only in test_profile: " << Unique.NumEntries << "\n";
1259
1260 OS << " Edge profile overlap: " << format("%.3f%%", Overlap.CountSum * 100)
1261 << "\n";
1262 if (Mismatch.NumEntries)
1263 OS << " Mismatched count percentage (Edge): "
1264 << format("%.3f%%", Mismatch.CountSum * 100) << "\n";
1265 if (Unique.NumEntries)
1266 OS << " Percentage of Edge profile only in test_profile: "
1267 << format("%.3f%%", Unique.CountSum * 100) << "\n";
1268 OS << " Edge profile base count sum: " << format("%.0f", Base.CountSum)
1269 << "\n"
1270 << " Edge profile test count sum: " << format("%.0f", Test.CountSum)
1271 << "\n";
1272
1273 for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1274 if (Base.ValueCounts[I] < 1.0f && Test.ValueCounts[I] < 1.0f)
1275 continue;
1276 char ProfileKindName[20];
1277 switch (I) {
1278 case IPVK_IndirectCallTarget:
1279 strncpy(ProfileKindName, "IndirectCall", 19);
1280 break;
1281 case IPVK_MemOPSize:
1282 strncpy(ProfileKindName, "MemOP", 19);
1283 break;
1284 default:
1285 snprintf(ProfileKindName, 19, "VP[%d]", I);
1286 break;
1287 }
1288 OS << " " << ProfileKindName
1289 << " profile overlap: " << format("%.3f%%", Overlap.ValueCounts[I] * 100)
1290 << "\n";
1291 if (Mismatch.NumEntries)
1292 OS << " Mismatched count percentage (" << ProfileKindName
1293 << "): " << format("%.3f%%", Mismatch.ValueCounts[I] * 100) << "\n";
1294 if (Unique.NumEntries)
1295 OS << " Percentage of " << ProfileKindName
1296 << " profile only in test_profile: "
1297 << format("%.3f%%", Unique.ValueCounts[I] * 100) << "\n";
1298 OS << " " << ProfileKindName
1299 << " profile base count sum: " << format("%.0f", Base.ValueCounts[I])
1300 << "\n"
1301 << " " << ProfileKindName
1302 << " profile test count sum: " << format("%.0f", Test.ValueCounts[I])
1303 << "\n";
1304 }
1305 }
1306
1307 namespace IndexedInstrProf {
1308 // A C++14 compatible version of the offsetof macro.
1309 template <typename T1, typename T2>
offsetOf(T1 T2::* Member)1310 inline size_t constexpr offsetOf(T1 T2::*Member) {
1311 constexpr T2 Object{};
1312 return size_t(&(Object.*Member)) - size_t(&Object);
1313 }
1314
read(const unsigned char * Buffer,size_t Offset)1315 static inline uint64_t read(const unsigned char *Buffer, size_t Offset) {
1316 return *reinterpret_cast<const uint64_t *>(Buffer + Offset);
1317 }
1318
formatVersion() const1319 uint64_t Header::formatVersion() const {
1320 using namespace support;
1321 return endian::byte_swap<uint64_t, little>(Version);
1322 }
1323
readFromBuffer(const unsigned char * Buffer)1324 Expected<Header> Header::readFromBuffer(const unsigned char *Buffer) {
1325 using namespace support;
1326 static_assert(std::is_standard_layout<Header>::value,
1327 "The header should be standard layout type since we use offset "
1328 "of fields to read.");
1329 Header H;
1330
1331 H.Magic = read(Buffer, offsetOf(&Header::Magic));
1332 // Check the magic number.
1333 uint64_t Magic = endian::byte_swap<uint64_t, little>(H.Magic);
1334 if (Magic != IndexedInstrProf::Magic)
1335 return make_error<InstrProfError>(instrprof_error::bad_magic);
1336
1337 // Read the version.
1338 H.Version = read(Buffer, offsetOf(&Header::Version));
1339 if (GET_VERSION(H.formatVersion()) >
1340 IndexedInstrProf::ProfVersion::CurrentVersion)
1341 return make_error<InstrProfError>(instrprof_error::unsupported_version);
1342
1343 switch (GET_VERSION(H.formatVersion())) {
1344 // When a new field is added in the header add a case statement here to
1345 // populate it.
1346 static_assert(
1347 IndexedInstrProf::ProfVersion::CurrentVersion == Version8,
1348 "Please update the reading code below if a new field has been added, "
1349 "if not add a case statement to fall through to the latest version.");
1350 case 8ull:
1351 H.MemProfOffset = read(Buffer, offsetOf(&Header::MemProfOffset));
1352 LLVM_FALLTHROUGH;
1353 default: // Version7 (when the backwards compatible header was introduced).
1354 H.HashType = read(Buffer, offsetOf(&Header::HashType));
1355 H.HashOffset = read(Buffer, offsetOf(&Header::HashOffset));
1356 }
1357
1358 return H;
1359 }
1360
size() const1361 size_t Header::size() const {
1362 switch (GET_VERSION(formatVersion())) {
1363 // When a new field is added to the header add a case statement here to
1364 // compute the size as offset of the new field + size of the new field. This
1365 // relies on the field being added to the end of the list.
1366 static_assert(IndexedInstrProf::ProfVersion::CurrentVersion == Version8,
1367 "Please update the size computation below if a new field has "
1368 "been added to the header, if not add a case statement to "
1369 "fall through to the latest version.");
1370 case 8ull:
1371 return offsetOf(&Header::MemProfOffset) + sizeof(Header::MemProfOffset);
1372 default: // Version7 (when the backwards compatible header was introduced).
1373 return offsetOf(&Header::HashOffset) + sizeof(Header::HashOffset);
1374 }
1375 }
1376
1377 } // namespace IndexedInstrProf
1378
1379 } // end namespace llvm
1380