LLVM  14.0.0git
InstrProfCorrelator.cpp
Go to the documentation of this file.
1 //===-- InstrProfCorrelator.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
10 #include "llvm/Object/MachO.h"
11 #include "llvm/Support/Debug.h"
13 #include "llvm/Support/Path.h"
14 
15 #define DEBUG_TYPE "correlator"
16 
17 using namespace llvm;
18 
19 /// Get the __llvm_prf_cnts section.
21  for (auto &Section : Obj.sections())
22  if (auto SectionName = Section.getName())
23  if (SectionName.get() == INSTR_PROF_CNTS_SECT_NAME)
24  return Section;
25  return make_error<InstrProfError>(
27 }
28 
29 const char *InstrProfCorrelator::FunctionNameAttributeName = "Function Name";
30 const char *InstrProfCorrelator::CFGHashAttributeName = "CFG Hash";
31 const char *InstrProfCorrelator::NumCountersAttributeName = "Num Counters";
32 
34 InstrProfCorrelator::Context::get(std::unique_ptr<MemoryBuffer> Buffer,
35  const object::ObjectFile &Obj) {
36  auto CountersSection = getCountersSection(Obj);
37  if (auto Err = CountersSection.takeError())
38  return std::move(Err);
39  auto C = std::make_unique<Context>();
40  C->Buffer = std::move(Buffer);
41  C->CountersSectionStart = CountersSection->getAddress();
42  C->CountersSectionEnd = C->CountersSectionStart + CountersSection->getSize();
43  C->ShouldSwapBytes = Obj.isLittleEndian() != sys::IsLittleEndianHost;
45 }
46 
48 InstrProfCorrelator::get(StringRef DebugInfoFilename) {
49  auto DsymObjectsOrErr =
51  if (auto Err = DsymObjectsOrErr.takeError())
52  return std::move(Err);
53  if (!DsymObjectsOrErr->empty()) {
54  // TODO: Enable profile correlation when there are multiple objects in a
55  // dSYM bundle.
56  if (DsymObjectsOrErr->size() > 1)
57  return createStringError(
58  std::error_code(),
59  "Profile correlation using multiple objects is not yet supported");
60  DebugInfoFilename = *DsymObjectsOrErr->begin();
61  }
62  auto BufferOrErr =
63  errorOrToExpected(MemoryBuffer::getFile(DebugInfoFilename));
64  if (auto Err = BufferOrErr.takeError())
65  return std::move(Err);
66 
67  return get(std::move(*BufferOrErr));
68 }
69 
71 InstrProfCorrelator::get(std::unique_ptr<MemoryBuffer> Buffer) {
72  auto BinOrErr = object::createBinary(*Buffer);
73  if (auto Err = BinOrErr.takeError())
74  return std::move(Err);
75 
76  if (auto *Obj = dyn_cast<object::ObjectFile>(BinOrErr->get())) {
77  auto CtxOrErr = Context::get(std::move(Buffer), *Obj);
78  if (auto Err = CtxOrErr.takeError())
79  return std::move(Err);
80  auto T = Obj->makeTriple();
81  if (T.isArch64Bit())
82  return InstrProfCorrelatorImpl<uint64_t>::get(std::move(*CtxOrErr), *Obj);
83  if (T.isArch32Bit())
84  return InstrProfCorrelatorImpl<uint32_t>::get(std::move(*CtxOrErr), *Obj);
85  }
86  return make_error<InstrProfError>(
88 }
89 
90 namespace llvm {
91 
92 template <>
94  std::unique_ptr<InstrProfCorrelator::Context> Ctx)
96  std::move(Ctx)) {}
97 template <>
99  std::unique_ptr<InstrProfCorrelator::Context> Ctx)
101  std::move(Ctx)) {}
102 template <>
104  return C->getKind() == InstrProfCorrelatorKind::CK_32Bit;
105 }
106 template <>
108  return C->getKind() == InstrProfCorrelatorKind::CK_64Bit;
109 }
110 
111 } // end namespace llvm
112 
113 template <class IntPtrT>
116  std::unique_ptr<InstrProfCorrelator::Context> Ctx,
117  const object::ObjectFile &Obj) {
118  if (Obj.isELF() || Obj.isMachO()) {
119  auto DICtx = DWARFContext::create(Obj);
120  return std::make_unique<DwarfInstrProfCorrelator<IntPtrT>>(std::move(DICtx),
121  std::move(Ctx));
122  }
123  return make_error<InstrProfError>(instrprof_error::unsupported_debug_format);
124 }
125 
126 template <class IntPtrT>
128  assert(Data.empty() && CompressedNames.empty() && Names.empty());
129  correlateProfileDataImpl();
130  auto Result =
131  collectPGOFuncNameStrings(Names, /*doCompression=*/true, CompressedNames);
132  CounterOffsets.clear();
133  Names.clear();
134  return Result;
135 }
136 
137 template <class IntPtrT>
139  uint64_t CFGHash,
140  IntPtrT CounterOffset,
141  IntPtrT FunctionPtr,
142  uint32_t NumCounters) {
143  // Check if a probe was already added for this counter offset.
144  if (!CounterOffsets.insert(CounterOffset).second)
145  return;
146  Data.push_back({
147  maybeSwap<uint64_t>(IndexedInstrProf::ComputeHash(FunctionName)),
148  maybeSwap<uint64_t>(CFGHash),
149  // In this mode, CounterPtr actually stores the section relative address
150  // of the counter.
151  maybeSwap<IntPtrT>(CounterOffset),
152  maybeSwap<IntPtrT>(FunctionPtr),
153  // TODO: Value profiling is not yet supported.
154  /*ValuesPtr=*/maybeSwap<IntPtrT>(0),
155  maybeSwap<uint32_t>(NumCounters),
156  /*NumValueSites=*/{maybeSwap<uint16_t>(0), maybeSwap<uint16_t>(0)},
157  });
158  Names.push_back(FunctionName.str());
159 }
160 
161 template <class IntPtrT>
164  auto Locations = Die.getLocations(dwarf::DW_AT_location);
165  if (!Locations) {
166  consumeError(Locations.takeError());
167  return {};
168  }
169  auto &DU = *Die.getDwarfUnit();
170  for (auto &Location : *Locations) {
171  auto AddressSize = DU.getAddressByteSize();
172  DataExtractor Data(Location.Expr, DICtx->isLittleEndian(), AddressSize);
173  DWARFExpression Expr(Data, AddressSize);
174  for (auto &Op : Expr)
175  if (Op.getCode() == dwarf::DW_OP_addr)
176  return Op.getRawOperand(0);
177  }
178  return {};
179 }
180 
181 template <class IntPtrT>
183  const auto &ParentDie = Die.getParent();
184  if (!Die.isValid() || !ParentDie.isValid() || Die.isNULL())
185  return false;
186  if (Die.getTag() != dwarf::DW_TAG_variable)
187  return false;
188  if (!ParentDie.isSubprogramDIE())
189  return false;
190  if (!Die.hasChildren())
191  return false;
192  if (const char *Name = Die.getName(DINameKind::ShortName))
194  return false;
195 }
196 
197 template <class IntPtrT>
199  auto maybeAddProbe = [&](DWARFDie Die) {
200  if (!isDIEOfProbe(Die))
201  return;
202  Optional<const char *> FunctionName;
203  Optional<uint64_t> CFGHash;
204  Optional<uint64_t> CounterPtr = getLocation(Die);
205  auto FunctionPtr =
206  dwarf::toAddress(Die.getParent().find(dwarf::DW_AT_low_pc));
207  Optional<uint64_t> NumCounters;
208  for (const DWARFDie &Child : Die.children()) {
209  if (Child.getTag() != dwarf::DW_TAG_LLVM_annotation)
210  continue;
211  auto AnnotationFormName = Child.find(dwarf::DW_AT_name);
212  auto AnnotationFormValue = Child.find(dwarf::DW_AT_const_value);
213  if (!AnnotationFormName || !AnnotationFormValue)
214  continue;
215  auto AnnotationNameOrErr = AnnotationFormName->getAsCString();
216  if (auto Err = AnnotationNameOrErr.takeError()) {
217  consumeError(std::move(Err));
218  continue;
219  }
220  StringRef AnnotationName = *AnnotationNameOrErr;
221  if (AnnotationName.compare(
222  InstrProfCorrelator::FunctionNameAttributeName) == 0) {
223  if (auto EC =
224  AnnotationFormValue->getAsCString().moveInto(FunctionName))
225  consumeError(std::move(EC));
226  } else if (AnnotationName.compare(
227  InstrProfCorrelator::CFGHashAttributeName) == 0) {
228  CFGHash = AnnotationFormValue->getAsUnsignedConstant();
229  } else if (AnnotationName.compare(
230  InstrProfCorrelator::NumCountersAttributeName) == 0) {
231  NumCounters = AnnotationFormValue->getAsUnsignedConstant();
232  }
233  }
234  if (!FunctionName || !CFGHash || !CounterPtr || !NumCounters) {
235  LLVM_DEBUG(dbgs() << "Incomplete DIE for probe\n\tFunctionName: "
236  << FunctionName << "\n\tCFGHash: " << CFGHash
237  << "\n\tCounterPtr: " << CounterPtr
238  << "\n\tNumCounters: " << NumCounters);
239  LLVM_DEBUG(Die.dump(dbgs()));
240  return;
241  }
242  uint64_t CountersStart = this->Ctx->CountersSectionStart;
243  uint64_t CountersEnd = this->Ctx->CountersSectionEnd;
244  if (*CounterPtr < CountersStart || *CounterPtr >= CountersEnd) {
245  LLVM_DEBUG(
246  dbgs() << "CounterPtr out of range for probe\n\tFunction Name: "
247  << FunctionName << "\n\tExpected: [0x"
248  << Twine::utohexstr(CountersStart) << ", 0x"
249  << Twine::utohexstr(CountersEnd) << ")\n\tActual: 0x"
250  << Twine::utohexstr(*CounterPtr));
251  LLVM_DEBUG(Die.dump(dbgs()));
252  return;
253  }
254  if (!FunctionPtr) {
255  LLVM_DEBUG(dbgs() << "Could not find address of " << *FunctionName
256  << "\n");
257  LLVM_DEBUG(Die.dump(dbgs()));
258  }
259  this->addProbe(*FunctionName, *CFGHash, *CounterPtr - CountersStart,
260  FunctionPtr.getValueOr(0), *NumCounters);
261  };
262  for (auto &CU : DICtx->normal_units())
263  for (const auto &Entry : CU->dies())
264  maybeAddProbe(DWARFDie(CU.get(), &Entry));
265  for (auto &CU : DICtx->dwo_units())
266  for (const auto &Entry : CU->dies())
267  maybeAddProbe(DWARFDie(CU.get(), &Entry));
268 }
llvm::StringRef::startswith
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:285
llvm::DWARFDie::isValid
bool isValid() const
Definition: DWARFDie.h:51
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AllocatorList.h:23
FileSystem.h
llvm::InstrProfCorrelator::NumCountersAttributeName
static const char * NumCountersAttributeName
Definition: InstrProfCorrelator.h:40
T
llvm::object::MachOObjectFile::findDsymObjectMembers
static Expected< std::vector< std::string > > findDsymObjectMembers(StringRef Path)
If the input path is a .dSYM bundle (as created by the dsymutil tool), return the paths to the object...
Definition: MachOObjectFile.cpp:4727
llvm::object::Binary::isLittleEndian
bool isLittleEndian() const
Definition: Binary.h:148
llvm::IndexedInstrProf::ComputeHash
uint64_t ComputeHash(StringRef K)
Definition: InstrProf.h:1003
Path.h
llvm::InstrProfCorrelator::CFGHashAttributeName
static const char * CFGHashAttributeName
Definition: InstrProfCorrelator.h:39
llvm::Optional< uint64_t >
llvm::Expected
Tagged union holding either a T or a Error.
Definition: APFloat.h:42
llvm::DWARFDie::isNULL
bool isNULL() const
Returns true for a valid DIE that terminates a sibling chain.
Definition: DWARFDie.h:85
llvm::DWARFDie::children
iterator_range< iterator > children() const
Definition: DWARFDie.h:389
llvm::consumeError
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1045
llvm::Data
@ Data
Definition: SIMachineScheduler.h:55
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:101
llvm::dwarf::toAddress
Optional< uint64_t > toAddress(const Optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an address.
Definition: DWARFFormValue.h:288
MachO.h
llvm::InstrProfCorrelatorImpl
InstrProfCorrelatorImpl - A child of InstrProfCorrelator with a template pointer type so that the Pro...
Definition: InstrProfCorrelator.h:72
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
llvm::ARMBuildAttrs::Section
@ Section
Legacy Tags.
Definition: ARMBuildAttributes.h:82
llvm::DwarfInstrProfCorrelator
DwarfInstrProfCorrelator - A child of InstrProfCorrelatorImpl that takes DWARF debug info as input to...
Definition: InstrProfCorrelator.h:125
llvm::MemoryBuffer::getFile
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Definition: MemoryBuffer.cpp:237
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::InstrProfCorrelator::CK_32Bit
@ CK_32Bit
Definition: InstrProfCorrelator.h:42
llvm::InstrProfCorrelator::FunctionNameAttributeName
static const char * FunctionNameAttributeName
Definition: InstrProfCorrelator.h:38
llvm::InstrProfCorrelator::Ctx
const std::unique_ptr< InstrProfCorrelator::Context > Ctx
Definition: InstrProfCorrelator.h:57
llvm::getInstrProfCountersVarPrefix
StringRef getInstrProfCountersVarPrefix()
Return the name prefix of profile counter variables.
Definition: InstrProf.h:90
llvm::StringRef::str
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:244
llvm::DWARFDie::dump
void dump(raw_ostream &OS, unsigned indent=0, DIDumpOptions DumpOpts=DIDumpOptions()) const
Dump the DIE and all of its attributes to the supplied stream.
Definition: DWARFDie.cpp:1076
llvm::InstrProfCorrelatorImpl::InstrProfCorrelatorImpl
InstrProfCorrelatorImpl(std::unique_ptr< InstrProfCorrelator::Context > Ctx)
llvm::InstrProfCorrelator::get
static llvm::Expected< std::unique_ptr< InstrProfCorrelator > > get(StringRef DebugInfoFilename)
Definition: InstrProfCorrelator.cpp:48
uint64_t
llvm::InstrProfCorrelator::InstrProfCorrelatorKind
InstrProfCorrelatorKind
Definition: InstrProfCorrelator.h:42
move
compiles ldr LCPI1_0 ldr ldr mov lsr tst moveq r1 ldr LCPI1_1 and r0 bx lr It would be better to do something like to fold the shift into the conditional move
Definition: README.txt:546
llvm::DWARFDie::find
Optional< DWARFFormValue > find(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE.
Definition: DWARFDie.cpp:821
llvm::DWARFExpression
Definition: DWARFExpression.h:25
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::move
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1707
llvm::object::Binary::isELF
bool isELF() const
Definition: Binary.h:120
llvm::collectPGOFuncNameStrings
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:442
llvm::InstrProfCorrelatorImpl::classof
static bool classof(const InstrProfCorrelator *C)
getCountersSection
Expected< object::SectionRef > getCountersSection(const object::ObjectFile &Obj)
Get the __llvm_prf_cnts section.
Definition: InstrProfCorrelator.cpp:20
llvm::DWARFDie::getLocations
Expected< DWARFLocationExpressionsVector > getLocations(dwarf::Attribute Attr) const
Definition: DWARFDie.cpp:980
llvm::InstrProfCorrelator::Context::get
static llvm::Expected< std::unique_ptr< Context > > get(std::unique_ptr< MemoryBuffer > Buffer, const object::ObjectFile &Obj)
Definition: InstrProfCorrelator.cpp:34
llvm::InstrProfCorrelator::Context::Buffer
std::unique_ptr< MemoryBuffer > Buffer
Definition: InstrProfCorrelator.h:50
llvm::DWARFDie::hasChildren
bool hasChildren() const
Definition: DWARFDie.h:79
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:57
llvm::object::ObjectFile
This class is the base class for all object file types.
Definition: ObjectFile.h:227
llvm::DWARFDie::getDwarfUnit
DWARFUnit * getDwarfUnit() const
Definition: DWARFDie.h:54
uint32_t
llvm::DWARFDie::getName
const char * getName(DINameKind Kind) const
Return the DIE name resolving DW_AT_specification or DW_AT_abstract_origin references if necessary.
Definition: DWARFDie.cpp:1016
llvm::InstrProfCorrelatorImpl::get
static llvm::Expected< std::unique_ptr< InstrProfCorrelatorImpl< IntPtrT > > > get(std::unique_ptr< InstrProfCorrelator::Context > Ctx, const object::ObjectFile &Obj)
Definition: InstrProfCorrelator.cpp:115
llvm::DWARFDie::getParent
DWARFDie getParent() const
Get the parent of this DIE object.
Definition: DWARFDie.cpp:1136
llvm::DWARFUnit::getAddressByteSize
uint8_t getAddressByteSize() const
Definition: DWARFUnit.h:286
llvm::createStringError
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1241
llvm::GraphProgram::Name
Name
Definition: GraphWriter.h:52
std
Definition: BitVector.h:838
get
Should compile to something r4 addze r3 instead we get
Definition: README.txt:24
llvm::AMDGPU::SendMsg::Op
Op
Definition: SIDefines.h:325
llvm::SectionName
Definition: DWARFSection.h:21
llvm::Error
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
llvm::object::Binary::isMachO
bool isMachO() const
Definition: Binary.h:124
llvm::errorOrToExpected
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
Definition: Error.h:1181
llvm::DataExtractor
Definition: DataExtractor.h:41
llvm::DWARFDie::getTag
dwarf::Tag getTag() const
Definition: DWARFDie.h:72
llvm::sys::IsLittleEndianHost
static const bool IsLittleEndianHost
Definition: SwapByteOrder.h:101
llvm::instrprof_error::unable_to_correlate_profile
@ unable_to_correlate_profile
llvm::object::ObjectFile::sections
section_iterator_range sections() const
Definition: ObjectFile.h:321
llvm::object::createBinary
Expected< std::unique_ptr< Binary > > createBinary(MemoryBufferRef Source, LLVMContext *Context=nullptr, bool InitContent=true)
Create a Binary from Source, autodetecting the file type.
Definition: Binary.cpp:46
llvm::InstrProfCorrelator
InstrProfCorrelator - A base class used to create raw instrumentation data to their functions.
Definition: InstrProfCorrelator.h:29
InstrProfCorrelator.h
getLocation
static MemoryLocation getLocation(Instruction *I)
Definition: SLPVectorizer.cpp:584
llvm::DWARFDie
Utility class that carries the DWARF compile/type unit and the debug info entry in an object.
Definition: DWARFDie.h:43
llvm::StringRef::begin
iterator begin() const
Definition: StringRef.h:127
CU
Definition: AArch64AsmBackend.cpp:504
llvm::StringRef::compare
LLVM_NODISCARD int compare(StringRef RHS) const
compare - Compare two strings; the result is -1, 0, or 1 if this string is lexicographically less tha...
Definition: StringRef.h:200
Debug.h