LLVM  10.0.0svn
InstrProf.cpp
Go to the documentation of this file.
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 
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"
33 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Endian.h"
38 #include "llvm/Support/Error.h"
40 #include "llvm/Support/LEB128.h"
43 #include "llvm/Support/Path.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 
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.
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 
76 static std::string getInstrProfErrString(instrprof_error Err) {
77  switch (Err) {
79  return "Success";
81  return "End of File";
83  return "Unrecognized instrumentation profile encoding format";
85  return "Invalid instrumentation profile data (bad magic)";
87  return "Invalid instrumentation profile data (file header is corrupt)";
89  return "Unsupported instrumentation profile format version";
91  return "Unsupported instrumentation profile hash type";
93  return "Too much profile data";
95  return "Truncated profile data";
97  return "Malformed instrumentation profile data";
99  return "No profile data available for function";
101  return "Function control flow change detected (hash mismatch)";
103  return "Function basic block count change detected (counter mismatch)";
105  return "Counter overflow";
107  return "Function value site count change detected (counter mismatch)";
109  return "Failed to compress data (zlib)";
111  return "Failed to uncompress data (zlib)";
113  return "Empty raw profile file";
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 {
126  const char *name() const noexcept override { return "llvm.instrprof"; }
127 
128  std::string message(int IE) const override {
129  return getInstrProfErrString(static_cast<instrprof_error>(IE));
130  }
131 };
132 
133 } // end anonymous namespace
134 
136 
138  return *ErrorCategory;
139 }
140 
141 namespace {
142 
143 const char *InstrProfSectNameCommon[] = {
144 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
145  SectNameCommon,
147 };
148 
149 const char *InstrProfSectNameCoff[] = {
150 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
151  SectNameCoff,
153 };
154 
155 const char *InstrProfSectNamePrefix[] = {
156 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
157  Prefix,
159 };
160 
161 } // namespace
162 
163 namespace llvm {
164 
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 
185  if (IE == instrprof_error::success)
186  return;
187 
188  if (FirstError == instrprof_error::success)
189  FirstError = IE;
190 
191  switch (IE) {
193  ++NumHashMismatches;
194  break;
196  ++NumCountMismatches;
197  break;
199  ++NumCounterOverflows;
200  break;
202  ++NumValueSiteCountMismatches;
203  break;
204  default:
205  llvm_unreachable("Not a soft error");
206  }
207 }
208 
209 std::string InstrProfError::message() const {
210  return getInstrProfErrString(Err);
211 }
212 
213 char InstrProfError::ID = 0;
214 
215 std::string getPGOFuncName(StringRef RawFuncName,
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.
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;
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.
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.
274 }
275 
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.
287 std::string getPGOFuncNameVarName(StringRef FuncName,
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 
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)
313  else if (Linkage == GlobalValue::AvailableExternallyLinkage)
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()))
328 
329  return FuncNameVar;
330 }
331 
333  return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
334 }
335 
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 
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 
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 
420  auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
421  StringRef NameStr =
422  Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
423  return NameStr;
424 }
425 
427  std::string &Result, bool doCompression) {
428  std::vector<std::string> NameStrs;
429  for (auto *NameVar : NameVars) {
430  NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
431  }
433  NameStrs, zlib::isAvailable() && doCompression, Result);
434 }
435 
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) {
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.
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 
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 
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.
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);
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 
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 
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)
617  ++I;
618  continue;
619  }
620  ValueData.insert(I, *J);
621  }
622 }
623 
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)
631  }
632 }
633 
634 // Merge Value Profile data from Src record to this record for ValueKind.
635 // Scale merged value counts by \p Weight.
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) {
643  return;
644  }
645  if (!ThisNumValueSites)
646  return;
647  std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
648  getOrCreateValueSitesForKind(ValueKind);
650  Src.getValueSitesForKind(ValueKind);
651  for (uint32_t I = 0; I < ThisNumValueSites; I++)
652  ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn);
653 }
654 
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()) {
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)
670  }
671 
672  for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
673  mergeValueProfData(Kind, Other, Weight, Warn);
674 }
675 
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 
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)
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.
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 
708  InstrProfValueData *VData, uint32_t N,
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
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  */
730  return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
731 }
732 
734  return reinterpret_cast<const InstrProfRecord *>(Record)
735  ->getNumValueSites(VKind);
736 }
737 
739  return reinterpret_cast<const InstrProfRecord *>(Record)
740  ->getNumValueData(VKind);
741 }
742 
744  uint32_t S) {
745  return reinterpret_cast<const InstrProfRecord *>(R)
746  ->getNumValueDataForSite(VK, S);
747 }
748 
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 
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,
767  nullptr,
770 
771 // Wrapper implementation using the closure mechanism.
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>
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 
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.
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 
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>
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 
850 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
851  return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
852  ValueProfData());
853 }
854 
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 
874 ValueProfData::getValueProfData(const unsigned char *D,
875  const unsigned char *const BufferEnd,
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 
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 
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 
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 
949  uint64_t Sum, InstrProfValueKind ValueKind,
950  uint32_t MaxMDCount) {
951  LLVMContext &Ctx = M.getContext();
952  MDBuilder MDHelper(Ctx);
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 
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 
1030 }
1031 
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));
1042 }
1043 
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.
1062  if (Linkage != GlobalValue::ExternalWeakLinkage &&
1064  return false;
1065 
1066  return true;
1067 }
1068 
1069 // Check if INSTR_PROF_RAW_VERSION_VAR is defined.
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.
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.
1100  return false;
1101 
1102  // For AvailableExternallyLinkage functions.
1103  if (!F.hasComdat()) {
1105  return true;
1106  }
1107  return true;
1108 }
1109 
1110 // Parse the value profile options.
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.
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.
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 
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 
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 
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 
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
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:242
void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst, uint32_t K, uint32_t S)
Definition: InstrProf.cpp:749
cl::opt< std::string > MemOPSizeRange("memop-size-range", cl::desc("Set the range of size in memory intrinsic calls to be profiled " "precisely, in a format of <start_val>:<end_val>"), cl::init(""))
uint64_t CallInst * C
void overlap(InstrProfRecord &Other, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap, uint64_t ValueCutoff)
Compute the overlap b/w this IntrprofRecord and Other.
Definition: InstrProf.cpp:550
bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
Definition: Path.cpp:593
void addOneMismatch(const CountSumOrPercent &MismatchFunc)
Definition: InstrProf.cpp:1192
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:241
A symbol table used for function PGO name look-up with keys (such as pointers, md5hash values) to the...
Definition: InstrProf.h:406
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2579
void merge(InstrProfRecord &Other, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge the counts in Other into this one.
Definition: InstrProf.cpp:655
static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix)
Definition: InstrProf.cpp:225
CountSumOrPercent Base
Definition: InstrProf.h:608
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:232
DiagnosticInfoOptimizationBase::Argument NV
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
Definition: InstrProf.h:82
uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind)
Definition: InstrProf.cpp:738
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
const unsigned char * bytes_end() const
Definition: StringRef.h:122
ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
Definition: MDBuilder.cpp:24
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
iterator begin() const
Definition: ArrayRef.h:136
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
void addValueData(uint32_t ValueKind, uint32_t Site, InstrProfValueData *VData, uint32_t N, InstrProfSymtab *SymTab)
Add ValueData for ValueKind at value Site.
Definition: InstrProf.cpp:707
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:453
uint32_t getNumValueDataForSite(uint32_t ValueKind, uint32_t Site) const
Return the number of value data collected for ValueKind at profiling site: Site.
Definition: InstrProf.h:880
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:270
Available for inspection, not emission.
Definition: GlobalValue.h:49
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
Definition: InstrProf.cpp:1088
This file contains the declarations for metadata subclasses.
MDNode * getPGOFuncNameMetadata(const Function &F)
Return the PGOFuncName meta data associated with a function.
Definition: InstrProf.cpp:1028
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:104
const GlobalVariable * getNamedGlobal(StringRef Name) const
Return the global variable in the module with the specified name, of arbitrary type.
Definition: Module.h:406
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:56
Externally visible function.
Definition: GlobalValue.h:48
constexpr support::endianness Endianness
The endianness of all multi-byte encoded values in MessagePack.
Definition: MsgPack.h:24
static std::unique_ptr< ValueProfData > allocValueProfData(uint32_t TotalSize)
Definition: InstrProf.cpp:850
static T swapToHostOrder(const unsigned char *&D, support::endianness Orig)
Definition: InstrProf.cpp:841
Metadata node.
Definition: Metadata.h:863
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
Definition: InstrProf.cpp:165
F(f)
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1068
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:181
static double score(uint64_t Val1, uint64_t Val2, double Sum1, double Sum2)
Definition: InstrProf.h:638
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e...
Definition: Globals.cpp:160
std::enable_if< std::is_unsigned< T >::value, T >::type SaturatingMultiply(T X, T Y, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, of type T.
Definition: MathExtras.h:805
void reserveSites(uint32_t ValueKind, uint32_t NumValueSites)
Reserve space for NumValueSites sites.
Definition: InstrProf.h:916
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
Definition: InstrProf.h:876
static bool isLocalLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:330
uint32_t getNumValueKindsInstrProf(const void *Record)
ValueProfRecordClosure Interface implementation for InstrProfRecord class.
Definition: InstrProf.cpp:729
void overlap(InstrProfValueSiteRecord &Input, uint32_t ValueKind, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap b/w this record and Input record.
Definition: InstrProf.cpp:501
void merge(InstrProfValueSiteRecord &Input, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge data from another InstrProfValueSiteRecord Optionally scale merged counts by Weight...
Definition: InstrProf.cpp:601
Error compress(StringRef InputBuffer, SmallVectorImpl< char > &CompressedBuffer, int Level=DefaultCompression)
Definition: Compression.cpp:49
static Expected< std::unique_ptr< InstrProfReader > > create(const Twine &Path)
Factory method to create an appropriately typed reader for the given instrprof file.
void overlapValueProfData(uint32_t ValueKind, InstrProfRecord &Src, OverlapStats &Overlap, OverlapStats &FuncLevelOverlap)
Compute the overlap of value profile counts.
Definition: InstrProf.cpp:532
LLVM_NODISCARD StringRef drop_front(size_t N=1) const
Return a StringRef equal to &#39;this&#39; but with the first N elements dropped.
Definition: StringRef.h:634
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:245
void scale(uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Scale up profile counts (including value profile data) by Weight.
Definition: InstrProf.cpp:683
const std::error_category & instrprof_category()
Definition: InstrProf.cpp:137
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Metadata.cpp:1440
InstrProfValueKind
Definition: InstrProf.h:232
Error collectPGOFuncNameStrings(ArrayRef< std::string > NameStrs, bool doCompression, std::string &Result)
Given a vector of strings (function PGO names) NameStrs, the method generates a combined string Resul...
Definition: InstrProf.cpp:378
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
Definition: StringExtras.h:370
Tagged union holding either a T or a Error.
Definition: yaml2obj.h:21
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:592
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:140
InstrProfSectKind
Definition: InstrProf.h:56
auto partition_point(R &&Range, Predicate P) -> decltype(adl_begin(Range))
Binary search for the first iterator in a range where a predicate is false.
Definition: STLExtras.h:1302
StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name...
Definition: InstrProf.cpp:276
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:244
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
StringRef getInstrProfNameSeparator()
Return the marker used to separate PGO names during serialization.
Definition: InstrProf.h:157
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:144
void addError(instrprof_error IE)
Track a soft error (IE) and increment its associated counter.
Definition: InstrProf.cpp:184
LinkageTypes getLinkage() const
Definition: GlobalValue.h:460
static constexpr int BestSizeCompression
Definition: Compression.h:28
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:1231
const std::string & getSourceFileName() const
Get the module&#39;s original source file name.
Definition: Module.h:222
bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
Definition: InstrProf.cpp:1070
static cl::opt< bool > StaticFuncFullModulePrefix("static-func-full-module-prefix", cl::init(true), cl::Hidden, cl::desc("Use full module build paths in the profile counter names for " "static functions."))
static ManagedStatic< InstrProfErrorCategoryType > ErrorCategory
Definition: InstrProf.cpp:135
std::string message() const override
Return the error message as a string.
Definition: InstrProf.cpp:209
StringRef getString() const
Definition: Metadata.cpp:463
ExternalWeak linkage description.
Definition: GlobalValue.h:57
uint64_t getFunctionHashFromAddress(uint64_t Address)
Return a function&#39;s hash, or 0, if the function isn&#39;t in this SymTab.
Definition: InstrProf.cpp:364
void getMemOPSizeRangeFromOption(StringRef Str, int64_t &RangeStart, int64_t &RangeLast)
Definition: InstrProf.cpp:1111
Error accumulateCounts(const std::string &BaseFilename, const std::string &TestFilename, bool IsCS)
Definition: InstrProf.cpp:1167
bool needsComdatForCounter(const Function &F, const Module &M)
Check if we can use Comdat for profile variables.
Definition: InstrProf.cpp:1044
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1165
bool isAvailable()
Definition: Compression.cpp:47
#define P(N)
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:51
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:432
bool getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, InstrProfValueData ValueData[], uint32_t &ActualNumValueData, uint64_t &TotalC)
Extract the value profile data from Inst which is annotated with value profile meta data...
Definition: InstrProf.cpp:976
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:148
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:290
void scale(uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Scale up value profile data counts.
Definition: InstrProf.cpp:624
std::string getPGOFuncNameVarName(StringRef FuncName, GlobalValue::LinkageTypes Linkage)
Return the name of the global variable used to store a function name in PGO instrumentation.
Definition: InstrProf.cpp:287
void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
Definition: InstrProf.cpp:1151
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:64
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:148
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
ValueKind
Value kinds.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static ValueProfRecordClosure InstrProfRecordClosure
Definition: InstrProf.cpp:761
ValueProfData * allocValueProfDataInstrProf(size_t TotalSizeInBytes)
Definition: InstrProf.cpp:754
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:299
static ManagedStatic< _object_error_category > error_category
Definition: Error.cpp:74
uint64_t decodeULEB128(const uint8_t *p, unsigned *n=nullptr, const uint8_t *end=nullptr, const char **error=nullptr)
Utility function to decode a ULEB128 value.
Definition: LEB128.h:128
#define LLVM_ATTRIBUTE_UNUSED
Definition: Compiler.h:180
std::list< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
Definition: InstrProf.h:655
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:205
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition: Module.cpp:482
void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
Definition: InstrProf.cpp:931
Value(Type *Ty, unsigned scid)
Definition: Value.cpp:52
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1001
size_t size() const
Definition: SmallVector.h:52
void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function&#39;s raw name.
Definition: InstrProf.cpp:1032
Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab)
NameStrings is a string composed of one of more sub-strings encoded in the format described above...
Definition: InstrProf.cpp:436
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1222
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
static Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
Definition: Constants.cpp:326
bool isDiscardableIfUnused() const
Definition: GlobalValue.h:462
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:492
std::enable_if< std::is_unsigned< T >::value, T >::type SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, and add the unsigned integer, A to the product.
Definition: MathExtras.h:851
void addOneUnique(const CountSumOrPercent &UniqueFunc)
Definition: InstrProf.cpp:1202
CountSumOrPercent Test
Definition: InstrProf.h:610
Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
static ErrorSuccess success()
Create a success value.
Definition: Error.h:326
See the file comment.
Definition: ValueMap.h:85
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:390
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:80
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:50
Module.h This file contains the declarations for the Module class.
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:710
iterator end() const
Definition: ArrayRef.h:137
static cl::opt< unsigned > StaticFuncStripDirNamePrefix("static-func-strip-dirname-prefix", cl::init(0), cl::Hidden, cl::desc("Strip specified level of directory name from source path in " "the profile counter name for static functions."))
static std::string getInstrProfErrString(instrprof_error Err)
Definition: InstrProf.cpp:76
StringRef getPGOFuncNameMetadataName()
Definition: InstrProf.h:259
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:653
Class for arbitrary precision integers.
Definition: APInt.h:69
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:47
static char ID
Definition: InstrProf.h:328
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:510
CountSumOrPercent Overlap
Definition: InstrProf.h:612
void sortByTargetValues()
Sort ValueData ascending by Value.
Definition: InstrProf.h:663
bool hasComdat() const
Definition: GlobalObject.h:119
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
Definition: Metadata.cpp:1430
LLVM_NODISCARD bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
Definition: StringRef.h:174
std::vector< uint64_t > Counts
Definition: InstrProf.h:686
void dump(raw_fd_ostream &OS) const
Definition: InstrProf.cpp:1211
const unsigned char * bytes_begin() const
Definition: StringRef.h:119
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:384
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:144
Profiling information for a single function.
Definition: InstrProf.h:685
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:180
std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Return the modified name for function F suitable to be used the key for profile lookup.
Definition: InstrProf.cpp:253
instrprof_error
Definition: InstrProf.h:275
MDString * createString(StringRef Str)
Return the given string as metadata.
Definition: MDBuilder.cpp:20
Error addFuncName(StringRef FuncName)
Update the symtab by adding FuncName to the table.
Definition: InstrProf.h:467
void accumulateCounts(CountSumOrPercent &Sum) const
Compute the sums of all counts and store in Sum.
Definition: InstrProf.cpp:481
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
Definition: InstrProf.cpp:332
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:52
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
Definition: Function.cpp:1420
uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind)
Definition: InstrProf.cpp:733
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ObjectFormatType
Definition: Triple.h:221
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:575
LLVM Value Representation.
Definition: Value.h:74
static const char * name
void createIRLevelProfileFlagVar(Module &M, bool IsCS)
Definition: InstrProf.cpp:1133
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
support::endianness getHostEndianness()
Definition: InstrProf.h:922
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
A single uniqued string.
Definition: Metadata.h:603
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:83
std::unique_ptr< InstrProfValueData[]> getValueForSite(uint32_t ValueKind, uint32_t Site, uint64_t *TotalC=nullptr) const
Return the array of profiled values at Site.
Definition: InstrProf.h:886
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1074
uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK, uint32_t S)
Definition: InstrProf.cpp:743
Error uncompress(StringRef InputBuffer, char *UncompressedBuffer, size_t &UncompressedSize)
Definition: Compression.cpp:63
const uint64_t Version
Definition: InstrProf.h:980
StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
Definition: InstrProf.cpp:419
double ValueCounts[IPVK_Last - IPVK_First+1]
Definition: InstrProf.h:594
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:143