LLVM  5.0.0
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),
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),
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";
114  }
115  llvm_unreachable("A value of instrprof_error has no message.");
116 }
117 
118 namespace {
119 
120 // FIXME: This class is only here to support the transition to llvm::Error. It
121 // will be removed once this transition is complete. Clients should prefer to
122 // deal with the Error value directly, rather than converting to error_code.
123 class InstrProfErrorCategoryType : public std::error_category {
124  const char *name() const noexcept override { return "llvm.instrprof"; }
125 
126  std::string message(int IE) const override {
127  return getInstrProfErrString(static_cast<instrprof_error>(IE));
128  }
129 };
130 
131 } // end anonymous namespace
132 
134 
136  return *ErrorCategory;
137 }
138 
139 namespace {
140 
141 const char *InstrProfSectNameCommon[] = {
142 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
143  SectNameCommon,
145 };
146 
147 const char *InstrProfSectNameCoff[] = {
148 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
149  SectNameCoff,
151 };
152 
153 const char *InstrProfSectNamePrefix[] = {
154 #define INSTR_PROF_SECT_ENTRY(Kind, SectNameCommon, SectNameCoff, Prefix) \
155  Prefix,
157 };
158 
159 } // namespace
160 
161 namespace llvm {
162 
165  bool AddSegmentInfo) {
166  std::string SectName;
167 
168  if (OF == Triple::MachO && AddSegmentInfo)
169  SectName = InstrProfSectNamePrefix[IPSK];
170 
171  if (OF == Triple::COFF)
172  SectName += InstrProfSectNameCoff[IPSK];
173  else
174  SectName += InstrProfSectNameCommon[IPSK];
175 
176  if (OF == Triple::MachO && IPSK == IPSK_data && AddSegmentInfo)
177  SectName += ",regular,live_support";
178 
179  return SectName;
180 }
181 
183  if (IE == instrprof_error::success)
184  return;
185 
186  if (FirstError == instrprof_error::success)
187  FirstError = IE;
188 
189  switch (IE) {
191  ++NumHashMismatches;
192  break;
194  ++NumCountMismatches;
195  break;
197  ++NumCounterOverflows;
198  break;
200  ++NumValueSiteCountMismatches;
201  break;
202  default:
203  llvm_unreachable("Not a soft error");
204  }
205 }
206 
207 std::string InstrProfError::message() const {
208  return getInstrProfErrString(Err);
209 }
210 
211 char InstrProfError::ID = 0;
212 
213 std::string getPGOFuncName(StringRef RawFuncName,
215  StringRef FileName,
216  uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
217  return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
218 }
219 
220 // Strip NumPrefix level of directory name from PathNameStr. If the number of
221 // directory separators is less than NumPrefix, strip all the directories and
222 // leave base file name only.
223 static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
224  uint32_t Count = NumPrefix;
225  uint32_t Pos = 0, LastPos = 0;
226  for (auto & CI : PathNameStr) {
227  ++Pos;
229  LastPos = Pos;
230  --Count;
231  }
232  if (Count == 0)
233  break;
234  }
235  return PathNameStr.substr(LastPos);
236 }
237 
238 // Return the PGOFuncName. This function has some special handling when called
239 // in LTO optimization. The following only applies when calling in LTO passes
240 // (when \c InLTO is true): LTO's internalization privatizes many global linkage
241 // symbols. This happens after value profile annotation, but those internal
242 // linkage functions should not have a source prefix.
243 // Additionally, for ThinLTO mode, exported internal functions are promoted
244 // and renamed. We need to ensure that the original internal PGO name is
245 // used when computing the GUID that is compared against the profiled GUIDs.
246 // To differentiate compiler generated internal symbols from original ones,
247 // PGOFuncName meta data are created and attached to the original internal
248 // symbols in the value profile annotation step
249 // (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
250 // data, its original linkage must be non-internal.
251 std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
252  if (!InLTO) {
254  ? F.getParent()->getName()
257  FileName = stripDirPrefix(FileName, StaticFuncStripDirNamePrefix);
258  return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
259  }
260 
261  // In LTO mode (when InLTO is true), first check if there is a meta data.
262  if (MDNode *MD = getPGOFuncNameMetadata(F)) {
263  StringRef S = cast<MDString>(MD->getOperand(0))->getString();
264  return S.str();
265  }
266 
267  // If there is no meta data, the function must be a global before the value
268  // profile annotation pass. Its current linkage may be internal if it is
269  // internalized in LTO mode.
271 }
272 
274  if (FileName.empty())
275  return PGOFuncName;
276  // Drop the file name including ':'. See also getPGOFuncName.
277  if (PGOFuncName.startswith(FileName))
278  PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
279  return PGOFuncName;
280 }
281 
282 // \p FuncName is the string used as profile lookup key for the function. A
283 // symbol is created to hold the name. Return the legalized symbol name.
284 std::string getPGOFuncNameVarName(StringRef FuncName,
285  GlobalValue::LinkageTypes Linkage) {
286  std::string VarName = getInstrProfNameVarPrefix();
287  VarName += FuncName;
288 
289  if (!GlobalValue::isLocalLinkage(Linkage))
290  return VarName;
291 
292  // Now fix up illegal chars in local VarName that may upset the assembler.
293  const char *InvalidChars = "-:<>/\"'";
294  size_t found = VarName.find_first_of(InvalidChars);
295  while (found != std::string::npos) {
296  VarName[found] = '_';
297  found = VarName.find_first_of(InvalidChars, found + 1);
298  }
299  return VarName;
300 }
301 
304  StringRef PGOFuncName) {
305  // We generally want to match the function's linkage, but available_externally
306  // and extern_weak both have the wrong semantics, and anything that doesn't
307  // need to link across compilation units doesn't need to be visible at all.
308  if (Linkage == GlobalValue::ExternalWeakLinkage)
310  else if (Linkage == GlobalValue::AvailableExternallyLinkage)
312  else if (Linkage == GlobalValue::InternalLinkage ||
313  Linkage == GlobalValue::ExternalLinkage)
314  Linkage = GlobalValue::PrivateLinkage;
315 
316  auto *Value =
317  ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
318  auto FuncNameVar =
319  new GlobalVariable(M, Value->getType(), true, Linkage, Value,
320  getPGOFuncNameVarName(PGOFuncName, Linkage));
321 
322  // Hide the symbol so that we correctly get a copy for each executable.
323  if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
325 
326  return FuncNameVar;
327 }
328 
330  return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
331 }
332 
334  for (Function &F : M) {
335  // Function may not have a name: like using asm("") to overwrite the name.
336  // Ignore in this case.
337  if (!F.hasName())
338  continue;
339  const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
340  if (Error E = addFuncName(PGOFuncName))
341  return E;
342  MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
343  // In ThinLTO, local function may have been promoted to global and have
344  // suffix added to the function name. We need to add the stripped function
345  // name to the symbol table so that we can find a match from profile.
346  if (InLTO) {
347  auto pos = PGOFuncName.find('.');
348  if (pos != std::string::npos) {
349  const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
350  if (Error E = addFuncName(OtherFuncName))
351  return E;
352  MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F);
353  }
354  }
355  }
356 
357  finalizeSymtab();
358  return Error::success();
359 }
360 
362  bool doCompression, std::string &Result) {
363  assert(!NameStrs.empty() && "No name data to emit");
364 
365  uint8_t Header[16], *P = Header;
366  std::string UncompressedNameStrings =
367  join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
368 
369  assert(StringRef(UncompressedNameStrings)
370  .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
371  "PGO name is invalid (contains separator token)");
372 
373  unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
374  P += EncLen;
375 
376  auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
377  EncLen = encodeULEB128(CompressedLen, P);
378  P += EncLen;
379  char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
380  unsigned HeaderLen = P - &Header[0];
381  Result.append(HeaderStr, HeaderLen);
382  Result += InputStr;
383  return Error::success();
384  };
385 
386  if (!doCompression) {
387  return WriteStringToResult(0, UncompressedNameStrings);
388  }
389 
390  SmallString<128> CompressedNameStrings;
391  Error E = zlib::compress(StringRef(UncompressedNameStrings),
392  CompressedNameStrings, zlib::BestSizeCompression);
393  if (E) {
394  consumeError(std::move(E));
395  return make_error<InstrProfError>(instrprof_error::compress_failed);
396  }
397 
398  return WriteStringToResult(CompressedNameStrings.size(),
399  CompressedNameStrings);
400 }
401 
403  auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
404  StringRef NameStr =
405  Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
406  return NameStr;
407 }
408 
410  std::string &Result, bool doCompression) {
411  std::vector<std::string> NameStrs;
412  for (auto *NameVar : NameVars) {
413  NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
414  }
416  NameStrs, zlib::isAvailable() && doCompression, Result);
417 }
418 
420  const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
421  const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
422  NameStrings.size());
423  while (P < EndP) {
424  uint32_t N;
425  uint64_t UncompressedSize = decodeULEB128(P, &N);
426  P += N;
427  uint64_t CompressedSize = decodeULEB128(P, &N);
428  P += N;
429  bool isCompressed = (CompressedSize != 0);
430  SmallString<128> UncompressedNameStrings;
431  StringRef NameStrings;
432  if (isCompressed) {
433  StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
434  CompressedSize);
435  if (Error E =
436  zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
437  UncompressedSize)) {
438  consumeError(std::move(E));
439  return make_error<InstrProfError>(instrprof_error::uncompress_failed);
440  }
441  P += CompressedSize;
442  NameStrings = StringRef(UncompressedNameStrings.data(),
443  UncompressedNameStrings.size());
444  } else {
445  NameStrings =
446  StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
447  P += UncompressedSize;
448  }
449  // Now parse the name strings.
451  NameStrings.split(Names, getInstrProfNameSeparator());
452  for (StringRef &Name : Names)
453  if (Error E = Symtab.addFuncName(Name))
454  return E;
455 
456  while (P < EndP && *P == 0)
457  P++;
458  }
459  Symtab.finalizeSymtab();
460  return Error::success();
461 }
462 
464  uint64_t Weight,
465  function_ref<void(instrprof_error)> Warn) {
466  this->sortByTargetValues();
467  Input.sortByTargetValues();
468  auto I = ValueData.begin();
469  auto IE = ValueData.end();
470  for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
471  ++J) {
472  while (I != IE && I->Value < J->Value)
473  ++I;
474  if (I != IE && I->Value == J->Value) {
475  bool Overflowed;
476  I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
477  if (Overflowed)
479  ++I;
480  continue;
481  }
482  ValueData.insert(I, *J);
483  }
484 }
485 
486 void InstrProfValueSiteRecord::scale(uint64_t Weight,
487  function_ref<void(instrprof_error)> Warn) {
488  for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
489  bool Overflowed;
490  I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
491  if (Overflowed)
493  }
494 }
495 
496 // Merge Value Profile data from Src record to this record for ValueKind.
497 // Scale merged value counts by \p Weight.
498 void InstrProfRecord::mergeValueProfData(
499  uint32_t ValueKind, InstrProfRecord &Src, uint64_t Weight,
500  function_ref<void(instrprof_error)> Warn) {
501  uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
502  uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
503  if (ThisNumValueSites != OtherNumValueSites) {
505  return;
506  }
507  if (!ThisNumValueSites)
508  return;
509  std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
510  getOrCreateValueSitesForKind(ValueKind);
512  Src.getValueSitesForKind(ValueKind);
513  for (uint32_t I = 0; I < ThisNumValueSites; I++)
514  ThisSiteRecords[I].merge(OtherSiteRecords[I], Weight, Warn);
515 }
516 
517 void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight,
518  function_ref<void(instrprof_error)> Warn) {
519  // If the number of counters doesn't match we either have bad data
520  // or a hash collision.
521  if (Counts.size() != Other.Counts.size()) {
523  return;
524  }
525 
526  for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
527  bool Overflowed;
528  Counts[I] =
529  SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
530  if (Overflowed)
532  }
533 
534  for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
535  mergeValueProfData(Kind, Other, Weight, Warn);
536 }
537 
538 void InstrProfRecord::scaleValueProfData(
539  uint32_t ValueKind, uint64_t Weight,
540  function_ref<void(instrprof_error)> Warn) {
541  for (auto &R : getValueSitesForKind(ValueKind))
542  R.scale(Weight, Warn);
543 }
544 
545 void InstrProfRecord::scale(uint64_t Weight,
546  function_ref<void(instrprof_error)> Warn) {
547  for (auto &Count : this->Counts) {
548  bool Overflowed;
549  Count = SaturatingMultiply(Count, Weight, &Overflowed);
550  if (Overflowed)
552  }
553  for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
554  scaleValueProfData(Kind, Weight, Warn);
555 }
556 
557 // Map indirect call target name hash to name string.
558 uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
559  ValueMapType *ValueMap) {
560  if (!ValueMap)
561  return Value;
562  switch (ValueKind) {
563  case IPVK_IndirectCallTarget: {
564  auto Result =
565  std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
566  [](const std::pair<uint64_t, uint64_t> &LHS,
567  uint64_t RHS) { return LHS.first < RHS; });
568  // Raw function pointer collected by value profiler may be from
569  // external functions that are not instrumented. They won't have
570  // mapping data to be used by the deserializer. Force the value to
571  // be 0 in this case.
572  if (Result != ValueMap->end() && Result->first == Value)
573  Value = (uint64_t)Result->second;
574  else
575  Value = 0;
576  break;
577  }
578  }
579  return Value;
580 }
581 
583  InstrProfValueData *VData, uint32_t N,
584  ValueMapType *ValueMap) {
585  for (uint32_t I = 0; I < N; I++) {
586  VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
587  }
588  std::vector<InstrProfValueSiteRecord> &ValueSites =
589  getOrCreateValueSitesForKind(ValueKind);
590  if (N == 0)
591  ValueSites.emplace_back();
592  else
593  ValueSites.emplace_back(VData, VData + N);
594 }
595 
596 #define INSTR_PROF_COMMON_API_IMPL
598 
599 /*!
600  * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
601  * class. These C wrappers are used as adaptors so that C++ code can be
602  * invoked as callbacks.
603  */
605  return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
606 }
607 
609  return reinterpret_cast<const InstrProfRecord *>(Record)
610  ->getNumValueSites(VKind);
611 }
612 
614  return reinterpret_cast<const InstrProfRecord *>(Record)
615  ->getNumValueData(VKind);
616 }
617 
619  uint32_t S) {
620  return reinterpret_cast<const InstrProfRecord *>(R)
621  ->getNumValueDataForSite(VK, S);
622 }
623 
624 void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
625  uint32_t K, uint32_t S) {
626  reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
627 }
628 
629 ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
630  ValueProfData *VD =
631  (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
632  memset(VD, 0, TotalSizeInBytes);
633  return VD;
634 }
635 
636 static ValueProfRecordClosure InstrProfRecordClosure = {
637  nullptr,
642  nullptr,
645 
646 // Wrapper implementation using the closure mechanism.
647 uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
648  auto Closure = InstrProfRecordClosure;
649  Closure.Record = &Record;
650  return getValueProfDataSize(&Closure);
651 }
652 
653 // Wrapper implementation using the closure mechanism.
654 std::unique_ptr<ValueProfData>
655 ValueProfData::serializeFrom(const InstrProfRecord &Record) {
656  InstrProfRecordClosure.Record = &Record;
657 
658  std::unique_ptr<ValueProfData> VPD(
659  serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
660  return VPD;
661 }
662 
663 void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
665  Record.reserveSites(Kind, NumValueSites);
666 
667  InstrProfValueData *ValueData = getValueProfRecordValueData(this);
668  for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
669  uint8_t ValueDataCount = this->SiteCountArray[VSite];
670  Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
671  ValueData += ValueDataCount;
672  }
673 }
674 
675 // For writing/serializing, Old is the host endianness, and New is
676 // byte order intended on disk. For Reading/deserialization, Old
677 // is the on-disk source endianness, and New is the host endianness.
678 void ValueProfRecord::swapBytes(support::endianness Old,
679  support::endianness New) {
680  using namespace support;
681 
682  if (Old == New)
683  return;
684 
685  if (getHostEndianness() != Old) {
686  sys::swapByteOrder<uint32_t>(NumValueSites);
687  sys::swapByteOrder<uint32_t>(Kind);
688  }
689  uint32_t ND = getValueProfRecordNumValueData(this);
690  InstrProfValueData *VD = getValueProfRecordValueData(this);
691 
692  // No need to swap byte array: SiteCountArrray.
693  for (uint32_t I = 0; I < ND; I++) {
694  sys::swapByteOrder<uint64_t>(VD[I].Value);
695  sys::swapByteOrder<uint64_t>(VD[I].Count);
696  }
697  if (getHostEndianness() == Old) {
698  sys::swapByteOrder<uint32_t>(NumValueSites);
699  sys::swapByteOrder<uint32_t>(Kind);
700  }
701 }
702 
703 void ValueProfData::deserializeTo(InstrProfRecord &Record,
705  if (NumValueKinds == 0)
706  return;
707 
708  ValueProfRecord *VR = getFirstValueProfRecord(this);
709  for (uint32_t K = 0; K < NumValueKinds; K++) {
710  VR->deserializeTo(Record, VMap);
711  VR = getValueProfRecordNext(VR);
712  }
713 }
714 
715 template <class T>
716 static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
717  using namespace support;
718 
719  if (Orig == little)
720  return endian::readNext<T, little, unaligned>(D);
721  else
722  return endian::readNext<T, big, unaligned>(D);
723 }
724 
725 static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
726  return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
727  ValueProfData());
728 }
729 
730 Error ValueProfData::checkIntegrity() {
731  if (NumValueKinds > IPVK_Last + 1)
732  return make_error<InstrProfError>(instrprof_error::malformed);
733  // Total size needs to be mulltiple of quadword size.
734  if (TotalSize % sizeof(uint64_t))
735  return make_error<InstrProfError>(instrprof_error::malformed);
736 
737  ValueProfRecord *VR = getFirstValueProfRecord(this);
738  for (uint32_t K = 0; K < this->NumValueKinds; K++) {
739  if (VR->Kind > IPVK_Last)
740  return make_error<InstrProfError>(instrprof_error::malformed);
741  VR = getValueProfRecordNext(VR);
742  if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
743  return make_error<InstrProfError>(instrprof_error::malformed);
744  }
745  return Error::success();
746 }
747 
749 ValueProfData::getValueProfData(const unsigned char *D,
750  const unsigned char *const BufferEnd,
751  support::endianness Endianness) {
752  using namespace support;
753 
754  if (D + sizeof(ValueProfData) > BufferEnd)
755  return make_error<InstrProfError>(instrprof_error::truncated);
756 
757  const unsigned char *Header = D;
758  uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
759  if (D + TotalSize > BufferEnd)
760  return make_error<InstrProfError>(instrprof_error::too_large);
761 
762  std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
763  memcpy(VPD.get(), D, TotalSize);
764  // Byte swap.
765  VPD->swapBytesToHost(Endianness);
766 
767  Error E = VPD->checkIntegrity();
768  if (E)
769  return std::move(E);
770 
771  return std::move(VPD);
772 }
773 
774 void ValueProfData::swapBytesToHost(support::endianness Endianness) {
775  using namespace support;
776 
777  if (Endianness == getHostEndianness())
778  return;
779 
780  sys::swapByteOrder<uint32_t>(TotalSize);
781  sys::swapByteOrder<uint32_t>(NumValueKinds);
782 
783  ValueProfRecord *VR = getFirstValueProfRecord(this);
784  for (uint32_t K = 0; K < NumValueKinds; K++) {
785  VR->swapBytes(Endianness, getHostEndianness());
786  VR = getValueProfRecordNext(VR);
787  }
788 }
789 
790 void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
791  using namespace support;
792 
793  if (Endianness == getHostEndianness())
794  return;
795 
796  ValueProfRecord *VR = getFirstValueProfRecord(this);
797  for (uint32_t K = 0; K < NumValueKinds; K++) {
798  ValueProfRecord *NVR = getValueProfRecordNext(VR);
799  VR->swapBytes(getHostEndianness(), Endianness);
800  VR = NVR;
801  }
802  sys::swapByteOrder<uint32_t>(TotalSize);
803  sys::swapByteOrder<uint32_t>(NumValueKinds);
804 }
805 
807  const InstrProfRecord &InstrProfR,
808  InstrProfValueKind ValueKind, uint32_t SiteIdx,
809  uint32_t MaxMDCount) {
810  uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
811  if (!NV)
812  return;
813 
814  uint64_t Sum = 0;
815  std::unique_ptr<InstrProfValueData[]> VD =
816  InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
817 
818  ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
819  annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
820 }
821 
824  uint64_t Sum, InstrProfValueKind ValueKind,
825  uint32_t MaxMDCount) {
826  LLVMContext &Ctx = M.getContext();
827  MDBuilder MDHelper(Ctx);
829  // Tag
830  Vals.push_back(MDHelper.createString("VP"));
831  // Value Kind
832  Vals.push_back(MDHelper.createConstant(
833  ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
834  // Total Count
835  Vals.push_back(
836  MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
837 
838  // Value Profile Data
839  uint32_t MDCount = MaxMDCount;
840  for (auto &VD : VDs) {
841  Vals.push_back(MDHelper.createConstant(
842  ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
843  Vals.push_back(MDHelper.createConstant(
844  ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
845  if (--MDCount == 0)
846  break;
847  }
848  Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
849 }
850 
852  InstrProfValueKind ValueKind,
853  uint32_t MaxNumValueData,
854  InstrProfValueData ValueData[],
855  uint32_t &ActualNumValueData, uint64_t &TotalC) {
857  if (!MD)
858  return false;
859 
860  unsigned NOps = MD->getNumOperands();
861 
862  if (NOps < 5)
863  return false;
864 
865  // Operand 0 is a string tag "VP":
866  MDString *Tag = cast<MDString>(MD->getOperand(0));
867  if (!Tag)
868  return false;
869 
870  if (!Tag->getString().equals("VP"))
871  return false;
872 
873  // Now check kind:
874  ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
875  if (!KindInt)
876  return false;
877  if (KindInt->getZExtValue() != ValueKind)
878  return false;
879 
880  // Get total count
881  ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
882  if (!TotalCInt)
883  return false;
884  TotalC = TotalCInt->getZExtValue();
885 
886  ActualNumValueData = 0;
887 
888  for (unsigned I = 3; I < NOps; I += 2) {
889  if (ActualNumValueData >= MaxNumValueData)
890  break;
891  ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
892  ConstantInt *Count =
893  mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
894  if (!Value || !Count)
895  return false;
896  ValueData[ActualNumValueData].Value = Value->getZExtValue();
897  ValueData[ActualNumValueData].Count = Count->getZExtValue();
898  ActualNumValueData++;
899  }
900  return true;
901 }
902 
905 }
906 
908  // Only for internal linkage functions.
909  if (PGOFuncName == F.getName())
910  return;
911  // Don't create duplicated meta-data.
912  if (getPGOFuncNameMetadata(F))
913  return;
914  LLVMContext &C = F.getContext();
915  MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
917 }
918 
919 bool needsComdatForCounter(const Function &F, const Module &M) {
920  if (F.hasComdat())
921  return true;
922 
923  Triple TT(M.getTargetTriple());
924  if (!TT.isOSBinFormatELF() && !TT.isOSBinFormatWasm())
925  return false;
926 
927  // See createPGOFuncNameVar for more details. To avoid link errors, profile
928  // counters for function with available_externally linkage needs to be changed
929  // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
930  // created. Without using comdat, duplicate entries won't be removed by the
931  // linker leading to increased data segement size and raw profile size. Even
932  // worse, since the referenced counter from profile per-function data object
933  // will be resolved to the common strong definition, the profile counts for
934  // available_externally functions will end up being duplicated in raw profile
935  // data. This can result in distorted profile as the counts of those dups
936  // will be accumulated by the profile merger.
938  if (Linkage != GlobalValue::ExternalWeakLinkage &&
940  return false;
941 
942  return true;
943 }
944 
945 // Check if INSTR_PROF_RAW_VERSION_VAR is defined.
946 bool isIRPGOFlagSet(const Module *M) {
947  auto IRInstrVar =
948  M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
949  if (!IRInstrVar || IRInstrVar->isDeclaration() ||
950  IRInstrVar->hasLocalLinkage())
951  return false;
952 
953  // Check if the flag is set.
954  if (!IRInstrVar->hasInitializer())
955  return false;
956 
957  const Constant *InitVal = IRInstrVar->getInitializer();
958  if (!InitVal)
959  return false;
960 
961  return (dyn_cast<ConstantInt>(InitVal)->getZExtValue() &
962  VARIANT_MASK_IR_PROF) != 0;
963 }
964 
965 // Check if we can safely rename this Comdat function.
966 bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
967  if (F.getName().empty())
968  return false;
969  if (!needsComdatForCounter(F, *(F.getParent())))
970  return false;
971  // Unsafe to rename the address-taken function (which can be used in
972  // function comparison).
973  if (CheckAddressTaken && F.hasAddressTaken())
974  return false;
975  // Only safe to do if this function may be discarded if it is not used
976  // in the compilation unit.
978  return false;
979 
980  // For AvailableExternallyLinkage functions.
981  if (!F.hasComdat()) {
983  return true;
984  }
985  return true;
986 }
987 
988 // Parse the value profile options.
990  int64_t &RangeLast) {
991  static const int64_t DefaultMemOPSizeRangeStart = 0;
992  static const int64_t DefaultMemOPSizeRangeLast = 8;
993  RangeStart = DefaultMemOPSizeRangeStart;
994  RangeLast = DefaultMemOPSizeRangeLast;
995 
996  if (!MemOPSizeRange.empty()) {
997  auto Pos = MemOPSizeRange.find(':');
998  if (Pos != std::string::npos) {
999  if (Pos > 0)
1000  MemOPSizeRange.substr(0, Pos).getAsInteger(10, RangeStart);
1001  if (Pos < MemOPSizeRange.size() - 1)
1002  MemOPSizeRange.substr(Pos + 1).getAsInteger(10, RangeLast);
1003  } else
1004  MemOPSizeRange.getAsInteger(10, RangeLast);
1005  }
1006  assert(RangeLast >= RangeStart);
1007 }
1008 
1009 } // end namespace llvm
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:226
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:645
void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst, uint32_t K, uint32_t S)
Definition: InstrProf.cpp:624
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
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:603
LinkageTypes getLinkage() const
Definition: GlobalValue.h:430
A symbol table used for function PGO name look-up with keys (such as pointers, md5hash values) to the...
Definition: InstrProf.h:410
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:2451
bool hasComdat() const
Definition: GlobalObject.h:100
void merge(InstrProfRecord &Other, uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Merge the counts in Other into this one.
Definition: InstrProf.cpp:517
static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix)
Definition: InstrProf.cpp:223
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:194
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:613
static cl::opt< unsigned > StaticFuncStripDirNamePrefix("static-func-strip-dirname-prefix", cl::init(0), cl::desc("Strip specified level of directory name from source path in ""the profile counter name for static functions."))
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:63
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:480
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:446
Available for inspection, not emission.
Definition: GlobalValue.h:50
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1073
iterator end() const
Definition: ArrayRef.h:138
bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
Definition: InstrProf.cpp:966
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:903
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:89
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
Externally visible function.
Definition: GlobalValue.h:49
static std::unique_ptr< ValueProfData > allocValueProfData(uint32_t TotalSize)
Definition: InstrProf.cpp:725
static T swapToHostOrder(const unsigned char *&D, support::endianness Orig)
Definition: InstrProf.cpp:716
Metadata node.
Definition: Metadata.h:862
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
Definition: InstrProf.cpp:163
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:177
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:233
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:780
void reserveSites(uint32_t ValueKind, uint32_t NumValueSites)
Reserve space for NumValueSites sites.
Definition: InstrProf.h:802
static bool isLocalLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:301
uint32_t getNumValueKindsInstrProf(const void *Record)
ValueProfRecordClosure Interface implementation for InstrProfRecord class.
Definition: InstrProf.cpp:604
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:218
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:463
StringRef getName() const
Get a short "name" for the module.
Definition: Module.h:220
const GlobalVariable * getNamedGlobal(StringRef Name) const
Return the global variable in the module with the specified name, of arbitrary type.
Definition: Module.h:383
static cl::opt< bool > StaticFuncFullModulePrefix("static-func-full-module-prefix", cl::init(true), cl::desc("Use full module build paths in the profile counter names for ""static functions."))
void scale(uint64_t Weight, function_ref< void(instrprof_error)> Warn)
Scale up profile counts (including value profile data) by Weight.
Definition: InstrProf.cpp:545
const std::error_category & instrprof_category()
Definition: InstrProf.cpp:135
InstrProfValueKind
Definition: InstrProf.h:237
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
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:361
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:313
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
InstrProfSectKind
Definition: InstrProf.h:57
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:772
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
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:273
#define F(x, y, z)
Definition: MD5.cpp:55
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:267
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
void addError(instrprof_error IE)
Track a soft error (IE) and increment its associated counter.
Definition: InstrProf.cpp:182
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(std::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:880
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
bool isDiscardableIfUnused() const
Definition: GlobalValue.h:432
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
const char * Name
bool isIRPGOFlagSet(const Module *M)
Check if INSTR_PROF_RAW_VERSION_VAR is defined.
Definition: InstrProf.cpp:946
static ManagedStatic< InstrProfErrorCategoryType > ErrorCategory
Definition: InstrProf.cpp:133
std::string message() const override
Return the error message as a string.
Definition: InstrProf.cpp:207
ExternalWeak linkage description.
Definition: GlobalValue.h:58
void getMemOPSizeRangeFromOption(StringRef Str, int64_t &RangeStart, int64_t &RangeLast)
Definition: InstrProf.cpp:989
bool needsComdatForCounter(const Function &F, const Module &M)
Check if we can use Comdat for profile variables.
Definition: InstrProf.cpp:919
bool isAvailable()
Definition: Compression.cpp:58
#define P(N)
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:52
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
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:851
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:486
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
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:284
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
This is an important base class in LLVM.
Definition: Constant.h:42
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static ValueProfRecordClosure InstrProfRecordClosure
Definition: InstrProf.cpp:636
std::vector< std::pair< uint64_t, uint64_t >> ValueMapType
Definition: InstrProf.h:616
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
ValueProfData * allocValueProfDataInstrProf(size_t TotalSizeInBytes)
Definition: InstrProf.cpp:629
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:114
#define LLVM_ATTRIBUTE_UNUSED
Definition: Compiler.h:144
std::list< InstrProfValueData > ValueData
Value profiling data pairs at a given value site.
Definition: InstrProf.h:565
iterator begin() const
Definition: ArrayRef.h:137
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:228
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:806
Value(Type *Ty, unsigned scid)
Definition: Value.cpp:49
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:593
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:766
void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName)
Create the PGOFuncName meta data if PGOFuncName is different from function's raw name.
Definition: InstrProf.cpp:907
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:419
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1214
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
void addValueData(uint32_t ValueKind, uint32_t Site, InstrProfValueData *VData, uint32_t N, ValueMapType *ValueMap)
Add ValueData for ValueKind at value Site.
Definition: InstrProf.cpp:582
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:826
StringRef getString() const
Definition: Metadata.cpp:456
Error create(object::SectionRef &Section)
Create InstrProfSymtab from an object file section which contains function PGO names.
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1067
static ErrorSuccess success()
Create a success value.
Definition: Error.h:311
Error compress(StringRef InputBuffer, SmallVectorImpl< char > &CompressedBuffer, CompressionLevel Level=DefaultCompression)
Definition: Compression.cpp:60
See the file comment.
Definition: ValueMap.h:86
#define E
Definition: LargeTest.cpp:27
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:51
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:190
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:150
static std::string getInstrProfErrString(instrprof_error Err)
Definition: InstrProf.cpp:76
const size_t N
StringRef getPGOFuncNameMetadataName()
Definition: InstrProf.h:264
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:560
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:48
static char ID
Definition: InstrProf.h:332
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
void sortByTargetValues()
Sort ValueData ascending by Value.
Definition: InstrProf.h:573
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 current metadata attachments for the given kind, if any.
Definition: Metadata.cpp:1431
void setMetadata(unsigned KindID, MDNode *MD)
Set a particular kind of metadata attachment.
Definition: Metadata.cpp:1421
llvm_unreachable("Unknown RegBank!")
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1164
std::vector< uint64_t > Counts
Definition: InstrProf.h:592
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:1208
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:142
Profiling information for a single function.
Definition: InstrProf.h:591
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:575
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:251
instrprof_error
Definition: InstrProf.h:280
#define C
Definition: LargeTest.cpp:25
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:466
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
Definition: InstrProf.cpp:329
Rename collisions when linking (static functions).
Definition: GlobalValue.h:56
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
Definition: InstrProf.h:762
const unsigned Kind
uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind)
Definition: InstrProf.cpp:608
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ObjectFormatType
Definition: Triple.h:207
aarch64 promote const
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:545
LLVM Value Representation.
Definition: Value.h:73
static const char * name
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
support::endianness getHostEndianness()
Definition: InstrProf.h:808
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
void encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned Padding=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:73
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
A single uniqued string.
Definition: Metadata.h:602
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:61
uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK, uint32_t S)
Definition: InstrProf.cpp:618
Error uncompress(StringRef InputBuffer, char *UncompressedBuffer, size_t &UncompressedSize)
Definition: Compression.cpp:76
const uint64_t Version
Definition: InstrProf.h:864
#define D
Definition: LargeTest.cpp:26
StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar)
Return the initializer in string of the PGO name var NameVar.
Definition: InstrProf.cpp:402
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:237
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(""))