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/IR/Constant.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalValue.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/Instruction.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/MDBuilder.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/ProfileData/InstrProfReader.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/Compression.h"
37 #include "llvm/Support/Endian.h"
38 #include "llvm/Support/Error.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/LEB128.h"
41 #include "llvm/Support/ManagedStatic.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 <utility>
54 #include <vector>
55 
56 using namespace llvm;
57 
58 static cl::opt<bool> StaticFuncFullModulePrefix(
59     "static-func-full-module-prefix", cl::init(true), cl::Hidden,
60     cl::desc("Use full module build paths in the profile counter names for "
61              "static functions."));
62 
63 // 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 //
68 // Note current ThinLTO module importing for the indirect-calls assumes
69 // the source directory name not being stripped. A non-zero option value here
70 // can potentially prevent some inter-module indirect-call-promotions.
71 static cl::opt<unsigned> StaticFuncStripDirNamePrefix(
72     "static-func-strip-dirname-prefix", cl::init(0), cl::Hidden,
73     cl::desc("Strip specified level of directory name from source path in "
74              "the profile counter name for static functions."));
75 
getInstrProfErrString(instrprof_error Err)76 static std::string getInstrProfErrString(instrprof_error Err) {
77   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)";
112   case instrprof_error::empty_raw_profile:
113     return "Empty raw profile file";
114   case instrprof_error::zlib_unavailable:
115     return "Profile uses zlib compression but the profile reader was built without zlib support";
116   }
117   llvm_unreachable("A value of instrprof_error has no message.");
118 }
119 
120 namespace {
121 
122 // 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.
125 class InstrProfErrorCategoryType : public std::error_category {
name() const126   const char *name() const noexcept override { return "llvm.instrprof"; }
127 
message(int IE) const128   std::string message(int IE) const override {
129     return getInstrProfErrString(static_cast<instrprof_error>(IE));
130   }
131 };
132 
133 } // end anonymous namespace
134 
135 static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
136 
instrprof_category()137 const std::error_category &llvm::instrprof_category() {
138   return *ErrorCategory;
139 }
140 
141 namespace {
142 
143 const char *InstrProfSectNameCommon[] = {
144 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix)      \
145   SectNameCommon,
146 #include "llvm/ProfileData/InstrProfData.inc"
147 };
148 
149 const char *InstrProfSectNameCoff[] = {
150 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix)      \
151   SectNameCoff,
152 #include "llvm/ProfileData/InstrProfData.inc"
153 };
154 
155 const char *InstrProfSectNamePrefix[] = {
156 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix)      \
157   Prefix,
158 #include "llvm/ProfileData/InstrProfData.inc"
159 };
160 
161 } // namespace
162 
163 namespace llvm {
164 
getInstrProfSectionName(InstrProfSectKind IPSK,Triple::ObjectFormatType OF,bool AddSegmentInfo)165 std::string getInstrProfSectionName(InstrProfSectKind IPSK,
166                                     Triple::ObjectFormatType OF,
167                                     bool AddSegmentInfo) {
168   std::string SectName;
169 
170   if (OF == Triple::MachO && AddSegmentInfo)
171     SectName = InstrProfSectNamePrefix[IPSK];
172 
173   if (OF == Triple::COFF)
174     SectName += InstrProfSectNameCoff[IPSK];
175   else
176     SectName += InstrProfSectNameCommon[IPSK];
177 
178   if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
179     SectName += ",regular,live_support";
180 
181   return SectName;
182 }
183 
addError(instrprof_error IE)184 void 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 
message() const209 std::string InstrProfError::message() const {
210   return getInstrProfErrString(Err);
211 }
212 
213 char InstrProfError::ID = 0;
214 
getPGOFuncName(StringRef RawFuncName,GlobalValue::LinkageTypes Linkage,StringRef FileName,uint64_t Version LLVM_ATTRIBUTE_UNUSED)215 std::string getPGOFuncName(StringRef RawFuncName,
216                            GlobalValue::LinkageTypes Linkage,
217                            StringRef FileName,
218                            uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
219   return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
220 }
221 
222 // 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.
stripDirPrefix(StringRef PathNameStr,uint32_t NumPrefix)225 static 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 
240 // 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.
245 // 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.
248 // 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.
getPGOFuncName(const Function & F,bool InLTO,uint64_t Version)253 std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
254   if (!InLTO) {
255     StringRef FileName(F.getParent()->getSourceFileName());
256     uint32_t StripLevel = StaticFuncFullModulePrefix ? 0 : (uint32_t)-1;
257     if (StripLevel < StaticFuncStripDirNamePrefix)
258       StripLevel = StaticFuncStripDirNamePrefix;
259     if (StripLevel)
260       FileName = stripDirPrefix(FileName, StripLevel);
261     return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
262   }
263 
264   // In LTO mode (when InLTO is true), first check if there is a meta data.
265   if (MDNode *MD = getPGOFuncNameMetadata(F)) {
266     StringRef S = cast<MDString>(MD->getOperand(0))->getString();
267     return S.str();
268   }
269 
270   // If there is no meta data, the function must be a global before the value
271   // profile annotation pass. Its current linkage may be internal if it is
272   // internalized in LTO mode.
273   return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
274 }
275 
getFuncNameWithoutPrefix(StringRef PGOFuncName,StringRef FileName)276 StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
277   if (FileName.empty())
278     return PGOFuncName;
279   // Drop the file name including ':'. See also getPGOFuncName.
280   if (PGOFuncName.startswith(FileName))
281     PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
282   return PGOFuncName;
283 }
284 
285 // \p FuncName is the string used as profile lookup key for the function. A
286 // symbol is created to hold the name. Return the legalized symbol name.
getPGOFuncNameVarName(StringRef FuncName,GlobalValue::LinkageTypes Linkage)287 std::string getPGOFuncNameVarName(StringRef FuncName,
288                                   GlobalValue::LinkageTypes Linkage) {
289   std::string VarName = getInstrProfNameVarPrefix();
290   VarName += FuncName;
291 
292   if (!GlobalValue::isLocalLinkage(Linkage))
293     return VarName;
294 
295   // Now fix up illegal chars in local VarName that may upset the assembler.
296   const char *InvalidChars = "-:<>/\"'";
297   size_t found = VarName.find_first_of(InvalidChars);
298   while (found != std::string::npos) {
299     VarName[found] = '_';
300     found = VarName.find_first_of(InvalidChars, found + 1);
301   }
302   return VarName;
303 }
304 
createPGOFuncNameVar(Module & M,GlobalValue::LinkageTypes Linkage,StringRef PGOFuncName)305 GlobalVariable *createPGOFuncNameVar(Module &M,
306                                      GlobalValue::LinkageTypes Linkage,
307                                      StringRef PGOFuncName) {
308   // We generally want to match the function's linkage, but available_externally
309   // and extern_weak both have the wrong semantics, and anything that doesn't
310   // need to link across compilation units doesn't need to be visible at all.
311   if (Linkage == GlobalValue::ExternalWeakLinkage)
312     Linkage = GlobalValue::LinkOnceAnyLinkage;
313   else if (Linkage == GlobalValue::AvailableExternallyLinkage)
314     Linkage = GlobalValue::LinkOnceODRLinkage;
315   else if (Linkage == GlobalValue::InternalLinkage ||
316            Linkage == GlobalValue::ExternalLinkage)
317     Linkage = GlobalValue::PrivateLinkage;
318 
319   auto *Value =
320       ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
321   auto FuncNameVar =
322       new GlobalVariable(M, Value->getType(), true, Linkage, Value,
323                          getPGOFuncNameVarName(PGOFuncName, Linkage));
324 
325   // Hide the symbol so that we correctly get a copy for each executable.
326   if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
327     FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
328 
329   return FuncNameVar;
330 }
331 
createPGOFuncNameVar(Function & F,StringRef PGOFuncName)332 GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
333   return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
334 }
335 
create(Module & M,bool InLTO)336 Error InstrProfSymtab::create(Module &M, bool InLTO) {
337   for (Function &F : M) {
338     // Function may not have a name: like using asm("") to overwrite the name.
339     // Ignore in this case.
340     if (!F.hasName())
341       continue;
342     const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
343     if (Error E = addFuncName(PGOFuncName))
344       return E;
345     MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
346     // In ThinLTO, local function may have been promoted to global and have
347     // suffix added to the function name. We need to add the stripped function
348     // name to the symbol table so that we can find a match from profile.
349     if (InLTO) {
350       auto pos = PGOFuncName.find('.');
351       if (pos != std::string::npos) {
352         const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
353         if (Error E = addFuncName(OtherFuncName))
354           return E;
355         MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F);
356       }
357     }
358   }
359   Sorted = false;
360   finalizeSymtab();
361   return Error::success();
362 }
363 
getFunctionHashFromAddress(uint64_t Address)364 uint64_t InstrProfSymtab::getFunctionHashFromAddress(uint64_t Address) {
365   finalizeSymtab();
366   auto It = partition_point(AddrToMD5Map, [=](std::pair<uint64_t, uint64_t> A) {
367     return A.first < Address;
368   });
369   // Raw function pointer collected by value profiler may be from
370   // external functions that are not instrumented. They won't have
371   // mapping data to be used by the deserializer. Force the value to
372   // be 0 in this case.
373   if (It != AddrToMD5Map.end() && It->first == Address)
374     return (uint64_t)It->second;
375   return 0;
376 }
377 
collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs,bool doCompression,std::string & Result)378 Error collectPGOFuncNameStrings(ArrayRef<std::string> NameStrs,
379                                 bool doCompression, std::string &Result) {
380   assert(!NameStrs.empty() && "No name data to emit");
381 
382   uint8_t Header[16], *P = Header;
383   std::string UncompressedNameStrings =
384       join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
385 
386   assert(StringRef(UncompressedNameStrings)
387                  .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
388          "PGO name is invalid (contains separator token)");
389 
390   unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
391   P += EncLen;
392 
393   auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
394     EncLen = encodeULEB128(CompressedLen, P);
395     P += EncLen;
396     char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
397     unsigned HeaderLen = P - &Header[0];
398     Result.append(HeaderStr, HeaderLen);
399     Result += InputStr;
400     return Error::success();
401   };
402 
403   if (!doCompression) {
404     return WriteStringToResult(0, UncompressedNameStrings);
405   }
406 
407   SmallString<128> CompressedNameStrings;
408   Error E = zlib::compress(StringRef(UncompressedNameStrings),
409                            CompressedNameStrings, zlib::BestSizeCompression);
410   if (E) {
411     consumeError(std::move(E));
412     return make_error<InstrProfError>(instrprof_error::compress_failed);
413   }
414 
415   return WriteStringToResult(CompressedNameStrings.size(),
416                              CompressedNameStrings);
417 }
418 
getPGOFuncNameVarInitializer(GlobalVariable * NameVar)419 StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
420   auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
421   StringRef NameStr =
422       Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
423   return NameStr;
424 }
425 
collectPGOFuncNameStrings(ArrayRef<GlobalVariable * > NameVars,std::string & Result,bool doCompression)426 Error collectPGOFuncNameStrings(ArrayRef<GlobalVariable *> NameVars,
427                                 std::string &Result, bool doCompression) {
428   std::vector<std::string> NameStrs;
429   for (auto *NameVar : NameVars) {
430     NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
431   }
432   return collectPGOFuncNameStrings(
433       NameStrs, zlib::isAvailable() && doCompression, Result);
434 }
435 
readPGOFuncNameStrings(StringRef NameStrings,InstrProfSymtab & Symtab)436 Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
437   const uint8_t *P = NameStrings.bytes_begin();
438   const uint8_t *EndP = NameStrings.bytes_end();
439   while (P < EndP) {
440     uint32_t N;
441     uint64_t UncompressedSize = decodeULEB128(P, &N);
442     P += N;
443     uint64_t CompressedSize = decodeULEB128(P, &N);
444     P += N;
445     bool isCompressed = (CompressedSize != 0);
446     SmallString<128> UncompressedNameStrings;
447     StringRef NameStrings;
448     if (isCompressed) {
449       if (!llvm::zlib::isAvailable())
450         return make_error<InstrProfError>(instrprof_error::zlib_unavailable);
451 
452       StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
453                                       CompressedSize);
454       if (Error E =
455               zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
456                                UncompressedSize)) {
457         consumeError(std::move(E));
458         return make_error<InstrProfError>(instrprof_error::uncompress_failed);
459       }
460       P += CompressedSize;
461       NameStrings = StringRef(UncompressedNameStrings.data(),
462                               UncompressedNameStrings.size());
463     } else {
464       NameStrings =
465           StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
466       P += UncompressedSize;
467     }
468     // Now parse the name strings.
469     SmallVector<StringRef, 0> Names;
470     NameStrings.split(Names, getInstrProfNameSeparator());
471     for (StringRef &Name : Names)
472       if (Error E = Symtab.addFuncName(Name))
473         return E;
474 
475     while (P < EndP && *P == 0)
476       P++;
477   }
478   return Error::success();
479 }
480 
accumulateCounts(CountSumOrPercent & Sum) const481 void InstrProfRecord::accumulateCounts(CountSumOrPercent &Sum) const {
482   uint64_t FuncSum = 0;
483   Sum.NumEntries += Counts.size();
484   for (size_t F = 0, E = Counts.size(); F < E; ++F)
485     FuncSum += Counts[F];
486   Sum.CountSum += FuncSum;
487 
488   for (uint32_t VK = IPVK_First; VK <= IPVK_Last; ++VK) {
489     uint64_t KindSum = 0;
490     uint32_t NumValueSites = getNumValueSites(VK);
491     for (size_t I = 0; I < NumValueSites; ++I) {
492       uint32_t NV = getNumValueDataForSite(VK, I);
493       std::unique_ptr<InstrProfValueData[]> VD = getValueForSite(VK, I);
494       for (uint32_t V = 0; V < NV; V++)
495         KindSum += VD[V].Count;
496     }
497     Sum.ValueCounts[VK] += KindSum;
498   }
499 }
500 
overlap(InstrProfValueSiteRecord & Input,uint32_t ValueKind,OverlapStats & Overlap,OverlapStats & FuncLevelOverlap)501 void InstrProfValueSiteRecord::overlap(InstrProfValueSiteRecord &Input,
502                                        uint32_t ValueKind,
503                                        OverlapStats &Overlap,
504                                        OverlapStats &FuncLevelOverlap) {
505   this->sortByTargetValues();
506   Input.sortByTargetValues();
507   double Score = 0.0f, FuncLevelScore = 0.0f;
508   auto I = ValueData.begin();
509   auto IE = ValueData.end();
510   auto J = Input.ValueData.begin();
511   auto JE = Input.ValueData.end();
512   while (I != IE && J != JE) {
513     if (I->Value == J->Value) {
514       Score += OverlapStats::score(I->Count, J->Count,
515                                    Overlap.Base.ValueCounts[ValueKind],
516                                    Overlap.Test.ValueCounts[ValueKind]);
517       FuncLevelScore += OverlapStats::score(
518           I->Count, J->Count, FuncLevelOverlap.Base.ValueCounts[ValueKind],
519           FuncLevelOverlap.Test.ValueCounts[ValueKind]);
520       ++I;
521     } else if (I->Value < J->Value) {
522       ++I;
523       continue;
524     }
525     ++J;
526   }
527   Overlap.Overlap.ValueCounts[ValueKind] += Score;
528   FuncLevelOverlap.Overlap.ValueCounts[ValueKind] += FuncLevelScore;
529 }
530 
531 // Return false on mismatch.
overlapValueProfData(uint32_t ValueKind,InstrProfRecord & Other,OverlapStats & Overlap,OverlapStats & FuncLevelOverlap)532 void InstrProfRecord::overlapValueProfData(uint32_t ValueKind,
533                                            InstrProfRecord &Other,
534                                            OverlapStats &Overlap,
535                                            OverlapStats &FuncLevelOverlap) {
536   uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
537   assert(ThisNumValueSites == Other.getNumValueSites(ValueKind));
538   if (!ThisNumValueSites)
539     return;
540 
541   std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
542       getOrCreateValueSitesForKind(ValueKind);
543   MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
544       Other.getValueSitesForKind(ValueKind);
545   for (uint32_t I = 0; I < ThisNumValueSites; I++)
546     ThisSiteRecords[I].overlap(OtherSiteRecords[I], ValueKind, Overlap,
547                                FuncLevelOverlap);
548 }
549 
overlap(InstrProfRecord & Other,OverlapStats & Overlap,OverlapStats & FuncLevelOverlap,uint64_t ValueCutoff)550 void InstrProfRecord::overlap(InstrProfRecord &Other, OverlapStats &Overlap,
551                               OverlapStats &FuncLevelOverlap,
552                               uint64_t ValueCutoff) {
553   // FuncLevel CountSum for other should already computed and nonzero.
554   assert(FuncLevelOverlap.Test.CountSum >= 1.0f);
555   accumulateCounts(FuncLevelOverlap.Base);
556   bool Mismatch = (Counts.size() != Other.Counts.size());
557 
558   // Check if the value profiles mismatch.
559   if (!Mismatch) {
560     for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
561       uint32_t ThisNumValueSites = getNumValueSites(Kind);
562       uint32_t OtherNumValueSites = Other.getNumValueSites(Kind);
563       if (ThisNumValueSites != OtherNumValueSites) {
564         Mismatch = true;
565         break;
566       }
567     }
568   }
569   if (Mismatch) {
570     Overlap.addOneMismatch(FuncLevelOverlap.Test);
571     return;
572   }
573 
574   // Compute overlap for value counts.
575   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
576     overlapValueProfData(Kind, Other, Overlap, FuncLevelOverlap);
577 
578   double Score = 0.0;
579   uint64_t MaxCount = 0;
580   // Compute overlap for edge counts.
581   for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
582     Score += OverlapStats::score(Counts[I], Other.Counts[I],
583                                  Overlap.Base.CountSum, Overlap.Test.CountSum);
584     MaxCount = std::max(Other.Counts[I], MaxCount);
585   }
586   Overlap.Overlap.CountSum += Score;
587   Overlap.Overlap.NumEntries += 1;
588 
589   if (MaxCount >= ValueCutoff) {
590     double FuncScore = 0.0;
591     for (size_t I = 0, E = Other.Counts.size(); I < E; ++I)
592       FuncScore += OverlapStats::score(Counts[I], Other.Counts[I],
593                                        FuncLevelOverlap.Base.CountSum,
594                                        FuncLevelOverlap.Test.CountSum);
595     FuncLevelOverlap.Overlap.CountSum = FuncScore;
596     FuncLevelOverlap.Overlap.NumEntries = Other.Counts.size();
597     FuncLevelOverlap.Valid = true;
598   }
599 }
600 
merge(InstrProfValueSiteRecord & Input,uint64_t Weight,function_ref<void (instrprof_error)> Warn)601 void InstrProfValueSiteRecord::merge(InstrProfValueSiteRecord &Input,
602                                      uint64_t Weight,
603                                      function_ref<void(instrprof_error)> Warn) {
604   this->sortByTargetValues();
605   Input.sortByTargetValues();
606   auto I = ValueData.begin();
607   auto IE = ValueData.end();
608   for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
609        ++J) {
610     while (I != IE && I->Value < J->Value)
611       ++I;
612     if (I != IE && I->Value == J->Value) {
613       bool Overflowed;
614       I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
615       if (Overflowed)
616         Warn(instrprof_error::counter_overflow);
617       ++I;
618       continue;
619     }
620     ValueData.insert(I, *J);
621   }
622 }
623 
scale(uint64_t Weight,function_ref<void (instrprof_error)> Warn)624 void InstrProfValueSiteRecord::scale(uint64_t Weight,
625                                      function_ref<void(instrprof_error)> Warn) {
626   for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
627     bool Overflowed;
628     I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
629     if (Overflowed)
630       Warn(instrprof_error::counter_overflow);
631   }
632 }
633 
634 // Merge Value Profile data from Src record to this record for ValueKind.
635 // Scale merged value counts by \p Weight.
mergeValueProfData(uint32_t ValueKind,InstrProfRecord & Src,uint64_t Weight,function_ref<void (instrprof_error)> Warn)636 void InstrProfRecord::mergeValueProfData(
637     uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight,
638     function_ref<void(instrprof_error)> Warn) {
639   uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
640   uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
641   if (ThisNumValueSites != OtherNumValueSites) {
642     Warn(instrprof_error::value_site_count_mismatch);
643     return;
644   }
645   if (!ThisNumValueSites)
646     return;
647   std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
648       getOrCreateValueSitesForKind(ValueKind);
649   MutableArrayRef<InstrProfValueSiteRecord> OtherSiteRecords =
650       Src.getValueSitesForKind(ValueKind);
651   for (uint32_t I = 0; I < ThisNumValueSites; I++)
652     ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn);
653 }
654 
merge(InstrProfRecord & Other,uint64_t Weight,function_ref<void (instrprof_error)> Warn)655 void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight,
656                             function_ref<void(instrprof_error)> Warn) {
657   // If the number of counters doesn't match we either have bad data
658   // or a hash collision.
659   if (Counts.size() != Other.Counts.size()) {
660     Warn(instrprof_error::count_mismatch);
661     return;
662   }
663 
664   for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
665     bool Overflowed;
666     Counts[I] =
667         SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
668     if (Overflowed)
669       Warn(instrprof_error::counter_overflow);
670   }
671 
672   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
673     mergeValueProfData(Kind, Other, Weight, Warn);
674 }
675 
scaleValueProfData(uint32_t ValueKind,uint64_t Weight,function_ref<void (instrprof_error)> Warn)676 void InstrProfRecord::scaleValueProfData(
677     uint32_t ValueKind, uint64_t Weight,
678     function_ref<void(instrprof_error)> Warn) {
679   for (auto &R : getValueSitesForKind(ValueKind))
680     R.scale(Weight, Warn);
681 }
682 
scale(uint64_t Weight,function_ref<void (instrprof_error)> Warn)683 void InstrProfRecord::scale(uint64_t Weight,
684                             function_ref<void(instrprof_error)> Warn) {
685   for (auto &Count : this->Counts) {
686     bool Overflowed;
687     Count = SaturatingMultiply(Count, Weight, &Overflowed);
688     if (Overflowed)
689       Warn(instrprof_error::counter_overflow);
690   }
691   for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
692     scaleValueProfData(Kind, Weight, Warn);
693 }
694 
695 // Map indirect call target name hash to name string.
remapValue(uint64_t Value,uint32_t ValueKind,InstrProfSymtab * SymTab)696 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
697                                      InstrProfSymtab *SymTab) {
698   if (!SymTab)
699     return Value;
700 
701   if (ValueKind == IPVK_IndirectCallTarget)
702     return SymTab->getFunctionHashFromAddress(Value);
703 
704   return Value;
705 }
706 
addValueData(uint32_t ValueKind,uint32_t Site,InstrProfValueData * VData,uint32_t N,InstrProfSymtab * ValueMap)707 void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
708                                    InstrProfValueData *VData, uint32_t N,
709                                    InstrProfSymtab *ValueMap) {
710   for (uint32_t I = 0; I < N; I++) {
711     VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
712   }
713   std::vector<InstrProfValueSiteRecord> &ValueSites =
714       getOrCreateValueSitesForKind(ValueKind);
715   if (N == 0)
716     ValueSites.emplace_back();
717   else
718     ValueSites.emplace_back(VData, VData + N);
719 }
720 
721 #define INSTR_PROF_COMMON_API_IMPL
722 #include "llvm/ProfileData/InstrProfData.inc"
723 
724 /*!
725  * ValueProfRecordClosure Interface implementation for  InstrProfRecord
726  *  class. These C wrappers are used as adaptors so that C++ code can be
727  *  invoked as callbacks.
728  */
getNumValueKindsInstrProf(const void * Record)729 uint32_t getNumValueKindsInstrProf(const void *Record) {
730   return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
731 }
732 
getNumValueSitesInstrProf(const void * Record,uint32_t VKind)733 uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
734   return reinterpret_cast<const InstrProfRecord *>(Record)
735       ->getNumValueSites(VKind);
736 }
737 
getNumValueDataInstrProf(const void * Record,uint32_t VKind)738 uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
739   return reinterpret_cast<const InstrProfRecord *>(Record)
740       ->getNumValueData(VKind);
741 }
742 
getNumValueDataForSiteInstrProf(const void * R,uint32_t VK,uint32_t S)743 uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
744                                          uint32_t S) {
745   return reinterpret_cast<const InstrProfRecord *>(R)
746       ->getNumValueDataForSite(VK, S);
747 }
748 
getValueForSiteInstrProf(const void * R,InstrProfValueData * Dst,uint32_t K,uint32_t S)749 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
750                               uint32_t K, uint32_t S) {
751   reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
752 }
753 
allocValueProfDataInstrProf(size_t TotalSizeInBytes)754 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
755   ValueProfData *VD =
756       (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
757   memset(VD, 0, TotalSizeInBytes);
758   return VD;
759 }
760 
761 static ValueProfRecordClosure InstrProfRecordClosure = {
762     nullptr,
763     getNumValueKindsInstrProf,
764     getNumValueSitesInstrProf,
765     getNumValueDataInstrProf,
766     getNumValueDataForSiteInstrProf,
767     nullptr,
768     getValueForSiteInstrProf,
769     allocValueProfDataInstrProf};
770 
771 // Wrapper implementation using the closure mechanism.
getSize(const InstrProfRecord & Record)772 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
773   auto Closure = InstrProfRecordClosure;
774   Closure.Record = &Record;
775   return getValueProfDataSize(&Closure);
776 }
777 
778 // Wrapper implementation using the closure mechanism.
779 std::unique_ptr<ValueProfData>
serializeFrom(const InstrProfRecord & Record)780 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
781   InstrProfRecordClosure.Record = &Record;
782 
783   std::unique_ptr<ValueProfData> VPD(
784       serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
785   return VPD;
786 }
787 
deserializeTo(InstrProfRecord & Record,InstrProfSymtab * SymTab)788 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
789                                     InstrProfSymtab *SymTab) {
790   Record.reserveSites(Kind, NumValueSites);
791 
792   InstrProfValueData *ValueData = getValueProfRecordValueData(this);
793   for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
794     uint8_t ValueDataCount = this->SiteCountArray[VSite];
795     Record.addValueData(Kind, VSite, ValueData, ValueDataCount, SymTab);
796     ValueData += ValueDataCount;
797   }
798 }
799 
800 // For writing/serializing,  Old is the host endianness, and  New is
801 // byte order intended on disk. For Reading/deserialization, Old
802 // is the on-disk source endianness, and New is the host endianness.
swapBytes(support::endianness Old,support::endianness New)803 void ValueProfRecord::swapBytes(support::endianness Old,
804                                 support::endianness New) {
805   using namespace support;
806 
807   if (Old == New)
808     return;
809 
810   if (getHostEndianness() != Old) {
811     sys::swapByteOrder<uint32_t>(NumValueSites);
812     sys::swapByteOrder<uint32_t>(Kind);
813   }
814   uint32_t ND = getValueProfRecordNumValueData(this);
815   InstrProfValueData *VD = getValueProfRecordValueData(this);
816 
817   // No need to swap byte array: SiteCountArrray.
818   for (uint32_t I = 0; I < ND; I++) {
819     sys::swapByteOrder<uint64_t>(VD[I].Value);
820     sys::swapByteOrder<uint64_t>(VD[I].Count);
821   }
822   if (getHostEndianness() == Old) {
823     sys::swapByteOrder<uint32_t>(NumValueSites);
824     sys::swapByteOrder<uint32_t>(Kind);
825   }
826 }
827 
deserializeTo(InstrProfRecord & Record,InstrProfSymtab * SymTab)828 void ValueProfData::deserializeTo(InstrProfRecord &Record,
829                                   InstrProfSymtab *SymTab) {
830   if (NumValueKinds == 0)
831     return;
832 
833   ValueProfRecord *VR = getFirstValueProfRecord(this);
834   for (uint32_t K = 0; K < NumValueKinds; K++) {
835     VR->deserializeTo(Record, SymTab);
836     VR = getValueProfRecordNext(VR);
837   }
838 }
839 
840 template <class T>
swapToHostOrder(const unsigned char * & D,support::endianness Orig)841 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
842   using namespace support;
843 
844   if (Orig == little)
845     return endian::readNext<T, little, unaligned>(D);
846   else
847     return endian::readNext<T, big, unaligned>(D);
848 }
849 
allocValueProfData(uint32_t TotalSize)850 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
851   return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
852                                             ValueProfData());
853 }
854 
checkIntegrity()855 Error ValueProfData::checkIntegrity() {
856   if (NumValueKinds > IPVK_Last + 1)
857     return make_error<InstrProfError>(instrprof_error::malformed);
858   // Total size needs to be mulltiple of quadword size.
859   if (TotalSize % sizeof(uint64_t))
860     return make_error<InstrProfError>(instrprof_error::malformed);
861 
862   ValueProfRecord *VR = getFirstValueProfRecord(this);
863   for (uint32_t K = 0; K < this->NumValueKinds; K++) {
864     if (VR->Kind > IPVK_Last)
865       return make_error<InstrProfError>(instrprof_error::malformed);
866     VR = getValueProfRecordNext(VR);
867     if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
868       return make_error<InstrProfError>(instrprof_error::malformed);
869   }
870   return Error::success();
871 }
872 
873 Expected<std::unique_ptr<ValueProfData>>
getValueProfData(const unsigned char * D,const unsigned char * const BufferEnd,support::endianness Endianness)874 ValueProfData::getValueProfData(const unsigned char *D,
875                                 const unsigned char *const BufferEnd,
876                                 support::endianness Endianness) {
877   using namespace support;
878 
879   if (D + sizeof(ValueProfData) > BufferEnd)
880     return make_error<InstrProfError>(instrprof_error::truncated);
881 
882   const unsigned char *Header = D;
883   uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
884   if (D + TotalSize > BufferEnd)
885     return make_error<InstrProfError>(instrprof_error::too_large);
886 
887   std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
888   memcpy(VPD.get(), D, TotalSize);
889   // Byte swap.
890   VPD->swapBytesToHost(Endianness);
891 
892   Error E = VPD->checkIntegrity();
893   if (E)
894     return std::move(E);
895 
896   return std::move(VPD);
897 }
898 
swapBytesToHost(support::endianness Endianness)899 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
900   using namespace support;
901 
902   if (Endianness == getHostEndianness())
903     return;
904 
905   sys::swapByteOrder<uint32_t>(TotalSize);
906   sys::swapByteOrder<uint32_t>(NumValueKinds);
907 
908   ValueProfRecord *VR = getFirstValueProfRecord(this);
909   for (uint32_t K = 0; K < NumValueKinds; K++) {
910     VR->swapBytes(Endianness, getHostEndianness());
911     VR = getValueProfRecordNext(VR);
912   }
913 }
914 
swapBytesFromHost(support::endianness Endianness)915 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
916   using namespace support;
917 
918   if (Endianness == getHostEndianness())
919     return;
920 
921   ValueProfRecord *VR = getFirstValueProfRecord(this);
922   for (uint32_t K = 0; K < NumValueKinds; K++) {
923     ValueProfRecord *NVR = getValueProfRecordNext(VR);
924     VR->swapBytes(getHostEndianness(), Endianness);
925     VR = NVR;
926   }
927   sys::swapByteOrder<uint32_t>(TotalSize);
928   sys::swapByteOrder<uint32_t>(NumValueKinds);
929 }
930 
annotateValueSite(Module & M,Instruction & Inst,const InstrProfRecord & InstrProfR,InstrProfValueKind ValueKind,uint32_t SiteIdx,uint32_t MaxMDCount)931 void annotateValueSite(Module &M, Instruction &Inst,
932                        const InstrProfRecord &InstrProfR,
933                        InstrProfValueKind ValueKind, uint32_t SiteIdx,
934                        uint32_t MaxMDCount) {
935   uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
936   if (!NV)
937     return;
938 
939   uint64_t Sum = 0;
940   std::unique_ptr<InstrProfValueData[]> VD =
941       InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
942 
943   ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
944   annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
945 }
946 
annotateValueSite(Module & M,Instruction & Inst,ArrayRef<InstrProfValueData> VDs,uint64_t Sum,InstrProfValueKind ValueKind,uint32_t MaxMDCount)947 void annotateValueSite(Module &M, Instruction &Inst,
948                        ArrayRef<InstrProfValueData> VDs,
949                        uint64_t Sum, InstrProfValueKind ValueKind,
950                        uint32_t MaxMDCount) {
951   LLVMContext &Ctx = M.getContext();
952   MDBuilder MDHelper(Ctx);
953   SmallVector<Metadata *, 3> Vals;
954   // Tag
955   Vals.push_back(MDHelper.createString("VP"));
956   // Value Kind
957   Vals.push_back(MDHelper.createConstant(
958       ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
959   // Total Count
960   Vals.push_back(
961       MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
962 
963   // Value Profile Data
964   uint32_t MDCount = MaxMDCount;
965   for (auto &VD : VDs) {
966     Vals.push_back(MDHelper.createConstant(
967         ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
968     Vals.push_back(MDHelper.createConstant(
969         ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
970     if (--MDCount == 0)
971       break;
972   }
973   Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
974 }
975 
getValueProfDataFromInst(const Instruction & Inst,InstrProfValueKind ValueKind,uint32_t MaxNumValueData,InstrProfValueData ValueData[],uint32_t & ActualNumValueData,uint64_t & TotalC)976 bool getValueProfDataFromInst(const Instruction &Inst,
977                               InstrProfValueKind ValueKind,
978                               uint32_t MaxNumValueData,
979                               InstrProfValueData ValueData[],
980                               uint32_t &ActualNumValueData, uint64_t &TotalC) {
981   MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
982   if (!MD)
983     return false;
984 
985   unsigned NOps = MD->getNumOperands();
986 
987   if (NOps < 5)
988     return false;
989 
990   // Operand 0 is a string tag "VP":
991   MDString *Tag = cast<MDString>(MD->getOperand(0));
992   if (!Tag)
993     return false;
994 
995   if (!Tag->getString().equals("VP"))
996     return false;
997 
998   // Now check kind:
999   ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
1000   if (!KindInt)
1001     return false;
1002   if (KindInt->getZExtValue() != ValueKind)
1003     return false;
1004 
1005   // Get total count
1006   ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
1007   if (!TotalCInt)
1008     return false;
1009   TotalC = TotalCInt->getZExtValue();
1010 
1011   ActualNumValueData = 0;
1012 
1013   for (unsigned I = 3; I < NOps; I += 2) {
1014     if (ActualNumValueData >= MaxNumValueData)
1015       break;
1016     ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
1017     ConstantInt *Count =
1018         mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
1019     if (!Value || !Count)
1020       return false;
1021     ValueData[ActualNumValueData].Value = Value->getZExtValue();
1022     ValueData[ActualNumValueData].Count = Count->getZExtValue();
1023     ActualNumValueData++;
1024   }
1025   return true;
1026 }
1027 
getPGOFuncNameMetadata(const Function & F)1028 MDNode *getPGOFuncNameMetadata(const Function &F) {
1029   return F.getMetadata(getPGOFuncNameMetadataName());
1030 }
1031 
createPGOFuncNameMetadata(Function & F,StringRef PGOFuncName)1032 void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
1033   // Only for internal linkage functions.
1034   if (PGOFuncName == F.getName())
1035       return;
1036   // Don't create duplicated meta-data.
1037   if (getPGOFuncNameMetadata(F))
1038     return;
1039   LLVMContext &C = F.getContext();
1040   MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
1041   F.setMetadata(getPGOFuncNameMetadataName(), N);
1042 }
1043 
needsComdatForCounter(const Function & F,const Module & M)1044 bool needsComdatForCounter(const Function &F, const Module &M) {
1045   if (F.hasComdat())
1046     return true;
1047 
1048   if (!Triple(M.getTargetTriple()).supportsCOMDAT())
1049     return false;
1050 
1051   // See createPGOFuncNameVar for more details. To avoid link errors, profile
1052   // counters for function with available_externally linkage needs to be changed
1053   // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
1054   // created. Without using comdat, duplicate entries won't be removed by the
1055   // linker leading to increased data segement size and raw profile size. Even
1056   // worse, since the referenced counter from profile per-function data object
1057   // will be resolved to the common strong definition, the profile counts for
1058   // available_externally functions will end up being duplicated in raw profile
1059   // data. This can result in distorted profile as the counts of those dups
1060   // will be accumulated by the profile merger.
1061   GlobalValue::LinkageTypes Linkage = F.getLinkage();
1062   if (Linkage != GlobalValue::ExternalWeakLinkage &&
1063       Linkage != GlobalValue::AvailableExternallyLinkage)
1064     return false;
1065 
1066   return true;
1067 }
1068 
1069 // Check if INSTR_PROF_RAW_VERSION_VAR is defined.
isIRPGOFlagSet(const Module * M)1070 bool isIRPGOFlagSet(const Module *M) {
1071   auto IRInstrVar =
1072       M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1073   if (!IRInstrVar || IRInstrVar->isDeclaration() ||
1074       IRInstrVar->hasLocalLinkage())
1075     return false;
1076 
1077   // Check if the flag is set.
1078   if (!IRInstrVar->hasInitializer())
1079     return false;
1080 
1081   auto *InitVal = dyn_cast_or_null<ConstantInt>(IRInstrVar->getInitializer());
1082   if (!InitVal)
1083     return false;
1084   return (InitVal->getZExtValue() & VARIANT_MASK_IR_PROF) != 0;
1085 }
1086 
1087 // Check if we can safely rename this Comdat function.
canRenameComdatFunc(const Function & F,bool CheckAddressTaken)1088 bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
1089   if (F.getName().empty())
1090     return false;
1091   if (!needsComdatForCounter(F, *(F.getParent())))
1092     return false;
1093   // Unsafe to rename the address-taken function (which can be used in
1094   // function comparison).
1095   if (CheckAddressTaken && F.hasAddressTaken())
1096     return false;
1097   // Only safe to do if this function may be discarded if it is not used
1098   // in the compilation unit.
1099   if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
1100     return false;
1101 
1102   // For AvailableExternallyLinkage functions.
1103   if (!F.hasComdat()) {
1104     assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
1105     return true;
1106   }
1107   return true;
1108 }
1109 
1110 // Parse the value profile options.
getMemOPSizeRangeFromOption(StringRef MemOPSizeRange,int64_t & RangeStart,int64_t & RangeLast)1111 void getMemOPSizeRangeFromOption(StringRef MemOPSizeRange, int64_t &RangeStart,
1112                                  int64_t &RangeLast) {
1113   static const int64_t DefaultMemOPSizeRangeStart = 0;
1114   static const int64_t DefaultMemOPSizeRangeLast = 8;
1115   RangeStart = DefaultMemOPSizeRangeStart;
1116   RangeLast = DefaultMemOPSizeRangeLast;
1117 
1118   if (!MemOPSizeRange.empty()) {
1119     auto Pos = MemOPSizeRange.find(':');
1120     if (Pos != std::string::npos) {
1121       if (Pos > 0)
1122         MemOPSizeRange.substr(0, Pos).getAsInteger(10, RangeStart);
1123       if (Pos < MemOPSizeRange.size() - 1)
1124         MemOPSizeRange.substr(Pos + 1).getAsInteger(10, RangeLast);
1125     } else
1126       MemOPSizeRange.getAsInteger(10, RangeLast);
1127   }
1128   assert(RangeLast >= RangeStart);
1129 }
1130 
1131 // Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
1132 // aware this is an ir_level profile so it can set the version flag.
createIRLevelProfileFlagVar(Module & M,bool IsCS)1133 void createIRLevelProfileFlagVar(Module &M, bool IsCS) {
1134   const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1135   Type *IntTy64 = Type::getInt64Ty(M.getContext());
1136   uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
1137   if (IsCS)
1138     ProfileVersion |= VARIANT_MASK_CSIR_PROF;
1139   auto IRLevelVersionVariable = new GlobalVariable(
1140       M, IntTy64, true, GlobalValue::WeakAnyLinkage,
1141       Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)), VarName);
1142   IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility);
1143   Triple TT(M.getTargetTriple());
1144   if (TT.supportsCOMDAT()) {
1145     IRLevelVersionVariable->setLinkage(GlobalValue::ExternalLinkage);
1146     IRLevelVersionVariable->setComdat(M.getOrInsertComdat(VarName));
1147   }
1148 }
1149 
1150 // Create the variable for the profile file name.
createProfileFileNameVar(Module & M,StringRef InstrProfileOutput)1151 void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput) {
1152   if (InstrProfileOutput.empty())
1153     return;
1154   Constant *ProfileNameConst =
1155       ConstantDataArray::getString(M.getContext(), InstrProfileOutput, true);
1156   GlobalVariable *ProfileNameVar = new GlobalVariable(
1157       M, ProfileNameConst->getType(), true, GlobalValue::WeakAnyLinkage,
1158       ProfileNameConst, INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR));
1159   Triple TT(M.getTargetTriple());
1160   if (TT.supportsCOMDAT()) {
1161     ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
1162     ProfileNameVar->setComdat(M.getOrInsertComdat(
1163         StringRef(INSTR_PROF_QUOTE(INSTR_PROF_PROFILE_NAME_VAR))));
1164   }
1165 }
1166 
accumulateCounts(const std::string & BaseFilename,const std::string & TestFilename,bool IsCS)1167 Error OverlapStats::accumulateCounts(const std::string &BaseFilename,
1168                                      const std::string &TestFilename,
1169                                      bool IsCS) {
1170   auto getProfileSum = [IsCS](const std::string &Filename,
1171                               CountSumOrPercent &Sum) -> Error {
1172     auto ReaderOrErr = InstrProfReader::create(Filename);
1173     if (Error E = ReaderOrErr.takeError()) {
1174       return E;
1175     }
1176     auto Reader = std::move(ReaderOrErr.get());
1177     Reader->accumulateCounts(Sum, IsCS);
1178     return Error::success();
1179   };
1180   auto Ret = getProfileSum(BaseFilename, Base);
1181   if (Ret)
1182     return Ret;
1183   Ret = getProfileSum(TestFilename, Test);
1184   if (Ret)
1185     return Ret;
1186   this->BaseFilename = &BaseFilename;
1187   this->TestFilename = &TestFilename;
1188   Valid = true;
1189   return Error::success();
1190 }
1191 
addOneMismatch(const CountSumOrPercent & MismatchFunc)1192 void OverlapStats::addOneMismatch(const CountSumOrPercent &MismatchFunc) {
1193   Mismatch.NumEntries += 1;
1194   Mismatch.CountSum += MismatchFunc.CountSum / Test.CountSum;
1195   for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1196     if (Test.ValueCounts[I] >= 1.0f)
1197       Mismatch.ValueCounts[I] +=
1198           MismatchFunc.ValueCounts[I] / Test.ValueCounts[I];
1199   }
1200 }
1201 
addOneUnique(const CountSumOrPercent & UniqueFunc)1202 void OverlapStats::addOneUnique(const CountSumOrPercent &UniqueFunc) {
1203   Unique.NumEntries += 1;
1204   Unique.CountSum += UniqueFunc.CountSum / Test.CountSum;
1205   for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1206     if (Test.ValueCounts[I] >= 1.0f)
1207       Unique.ValueCounts[I] += UniqueFunc.ValueCounts[I] / Test.ValueCounts[I];
1208   }
1209 }
1210 
dump(raw_fd_ostream & OS) const1211 void OverlapStats::dump(raw_fd_ostream &OS) const {
1212   if (!Valid)
1213     return;
1214 
1215   const char *EntryName =
1216       (Level == ProgramLevel ? "functions" : "edge counters");
1217   if (Level == ProgramLevel) {
1218     OS << "Profile overlap infomation for base_profile: " << *BaseFilename
1219        << " and test_profile: " << *TestFilename << "\nProgram level:\n";
1220   } else {
1221     OS << "Function level:\n"
1222        << "  Function: " << FuncName << " (Hash=" << FuncHash << ")\n";
1223   }
1224 
1225   OS << "  # of " << EntryName << " overlap: " << Overlap.NumEntries << "\n";
1226   if (Mismatch.NumEntries)
1227     OS << "  # of " << EntryName << " mismatch: " << Mismatch.NumEntries
1228        << "\n";
1229   if (Unique.NumEntries)
1230     OS << "  # of " << EntryName
1231        << " only in test_profile: " << Unique.NumEntries << "\n";
1232 
1233   OS << "  Edge profile overlap: " << format("%.3f%%", Overlap.CountSum * 100)
1234      << "\n";
1235   if (Mismatch.NumEntries)
1236     OS << "  Mismatched count percentage (Edge): "
1237        << format("%.3f%%", Mismatch.CountSum * 100) << "\n";
1238   if (Unique.NumEntries)
1239     OS << "  Percentage of Edge profile only in test_profile: "
1240        << format("%.3f%%", Unique.CountSum * 100) << "\n";
1241   OS << "  Edge profile base count sum: " << format("%.0f", Base.CountSum)
1242      << "\n"
1243      << "  Edge profile test count sum: " << format("%.0f", Test.CountSum)
1244      << "\n";
1245 
1246   for (unsigned I = 0; I < IPVK_Last - IPVK_First + 1; I++) {
1247     if (Base.ValueCounts[I] < 1.0f && Test.ValueCounts[I] < 1.0f)
1248       continue;
1249     char ProfileKindName[20];
1250     switch (I) {
1251     case IPVK_IndirectCallTarget:
1252       strncpy(ProfileKindName, "IndirectCall", 19);
1253       break;
1254     case IPVK_MemOPSize:
1255       strncpy(ProfileKindName, "MemOP", 19);
1256       break;
1257     default:
1258       snprintf(ProfileKindName, 19, "VP[%d]", I);
1259       break;
1260     }
1261     OS << "  " << ProfileKindName
1262        << " profile overlap: " << format("%.3f%%", Overlap.ValueCounts[I] * 100)
1263        << "\n";
1264     if (Mismatch.NumEntries)
1265       OS << "  Mismatched count percentage (" << ProfileKindName
1266          << "): " << format("%.3f%%", Mismatch.ValueCounts[I] * 100) << "\n";
1267     if (Unique.NumEntries)
1268       OS << "  Percentage of " << ProfileKindName
1269          << " profile only in test_profile: "
1270          << format("%.3f%%", Unique.ValueCounts[I] * 100) << "\n";
1271     OS << "  " << ProfileKindName
1272        << " profile base count sum: " << format("%.0f", Base.ValueCounts[I])
1273        << "\n"
1274        << "  " << ProfileKindName
1275        << " profile test count sum: " << format("%.0f", Test.ValueCounts[I])
1276        << "\n";
1277   }
1278 }
1279 
1280 } // end namespace llvm
1281