LLVM  8.0.0svn
InstrProf.cpp
Go to the documentation of this file.
1 //===- InstrProf.cpp - Instrumented profiling format support --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for clang's instrumentation based PGO and
11 // coverage.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/IR/Constant.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Instruction.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/MDBuilder.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/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) {
256  ? F.getParent()->getName()
259  FileName = stripDirPrefix(FileName, StaticFuncStripDirNamePrefix);
260  return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
261  }
262 
263  // In LTO mode (when InLTO is true), first check if there is a meta data.
264  if (MDNode *MD = getPGOFuncNameMetadata(F)) {
265  StringRef S = cast<MDString>(MD->getOperand(0))->getString();
266  return S.str();
267  }
268 
269  // If there is no meta data, the function must be a global before the value
270  // profile annotation pass. Its current linkage may be internal if it is
271  // internalized in LTO mode.
273 }
274 
276  if (FileName.empty())
277  return PGOFuncName;
278  // Drop the file name including ':'. See also getPGOFuncName.
279  if (PGOFuncName.startswith(FileName))
280  PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
281  return PGOFuncName;
282 }
283 
284 // \p FuncName is the string used as profile lookup key for the function. A
285 // symbol is created to hold the name. Return the legalized symbol name.
286 std::string getPGOFuncNameVarName(StringRef FuncName,
287  GlobalValue::LinkageTypes Linkage) {
288  std::string VarName = getInstrProfNameVarPrefix();
289  VarName += FuncName;
290 
291  if (!GlobalValue::isLocalLinkage(Linkage))
292  return VarName;
293 
294  // Now fix up illegal chars in local VarName that may upset the assembler.
295  const char *InvalidChars = "-:<>/\"'";
296  size_t found = VarName.find_first_of(InvalidChars);
297  while (found != std::string::npos) {
298  VarName[found] = '_';
299  found = VarName.find_first_of(InvalidChars, found + 1);
300  }
301  return VarName;
302 }
303 
306  StringRef PGOFuncName) {
307  // We generally want to match the function's linkage, but available_externally
308  // and extern_weak both have the wrong semantics, and anything that doesn't
309  // need to link across compilation units doesn't need to be visible at all.
310  if (Linkage == GlobalValue::ExternalWeakLinkage)
312  else if (Linkage == GlobalValue::AvailableExternallyLinkage)
314  else if (Linkage == GlobalValue::InternalLinkage ||
315  Linkage == GlobalValue::ExternalLinkage)
316  Linkage = GlobalValue::PrivateLinkage;
317 
318  auto *Value =
319  ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
320  auto FuncNameVar =
321  new GlobalVariable(M, Value->getType(), true, Linkage, Value,
322  getPGOFuncNameVarName(PGOFuncName, Linkage));
323 
324  // Hide the symbol so that we correctly get a copy for each executable.
325  if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
327 
328  return FuncNameVar;
329 }
330 
332  return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
333 }
334 
336  for (Function &F : M) {
337  // Function may not have a name: like using asm("") to overwrite the name.
338  // Ignore in this case.
339  if (!F.hasName())
340  continue;
341  const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
342  if (Error E = addFuncName(PGOFuncName))
343  return E;
344  MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
345  // In ThinLTO, local function may have been promoted to global and have
346  // suffix added to the function name. We need to add the stripped function
347  // name to the symbol table so that we can find a match from profile.
348  if (InLTO) {
349  auto pos = PGOFuncName.find('.');
350  if (pos != std::string::npos) {
351  const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
352  if (Error E = addFuncName(OtherFuncName))
353  return E;
354  MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F);
355  }
356  }
357  }
358  Sorted = false;
359  finalizeSymtab();
360  return Error::success();
361 }
362 
364  finalizeSymtab();
365  auto Result =
366  std::lower_bound(AddrToMD5Map.begin(), AddrToMD5Map.end(), Address,
367  [](const std::pair<uint64_t, uint64_t> &LHS,
368  uint64_t RHS) { return LHS.first < RHS; });
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 (Result != AddrToMD5Map.end() && Result->first == Address)
374  return (uint64_t)Result->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 = reinterpret_cast<const uint8_t *>(NameStrings.data());
438  const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
439  NameStrings.size());
440  while (P < EndP) {
441  uint32_t N;
442  uint64_t UncompressedSize = decodeULEB128(P, &N);
443  P += N;
444  uint64_t CompressedSize = decodeULEB128(P, &N);
445  P += N;
446  bool isCompressed = (CompressedSize != 0);
447  SmallString<128> UncompressedNameStrings;
448  StringRef NameStrings;
449  if (isCompressed) {
451  return make_error<InstrProfError>(instrprof_error::zlib_unavailable);
452 
453  StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
454  CompressedSize);
455  if (Error E =
456  zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
457  UncompressedSize)) {
458  consumeError(std::move(E));
459  return make_error<InstrProfError>(instrprof_error::uncompress_failed);
460  }
461  P += CompressedSize;
462  NameStrings = StringRef(UncompressedNameStrings.data(),
463  UncompressedNameStrings.size());
464  } else {
465  NameStrings =
466  StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
467  P += UncompressedSize;
468  }
469  // Now parse the name strings.
471  NameStrings.split(Names, getInstrProfNameSeparator());
472  for (StringRef &Name : Names)
473  if (Error E = Symtab.addFuncName(Name))
474  return E;
475 
476  while (P < EndP && *P == 0)
477  P++;
478  }
479  return Error::success();
480 }
481 
483  uint64_t Weight,
484  function_ref<void(instrprof_error)> Warn) {
485  this->sortByTargetValues();
486  Input.sortByTargetValues();
487  auto I = ValueData.begin();
488  auto IE = ValueData.end();
489  for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
490  ++J) {
491  while (I != IE && I->Value < J->Value)
492  ++I;
493  if (I != IE && I->Value == J->Value) {
494  bool Overflowed;
495  I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
496  if (Overflowed)
498  ++I;
499  continue;
500  }
501  ValueData.insert(I, *J);
502  }
503 }
504 
505 void InstrProfValueSiteRecord::scale(uint64_t Weight,
506  function_ref<void(instrprof_error)> Warn) {
507  for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
508  bool Overflowed;
509  I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
510  if (Overflowed)
512  }
513 }
514 
515 // Merge Value Profile data from Src record to this record for ValueKind.
516 // Scale merged value counts by \p Weight.
517 void InstrProfRecord::mergeValueProfData(
518  uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight,
519  function_ref<void(instrprof_error)> Warn) {
520  uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
521  uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
522  if (ThisNumValueSites != OtherNumValueSites) {
524  return;
525  }
526  if (!ThisNumValueSites)
527  return;
528  std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
529  getOrCreateValueSitesForKind(ValueKind);
531  Src.getValueSitesForKind(ValueKind);
532  for (uint32_t I = 0; I < ThisNumValueSites; I++)
533  ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn);
534 }
535 
536 void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight,
537  function_ref<void(instrprof_error)> Warn) {
538  // If the number of counters doesn't match we either have bad data
539  // or a hash collision.
540  if (Counts.size() != Other.Counts.size()) {
542  return;
543  }
544 
545  for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
546  bool Overflowed;
547  Counts[I] =
548  SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
549  if (Overflowed)
551  }
552 
553  for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
554  mergeValueProfData(Kind, Other, Weight, Warn);
555 }
556 
557 void InstrProfRecord::scaleValueProfData(
558  uint32_t ValueKind, uint64_t Weight,
559  function_ref<void(instrprof_error)> Warn) {
560  for (auto &R : getValueSitesForKind(ValueKind))
561  R.scale(Weight, Warn);
562 }
563 
564 void InstrProfRecord::scale(uint64_t Weight,
565  function_ref<void(instrprof_error)> Warn) {
566  for (auto &Count : this->Counts) {
567  bool Overflowed;
568  Count = SaturatingMultiply(Count, Weight, &Overflowed);
569  if (Overflowed)
571  }
572  for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
573  scaleValueProfData(Kind, Weight, Warn);
574 }
575 
576 // Map indirect call target name hash to name string.
577 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
578  InstrProfSymtab *SymTab) {
579  if (!SymTab)
580  return Value;
581 
582  if (ValueKind == IPVK_IndirectCallTarget)
583  return SymTab->getFunctionHashFromAddress(Value);
584 
585  return Value;
586 }
587 
589  InstrProfValueData *VData, uint32_t N,
591  for (uint32_t I = 0; I < N; I++) {
592  VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
593  }
594  std::vector<InstrProfValueSiteRecord> &ValueSites =
595  getOrCreateValueSitesForKind(ValueKind);
596  if (N == 0)
597  ValueSites.emplace_back();
598  else
599  ValueSites.emplace_back(VData, VData + N);
600 }
601 
602 #define INSTR_PROF_COMMON_API_IMPL
604 
605 /*!
606  * ValueProfRecordClosure Interface implementation for InstrProfRecord
607  * class. These C wrappers are used as adaptors so that C++ code can be
608  * invoked as callbacks.
609  */
611  return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
612 }
613 
615  return reinterpret_cast<const InstrProfRecord *>(Record)
616  ->getNumValueSites(VKind);
617 }
618 
620  return reinterpret_cast<const InstrProfRecord *>(Record)
621  ->getNumValueData(VKind);
622 }
623 
625  uint32_t S) {
626  return reinterpret_cast<const InstrProfRecord *>(R)
627  ->getNumValueDataForSite(VK, S);
628 }
629 
630 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
631  uint32_t K, uint32_t S) {
632  reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
633 }
634 
635 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
636  ValueProfData *VD =
637  (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
638  memset(VD, 0, TotalSizeInBytes);
639  return VD;
640 }
641 
642 static ValueProfRecordClosure InstrProfRecordClosure = {
643  nullptr,
648  nullptr,
651 
652 // Wrapper implementation using the closure mechanism.
653 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
654  auto Closure = InstrProfRecordClosure;
655  Closure.Record = &Record;
656  return getValueProfDataSize(&Closure);
657 }
658 
659 // Wrapper implementation using the closure mechanism.
660 std::unique_ptr<ValueProfData>
661 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
662  InstrProfRecordClosure.Record = &Record;
663 
664  std::unique_ptr<ValueProfData> VPD(
665  serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
666  return VPD;
667 }
668 
669 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
670  InstrProfSymtab *SymTab) {
671  Record.reserveSites(Kind, NumValueSites);
672 
673  InstrProfValueData *ValueData = getValueProfRecordValueData(this);
674  for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
675  uint8_t ValueDataCount = this->SiteCountArray[VSite];
676  Record.addValueData(Kind, VSite, ValueData, ValueDataCount, SymTab);
677  ValueData += ValueDataCount;
678  }
679 }
680 
681 // For writing/serializing, Old is the host endianness, and New is
682 // byte order intended on disk. For Reading/deserialization, Old
683 // is the on-disk source endianness, and New is the host endianness.
684 void ValueProfRecord::swapBytes(support::endianness Old,
685  support::endianness New) {
686  using namespace support;
687 
688  if (Old == New)
689  return;
690 
691  if (getHostEndianness() != Old) {
692  sys::swapByteOrder<uint32_t>(NumValueSites);
693  sys::swapByteOrder<uint32_t>(Kind);
694  }
695  uint32_t ND = getValueProfRecordNumValueData(this);
696  InstrProfValueData *VD = getValueProfRecordValueData(this);
697 
698  // No need to swap byte array: SiteCountArrray.
699  for (uint32_t I = 0; I < ND; I++) {
700  sys::swapByteOrder<uint64_t>(VD[I].Value);
701  sys::swapByteOrder<uint64_t>(VD[I].Count);
702  }
703  if (getHostEndianness() == Old) {
704  sys::swapByteOrder<uint32_t>(NumValueSites);
705  sys::swapByteOrder<uint32_t>(Kind);
706  }
707 }
708 
709 void ValueProfData::deserializeTo(InstrProfRecord &Record,
710  InstrProfSymtab *SymTab) {
711  if (NumValueKinds == 0)
712  return;
713 
714  ValueProfRecord *VR = getFirstValueProfRecord(this);
715  for (uint32_t K = 0; K < NumValueKinds; K++) {
716  VR->deserializeTo(Record, SymTab);
717  VR = getValueProfRecordNext(VR);
718  }
719 }
720 
721 template <class T>
722 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
723  using namespace support;
724 
725  if (Orig == little)
726  return endian::readNext<T, little, unaligned>(D);
727  else
728  return endian::readNext<T, big, unaligned>(D);
729 }
730 
731 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
732  return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
733  ValueProfData());
734 }
735 
736 Error ValueProfData::checkIntegrity() {
737  if (NumValueKinds > IPVK_Last + 1)
738  return make_error<InstrProfError>(instrprof_error::malformed);
739  // Total size needs to be mulltiple of quadword size.
740  if (TotalSize % sizeof(uint64_t))
741  return make_error<InstrProfError>(instrprof_error::malformed);
742 
743  ValueProfRecord *VR = getFirstValueProfRecord(this);
744  for (uint32_t K = 0; K < this->NumValueKinds; K++) {
745  if (VR->Kind > IPVK_Last)
746  return make_error<InstrProfError>(instrprof_error::malformed);
747  VR = getValueProfRecordNext(VR);
748  if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
749  return make_error<InstrProfError>(instrprof_error::malformed);
750  }
751  return Error::success();
752 }
753 
755 ValueProfData::getValueProfData(const unsigned char *D,
756  const unsigned char *const BufferEnd,
758  using namespace support;
759 
760  if (D + sizeof(ValueProfData) > BufferEnd)
761  return make_error<InstrProfError>(instrprof_error::truncated);
762 
763  const unsigned char *Header = D;
764  uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
765  if (D + TotalSize > BufferEnd)
766  return make_error<InstrProfError>(instrprof_error::too_large);
767 
768  std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
769  memcpy(VPD.get(), D, TotalSize);
770  // Byte swap.
771  VPD->swapBytesToHost(Endianness);
772 
773  Error E = VPD->checkIntegrity();
774  if (E)
775  return std::move(E);
776 
777  return std::move(VPD);
778 }
779 
780 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
781  using namespace support;
782 
783  if (Endianness == getHostEndianness())
784  return;
785 
786  sys::swapByteOrder<uint32_t>(TotalSize);
787  sys::swapByteOrder<uint32_t>(NumValueKinds);
788 
789  ValueProfRecord *VR = getFirstValueProfRecord(this);
790  for (uint32_t K = 0; K < NumValueKinds; K++) {
791  VR->swapBytes(Endianness, getHostEndianness());
792  VR = getValueProfRecordNext(VR);
793  }
794 }
795 
796 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
797  using namespace support;
798 
799  if (Endianness == getHostEndianness())
800  return;
801 
802  ValueProfRecord *VR = getFirstValueProfRecord(this);
803  for (uint32_t K = 0; K < NumValueKinds; K++) {
804  ValueProfRecord *NVR = getValueProfRecordNext(VR);
805  VR->swapBytes(getHostEndianness(), Endianness);
806  VR = NVR;
807  }
808  sys::swapByteOrder<uint32_t>(TotalSize);
809  sys::swapByteOrder<uint32_t>(NumValueKinds);
810 }
811 
813  const InstrProfRecord &InstrProfR,
814  InstrProfValueKind ValueKind, uint32_t SiteIdx,
815  uint32_t MaxMDCount) {
816  uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
817  if (!NV)
818  return;
819 
820  uint64_t Sum = 0;
821  std::unique_ptr<InstrProfValueData[]> VD =
822  InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
823 
824  ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
825  annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
826 }
827 
830  uint64_t Sum, InstrProfValueKind ValueKind,
831  uint32_t MaxMDCount) {
832  LLVMContext &Ctx = M.getContext();
833  MDBuilder MDHelper(Ctx);
835  // Tag
836  Vals.push_back(MDHelper.createString("VP"));
837  // Value Kind
838  Vals.push_back(MDHelper.createConstant(
839  ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
840  // Total Count
841  Vals.push_back(
842  MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
843 
844  // Value Profile Data
845  uint32_t MDCount = MaxMDCount;
846  for (auto &VD : VDs) {
847  Vals.push_back(MDHelper.createConstant(
848  ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
849  Vals.push_back(MDHelper.createConstant(
850  ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
851  if (--MDCount == 0)
852  break;
853  }
854  Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
855 }
856 
858  InstrProfValueKind ValueKind,
859  uint32_t MaxNumValueData,
860  InstrProfValueData ValueData[],
861  uint32_t &ActualNumValueData, uint64_t &TotalC) {
863  if (!MD)
864  return false;
865 
866  unsigned NOps = MD->getNumOperands();
867 
868  if (NOps < 5)
869  return false;
870 
871  // Operand 0 is a string tag "VP":
872  MDString *Tag = cast<MDString>(MD->getOperand(0));
873  if (!Tag)
874  return false;
875 
876  if (!Tag->getString().equals("VP"))
877  return false;
878 
879  // Now check kind:
880  ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
881  if (!KindInt)
882  return false;
883  if (KindInt->getZExtValue() != ValueKind)
884  return false;
885 
886  // Get total count
887  ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
888  if (!TotalCInt)
889  return false;
890  TotalC = TotalCInt->getZExtValue();
891 
892  ActualNumValueData = 0;
893 
894  for (unsigned I = 3; I < NOps; I += 2) {
895  if (ActualNumValueData >= MaxNumValueData)
896  break;
897  ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
898  ConstantInt *Count =
899  mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
900  if (!Value || !Count)
901  return false;
902  ValueData[ActualNumValueData].Value = Value->getZExtValue();
903  ValueData[ActualNumValueData].Count = Count->getZExtValue();
904  ActualNumValueData++;
905  }
906  return true;
907 }
908 
911 }
912 
914  // Only for internal linkage functions.
915  if (PGOFuncName == F.getName())
916  return;
917  // Don't create duplicated meta-data.
918  if (getPGOFuncNameMetadata(F))
919  return;
920  LLVMContext &C = F.getContext();
921  MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
923 }
924 
925 bool needsComdatForCounter(const Function &F, const Module &M) {
926  if (F.hasComdat())
927  return true;
928 
929  if (!Triple(M.getTargetTriple()).supportsCOMDAT())
930  return false;
931 
932  // See createPGOFuncNameVar for more details. To avoid link errors, profile
933  // counters for function with available_externally linkage needs to be changed
934  // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
935  // created. Without using comdat, duplicate entries won't be removed by the
936  // linker leading to increased data segement size and raw profile size. Even
937  // worse, since the referenced counter from profile per-function data object
938  // will be resolved to the common strong definition, the profile counts for
939  // available_externally functions will end up being duplicated in raw profile
940  // data. This can result in distorted profile as the counts of those dups
941  // will be accumulated by the profile merger.
943  if (Linkage != GlobalValue::ExternalWeakLinkage &&
945  return false;
946 
947  return true;
948 }
949 
950 // Check if INSTR_PROF_RAW_VERSION_VAR is defined.
951 bool isIRPGOFlagSet(const Module *M) {
952  auto IRInstrVar =
953  M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
954  if (!IRInstrVar || IRInstrVar->isDeclaration() ||
955  IRInstrVar->hasLocalLinkage())
956  return false;
957 
958  // Check if the flag is set.
959  if (!IRInstrVar->hasInitializer())
960  return false;
961 
962  const Constant *InitVal = IRInstrVar->getInitializer();
963  if (!InitVal)
964  return false;
965 
966  return (dyn_cast<ConstantInt>(InitVal)->getZExtValue() &
967  VARIANT_MASK_IR_PROF) != 0;
968 }
969 
970 // Check if we can safely rename this Comdat function.
971 bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
972  if (F.getName().empty())
973  return false;
974  if (!needsComdatForCounter(F, *(F.getParent())))
975  return false;
976  // Unsafe to rename the address-taken function (which can be used in
977  // function comparison).
978  if (CheckAddressTaken && F.hasAddressTaken())
979  return false;
980  // Only safe to do if this function may be discarded if it is not used
981  // in the compilation unit.
983  return false;
984 
985  // For AvailableExternallyLinkage functions.
986  if (!F.hasComdat()) {
988  return true;
989  }
990  return true;
991 }
992 
993 // Parse the value profile options.
995  int64_t &RangeLast) {
996  static const int64_t DefaultMemOPSizeRangeStart = 0;
997  static const int64_t DefaultMemOPSizeRangeLast = 8;
998  RangeStart = DefaultMemOPSizeRangeStart;
999  RangeLast = DefaultMemOPSizeRangeLast;
1000 
1001  if (!MemOPSizeRange.empty()) {
1002  auto Pos = MemOPSizeRange.find(':');
1003  if (Pos != std::string::npos) {
1004  if (Pos > 0)
1005  MemOPSizeRange.substr(0, Pos).getAsInteger(10, RangeStart);
1006  if (Pos < MemOPSizeRange.size() - 1)
1007  MemOPSizeRange.substr(Pos + 1).getAsInteger(10, RangeLast);
1008  } else
1009  MemOPSizeRange.getAsInteger(10, RangeLast);
1010  }
1011  assert(RangeLast >= RangeStart);
1012 }
1013 
1014 } // end namespace llvm
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:239
void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst, uint32_t K, uint32_t S)
Definition: InstrProf.cpp:630
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
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:618
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:239
A symbol table used for function PGO name look-up with keys (such as pointers, md5hash values) to the...
Definition: InstrProf.h:411
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:2564
void merge(InstrProfRecord &Other, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge the counts in Other into this one.
Definition: InstrProf.cpp:536
static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix)
Definition: InstrProf.cpp:225
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:228
DiagnosticInfoOptimizationBase::Argument NV
StringRef getInstrProfNameVarPrefix()
Return the name prefix of variables containing instrumented function names.
Definition: InstrProf.h:83
uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind)
Definition: InstrProf.cpp:619
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
Definition: AllocatorList.h:24
ConstantAsMetadata * createConstant(Constant *C)
Return the given constant as metadata.
Definition: MDBuilder.cpp:25
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:64
iterator begin() const
Definition: ArrayRef.h:137
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:588
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:454
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:795
Available for inspection, not emission.
Definition: GlobalValue.h:50
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
Definition: InstrProf.cpp:971
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:909
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:111
const GlobalVariable * getNamedGlobal(StringRef Name) const
Return the global variable in the module with the specified name, of arbitrary type.
Definition: Module.h:396
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
Externally visible function.
Definition: GlobalValue.h:49
constexpr support::endianness Endianness
The endianness of all multi-byte encoded values in MessagePack.
Definition: MsgPack.h:25
static std::unique_ptr< ValueProfData > allocValueProfData(uint32_t TotalSize)
Definition: InstrProf.cpp:731
static T swapToHostOrder(const unsigned char *&D, support::endianness Orig)
Definition: InstrProf.cpp:722
Metadata node.
Definition: Metadata.h:864
StringRef getName() const
Get a short "name" for the module.
Definition: Module.h:226
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:1069
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:177
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:156
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:793
void reserveSites(uint32_t ValueKind, uint32_t NumValueSites)
Reserve space for NumValueSites sites.
Definition: InstrProf.h:831
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
Definition: InstrProf.h:791
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:128
static bool isLocalLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:321
uint32_t getNumValueKindsInstrProf(const void *Record)
ValueProfRecordClosure Interface implementation for InstrProfRecord class.
Definition: InstrProf.cpp:610
amdgpu Simplify well known AMD library false Value Value const Twine & Name
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:482
Error compress(StringRef InputBuffer, SmallVectorImpl< char > &CompressedBuffer, int Level=DefaultCompression)
Definition: Compression.cpp:50
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:243
void scale(uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Scale up profile counts (including value profile data) by Weight.
Definition: InstrProf.cpp:564
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:1444
InstrProfValueKind
Definition: InstrProf.h:237
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:371
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
InstrProfSectKind
Definition: InstrProf.h:57
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:267
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:275
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:221
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
StringRef getInstrProfNameSeparator()
Return the marker used to separate PGO names during serialization.
Definition: InstrProf.h:162
auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1276
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:451
static constexpr int BestSizeCompression
Definition: Compression.h:29
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:598
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:1246
bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
Definition: InstrProf.cpp:951
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:464
ExternalWeak linkage description.
Definition: GlobalValue.h:58
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:363
void getMemOPSizeRangeFromOption(StringRef Str, int64_t &RangeStart, int64_t &RangeLast)
Definition: InstrProf.cpp:994
bool needsComdatForCounter(const Function &F, const Module &M)
Check if we can use Comdat for profile variables.
Definition: InstrProf.cpp:925
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1166
bool isAvailable()
Definition: Compression.cpp:48
#define P(N)
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:52
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:419
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:857
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:149
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:291
void scale(uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Scale up value profile data counts.
Definition: InstrProf.cpp:505
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:286
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:42
ValueKind
Value kinds.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static ValueProfRecordClosure InstrProfRecordClosure
Definition: InstrProf.cpp:642
ValueProfData * allocValueProfDataInstrProf(size_t TotalSizeInBytes)
Definition: InstrProf.cpp:635
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:129
std::list< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
Definition: InstrProf.h:596
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:194
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:812
Value(Type *Ty, unsigned scid)
Definition: Value.cpp:54
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:982
size_t size() const
Definition: SmallVector.h:53
void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function&#39;s raw name.
Definition: InstrProf.cpp:913
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:1226
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool isDiscardableIfUnused() const
Definition: GlobalValue.h:453
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:497
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:839
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE 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:645
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:327
See the file comment.
Definition: ValueMap.h:86
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
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:81
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:51
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:727
iterator end() const
Definition: ArrayRef.h:138
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:264
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:618
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:48
static char ID
Definition: InstrProf.h:333
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:501
void sortByTargetValues()
Sort ValueData ascending by Value.
Definition: InstrProf.h:604
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
Definition: StringRef.h:169
bool hasComdat() const
Definition: GlobalObject.h:100
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
Definition: Metadata.cpp:1434
std::vector< uint64_t > Counts
Definition: InstrProf.h:623
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:149
Profiling information for a single function.
Definition: InstrProf.h:622
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:590
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
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:280
MDString * createString(StringRef Str)
Return the given string as metadata.
Definition: MDBuilder.cpp:21
Error addFuncName(StringRef FuncName)
Update the symtab by adding FuncName to the table.
Definition: InstrProf.h:472
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
#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:331
Rename collisions when linking (static functions).
Definition: GlobalValue.h:56
const unsigned Kind
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:1255
uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind)
Definition: InstrProf.cpp:614
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ObjectFormatType
Definition: Triple.h:216
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:566
LLVM Value Representation.
Definition: Value.h:73
static const char * name
Lightweight error class with error context and mandatory checking.
Definition: Error.h:158
support::endianness getHostEndianness()
Definition: InstrProf.h:837
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
A single uniqued string.
Definition: Metadata.h:604
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:61
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:801
#define LLVM_ATTRIBUTE_UNUSED
Definition: Compiler.h:160
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1075
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:298
uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK, uint32_t S)
Definition: InstrProf.cpp:624
Error uncompress(StringRef InputBuffer, char *UncompressedBuffer, size_t &UncompressedSize)
Definition: Compression.cpp:64
const uint64_t Version
Definition: InstrProf.h:895
StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
Definition: InstrProf.cpp:419
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144