1 //===-- ProfiledBinary.h - Binary decoder -----------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_TOOLS_LLVM_PROFGEN_PROFILEDBINARY_H
10 #define LLVM_TOOLS_LLVM_PROFGEN_PROFILEDBINARY_H
12 #include "CallContext.h"
13 #include "ErrorHandling.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/ADT/StringSet.h"
17 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
18 #include "llvm/DebugInfo/Symbolize/Symbolize.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCInstPrinter.h"
24 #include "llvm/MC/MCInstrAnalysis.h"
25 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCObjectFileInfo.h"
27 #include "llvm/MC/MCPseudoProbe.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/MC/MCTargetOptions.h"
31 #include "llvm/Object/ELFObjectFile.h"
32 #include "llvm/ProfileData/SampleProf.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Transforms/IPO/SampleContextTracker.h"
41 #include <unordered_map>
42 #include <unordered_set>
46 extern cl::opt
<bool> EnableCSPreInliner
;
47 extern cl::opt
<bool> UseContextCostForPreInliner
;
51 using namespace sampleprof
;
52 using namespace llvm::object
;
55 namespace sampleprof
{
58 class MissingFrameInferrer
;
60 struct InstructionPointer
{
61 const ProfiledBinary
*Binary
;
62 // Address of the executable segment of the binary.
64 // Index to the sorted code address array of the binary.
66 InstructionPointer(const ProfiledBinary
*Binary
, uint64_t Address
,
67 bool RoundToNext
= false);
70 void update(uint64_t Addr
);
73 // The special frame addresses.
74 enum SpecialFrameAddr
{
75 // Dummy root of frame trie.
77 // Represent all the addresses outside of current binary.
78 // This's also used to indicate the call stack should be truncated since this
79 // isn't a real call context the compiler will see.
83 using RangesTy
= std::vector
<std::pair
<uint64_t, uint64_t>>;
85 struct BinaryFunction
{
87 // End of range is an exclusive bound.
90 uint64_t getFuncSize() {
92 for (auto &R
: Ranges
) {
93 Sum
+= R
.second
- R
.first
;
99 // Info about function range. A function can be split into multiple
100 // non-continuous ranges, each range corresponds to one FuncRange.
102 uint64_t StartAddress
;
103 // EndAddress is an exclusive bound.
105 // Function the range belongs to
106 BinaryFunction
*Func
;
107 // Whether the start address is the real entry of the function.
108 bool IsFuncEntry
= false;
110 StringRef
getFuncName() { return Func
->FuncName
; }
113 // PrologEpilog address tracker, used to filter out broken stack samples
114 // Currently we use a heuristic size (two) to infer prolog and epilog
115 // based on the start address and return address. In the future,
116 // we will switch to Dwarf CFI based tracker
117 struct PrologEpilogTracker
{
118 // A set of prolog and epilog addresses. Used by virtual unwinding.
119 std::unordered_set
<uint64_t> PrologEpilogSet
;
120 ProfiledBinary
*Binary
;
121 PrologEpilogTracker(ProfiledBinary
*Bin
) : Binary(Bin
){};
123 // Take the two addresses from the start of function as prolog
125 inferPrologAddresses(std::map
<uint64_t, FuncRange
> &FuncStartAddressMap
) {
126 for (auto I
: FuncStartAddressMap
) {
127 PrologEpilogSet
.insert(I
.first
);
128 InstructionPointer
IP(Binary
, I
.first
);
131 PrologEpilogSet
.insert(IP
.Address
);
135 // Take the last two addresses before the return address as epilog
136 void inferEpilogAddresses(std::unordered_set
<uint64_t> &RetAddrs
) {
137 for (auto Addr
: RetAddrs
) {
138 PrologEpilogSet
.insert(Addr
);
139 InstructionPointer
IP(Binary
, Addr
);
142 PrologEpilogSet
.insert(IP
.Address
);
147 // Track function byte size under different context (outlined version as well as
148 // various inlined versions). It also provides query support to get function
149 // size with the best matching context, which is used to help pre-inliner use
150 // accurate post-optimization size to make decisions.
151 // TODO: If an inlinee is completely optimized away, ideally we should have zero
152 // for its context size, currently we would misss such context since it doesn't
153 // have instructions. To fix this, we need to mark all inlinee with entry probe
154 // but without instructions as having zero size.
155 class BinarySizeContextTracker
{
157 // Add instruction with given size to a context
158 void addInstructionForContext(const SampleContextFrameVector
&Context
,
161 // Get function size with a specific context. When there's no exact match
162 // for the given context, try to retrieve the size of that function from
163 // closest matching context.
164 uint32_t getFuncSizeForContext(const ContextTrieNode
*Context
);
166 // For inlinees that are full optimized away, we can establish zero size using
167 // their remaining probes.
168 void trackInlineesOptimizedAway(MCPseudoProbeDecoder
&ProbeDecoder
);
170 using ProbeFrameStack
= SmallVector
<std::pair
<StringRef
, uint32_t>>;
171 void trackInlineesOptimizedAway(MCPseudoProbeDecoder
&ProbeDecoder
,
172 MCDecodedPseudoProbeInlineTree
&ProbeNode
,
173 ProbeFrameStack
&Context
);
175 void dump() { RootContext
.dumpTree(); }
178 // Root node for context trie tree, node that this is a reverse context trie
179 // with callee as parent and caller as child. This way we can traverse from
180 // root to find the best/longest matching context if an exact match does not
181 // exist. It gives us the best possible estimate for function's post-inline,
182 // post-optimization byte size.
183 ContextTrieNode RootContext
;
186 using AddressRange
= std::pair
<uint64_t, uint64_t>;
188 class ProfiledBinary
{
189 // Absolute path of the executable binary.
191 // Path of the debug info binary.
192 std::string DebugBinaryPath
;
193 // The target triple.
195 // Path of symbolizer path which should be pointed to binary with debug info.
196 StringRef SymbolizerPath
;
197 // Options used to configure the symbolizer
198 symbolize::LLVMSymbolizer::Options SymbolizerOpts
;
199 // The runtime base address that the first executable segment is loaded at.
200 uint64_t BaseAddress
= 0;
201 // The runtime base address that the first loadabe segment is loaded at.
202 uint64_t FirstLoadableAddress
= 0;
203 // The preferred load address of each executable segment.
204 std::vector
<uint64_t> PreferredTextSegmentAddresses
;
205 // The file offset of each executable segment.
206 std::vector
<uint64_t> TextSegmentOffsets
;
208 // Mutiple MC component info
209 std::unique_ptr
<const MCRegisterInfo
> MRI
;
210 std::unique_ptr
<const MCAsmInfo
> AsmInfo
;
211 std::unique_ptr
<const MCSubtargetInfo
> STI
;
212 std::unique_ptr
<const MCInstrInfo
> MII
;
213 std::unique_ptr
<MCDisassembler
> DisAsm
;
214 std::unique_ptr
<const MCInstrAnalysis
> MIA
;
215 std::unique_ptr
<MCInstPrinter
> IPrinter
;
216 // A list of text sections sorted by start RVA and size. Used to check
217 // if a given RVA is a valid code address.
218 std::set
<std::pair
<uint64_t, uint64_t>> TextSections
;
220 // A map of mapping function name to BinaryFunction info.
221 std::unordered_map
<std::string
, BinaryFunction
> BinaryFunctions
;
223 // A list of binary functions that have samples.
224 std::unordered_set
<const BinaryFunction
*> ProfiledFunctions
;
226 // GUID to Elf symbol start address map
227 DenseMap
<uint64_t, uint64_t> SymbolStartAddrs
;
229 // Start address to Elf symbol GUID map
230 std::unordered_multimap
<uint64_t, uint64_t> StartAddrToSymMap
;
232 // An ordered map of mapping function's start address to function range
233 // relevant info. Currently to determine if the offset of ELF is the start of
234 // a real function, we leverage the function range info from DWARF.
235 std::map
<uint64_t, FuncRange
> StartAddrToFuncRangeMap
;
237 // Address to context location map. Used to expand the context.
238 std::unordered_map
<uint64_t, SampleContextFrameVector
> AddressToLocStackMap
;
240 // Address to instruction size map. Also used for quick Address lookup.
241 std::unordered_map
<uint64_t, uint64_t> AddressToInstSizeMap
;
243 // An array of Addresses of all instructions sorted in increasing order. The
244 // sorting is needed to fast advance to the next forward/backward instruction.
245 std::vector
<uint64_t> CodeAddressVec
;
246 // A set of call instruction addresses. Used by virtual unwinding.
247 std::unordered_set
<uint64_t> CallAddressSet
;
248 // A set of return instruction addresses. Used by virtual unwinding.
249 std::unordered_set
<uint64_t> RetAddressSet
;
250 // An ordered set of unconditional branch instruction addresses.
251 std::set
<uint64_t> UncondBranchAddrSet
;
252 // A set of branch instruction addresses.
253 std::unordered_set
<uint64_t> BranchAddressSet
;
255 // Estimate and track function prolog and epilog ranges.
256 PrologEpilogTracker ProEpilogTracker
;
258 // Infer missing frames due to compiler optimizations such as tail call
260 std::unique_ptr
<MissingFrameInferrer
> MissingContextInferrer
;
262 // Track function sizes under different context
263 BinarySizeContextTracker FuncSizeTracker
;
265 // The symbolizer used to get inline context for an instruction.
266 std::unique_ptr
<symbolize::LLVMSymbolizer
> Symbolizer
;
268 // String table owning function name strings created from the symbolizer.
269 std::unordered_set
<std::string
> NameStrings
;
271 // A collection of functions to print disassembly for.
272 StringSet
<> DisassembleFunctionSet
;
274 // Pseudo probe decoder
275 MCPseudoProbeDecoder ProbeDecoder
;
277 // Function name to probe frame map for top-level outlined functions.
278 StringMap
<MCDecodedPseudoProbeInlineTree
*> TopLevelProbeFrameMap
;
280 bool UsePseudoProbes
= false;
282 bool UseFSDiscriminator
= false;
284 // Whether we need to symbolize all instructions to get function context size.
285 bool TrackFuncContextSize
= false;
287 // Indicate if the base loading address is parsed from the mmap event or uses
288 // the preferred address
289 bool IsLoadedByMMap
= false;
290 // Use to avoid redundant warning.
291 bool MissingMMapWarned
= false;
293 void setPreferredTextSegmentAddresses(const ELFObjectFileBase
*O
);
295 template <class ELFT
>
296 void setPreferredTextSegmentAddresses(const ELFFile
<ELFT
> &Obj
,
299 void checkPseudoProbe(const ELFObjectFileBase
*Obj
);
301 void decodePseudoProbe(const ELFObjectFileBase
*Obj
);
304 checkUseFSDiscriminator(const ELFObjectFileBase
*Obj
,
305 std::map
<SectionRef
, SectionSymbolsTy
> &AllSymbols
);
307 // Set up disassembler and related components.
308 void setUpDisassembler(const ELFObjectFileBase
*Obj
);
309 symbolize::LLVMSymbolizer::Options
getSymbolizerOpts() const;
311 // Load debug info of subprograms from DWARF section.
312 void loadSymbolsFromDWARF(ObjectFile
&Obj
);
314 // Load debug info from DWARF unit.
315 void loadSymbolsFromDWARFUnit(DWARFUnit
&CompilationUnit
);
317 // Create elf symbol to its start address mapping.
318 void populateElfSymbolAddressList(const ELFObjectFileBase
*O
);
320 // A function may be spilt into multiple non-continuous address ranges. We use
321 // this to set whether start a function range is the real entry of the
322 // function and also set false to the non-function label.
323 void setIsFuncEntry(FuncRange
*FRange
, StringRef RangeSymName
);
325 // Warn if no entry range exists in the function.
326 void warnNoFuncEntry();
328 /// Dissassemble the text section and build various address maps.
329 void disassemble(const ELFObjectFileBase
*O
);
331 /// Helper function to dissassemble the symbol and extract info for unwinding
332 bool dissassembleSymbol(std::size_t SI
, ArrayRef
<uint8_t> Bytes
,
333 SectionSymbolsTy
&Symbols
, const SectionRef
&Section
);
334 /// Symbolize a given instruction pointer and return a full call context.
335 SampleContextFrameVector
symbolize(const InstructionPointer
&IP
,
336 bool UseCanonicalFnName
= false,
337 bool UseProbeDiscriminator
= false);
338 /// Decode the interesting parts of the binary and build internal data
339 /// structures. On high level, the parts of interest are:
340 /// 1. Text sections, including the main code section and the PLT
341 /// entries that will be used to handle cross-module call transitions.
342 /// 2. The .debug_line section, used by Dwarf-based profile generation.
343 /// 3. Pseudo probe related sections, used by probe-based profile
348 ProfiledBinary(const StringRef ExeBinPath
, const StringRef DebugBinPath
);
351 void decodePseudoProbe();
353 StringRef
getPath() const { return Path
; }
354 StringRef
getName() const { return llvm::sys::path::filename(Path
); }
355 uint64_t getBaseAddress() const { return BaseAddress
; }
356 void setBaseAddress(uint64_t Address
) { BaseAddress
= Address
; }
358 // Canonicalize to use preferred load address as base address.
359 uint64_t canonicalizeVirtualAddress(uint64_t Address
) {
360 return Address
- BaseAddress
+ getPreferredBaseAddress();
362 // Return the preferred load address for the first executable segment.
363 uint64_t getPreferredBaseAddress() const {
364 return PreferredTextSegmentAddresses
[0];
366 // Return the preferred load address for the first loadable segment.
367 uint64_t getFirstLoadableAddress() const { return FirstLoadableAddress
; }
368 // Return the file offset for the first executable segment.
369 uint64_t getTextSegmentOffset() const { return TextSegmentOffsets
[0]; }
370 const std::vector
<uint64_t> &getPreferredTextSegmentAddresses() const {
371 return PreferredTextSegmentAddresses
;
373 const std::vector
<uint64_t> &getTextSegmentOffsets() const {
374 return TextSegmentOffsets
;
377 uint64_t getInstSize(uint64_t Address
) const {
378 auto I
= AddressToInstSizeMap
.find(Address
);
379 if (I
== AddressToInstSizeMap
.end())
384 bool addressIsCode(uint64_t Address
) const {
385 return AddressToInstSizeMap
.find(Address
) != AddressToInstSizeMap
.end();
388 bool addressIsCall(uint64_t Address
) const {
389 return CallAddressSet
.count(Address
);
391 bool addressIsReturn(uint64_t Address
) const {
392 return RetAddressSet
.count(Address
);
394 bool addressInPrologEpilog(uint64_t Address
) const {
395 return ProEpilogTracker
.PrologEpilogSet
.count(Address
);
398 bool addressIsTransfer(uint64_t Address
) {
399 return BranchAddressSet
.count(Address
) || RetAddressSet
.count(Address
) ||
400 CallAddressSet
.count(Address
);
403 bool rangeCrossUncondBranch(uint64_t Start
, uint64_t End
) {
406 auto R
= UncondBranchAddrSet
.lower_bound(Start
);
407 return R
!= UncondBranchAddrSet
.end() && *R
< End
;
410 uint64_t getAddressforIndex(uint64_t Index
) const {
411 return CodeAddressVec
[Index
];
414 size_t getCodeAddrVecSize() const { return CodeAddressVec
.size(); }
416 bool usePseudoProbes() const { return UsePseudoProbes
; }
417 bool useFSDiscriminator() const { return UseFSDiscriminator
; }
418 // Get the index in CodeAddressVec for the address
419 // As we might get an address which is not the code
420 // here it would round to the next valid code address by
421 // using lower bound operation
422 uint32_t getIndexForAddr(uint64_t Address
) const {
423 auto Low
= llvm::lower_bound(CodeAddressVec
, Address
);
424 return Low
- CodeAddressVec
.begin();
427 uint64_t getCallAddrFromFrameAddr(uint64_t FrameAddr
) const {
428 if (FrameAddr
== ExternalAddr
)
430 auto I
= getIndexForAddr(FrameAddr
);
431 FrameAddr
= I
? getAddressforIndex(I
- 1) : 0;
432 if (FrameAddr
&& addressIsCall(FrameAddr
))
437 FuncRange
*findFuncRangeForStartAddr(uint64_t Address
) {
438 auto I
= StartAddrToFuncRangeMap
.find(Address
);
439 if (I
== StartAddrToFuncRangeMap
.end())
444 // Binary search the function range which includes the input address.
445 FuncRange
*findFuncRange(uint64_t Address
) {
446 auto I
= StartAddrToFuncRangeMap
.upper_bound(Address
);
447 if (I
== StartAddrToFuncRangeMap
.begin())
451 if (Address
>= I
->second
.EndAddress
)
457 // Get all ranges of one function.
458 RangesTy
getRanges(uint64_t Address
) {
459 auto *FRange
= findFuncRange(Address
);
460 // Ignore the range which falls into plt section or system lib.
464 return FRange
->Func
->Ranges
;
467 const std::unordered_map
<std::string
, BinaryFunction
> &
468 getAllBinaryFunctions() {
469 return BinaryFunctions
;
472 std::unordered_set
<const BinaryFunction
*> &getProfiledFunctions() {
473 return ProfiledFunctions
;
476 void setProfiledFunctions(std::unordered_set
<const BinaryFunction
*> &Funcs
) {
477 ProfiledFunctions
= Funcs
;
480 BinaryFunction
*getBinaryFunction(StringRef FName
) {
481 auto I
= BinaryFunctions
.find(FName
.str());
482 if (I
== BinaryFunctions
.end())
487 uint32_t getFuncSizeForContext(const ContextTrieNode
*ContextNode
) {
488 return FuncSizeTracker
.getFuncSizeForContext(ContextNode
);
491 void inferMissingFrames(const SmallVectorImpl
<uint64_t> &Context
,
492 SmallVectorImpl
<uint64_t> &NewContext
);
494 // Load the symbols from debug table and populate into symbol list.
495 void populateSymbolListFromDWARF(ProfileSymbolList
&SymbolList
);
497 SampleContextFrameVector
498 getFrameLocationStack(uint64_t Address
, bool UseProbeDiscriminator
= false) {
499 InstructionPointer
IP(this, Address
);
500 return symbolize(IP
, SymbolizerOpts
.UseSymbolTable
, UseProbeDiscriminator
);
503 const SampleContextFrameVector
&
504 getCachedFrameLocationStack(uint64_t Address
,
505 bool UseProbeDiscriminator
= false) {
506 auto I
= AddressToLocStackMap
.emplace(Address
, SampleContextFrameVector());
508 I
.first
->second
= getFrameLocationStack(Address
, UseProbeDiscriminator
);
510 return I
.first
->second
;
513 std::optional
<SampleContextFrame
> getInlineLeafFrameLoc(uint64_t Address
) {
514 const auto &Stack
= getCachedFrameLocationStack(Address
);
520 void flushSymbolizer() { Symbolizer
.reset(); }
522 MissingFrameInferrer
* getMissingContextInferrer() {
523 return MissingContextInferrer
.get();
526 // Compare two addresses' inline context
527 bool inlineContextEqual(uint64_t Add1
, uint64_t Add2
);
529 // Get the full context of the current stack with inline context filled in.
530 // It will search the disassembling info stored in AddressToLocStackMap. This
531 // is used as the key of function sample map
532 SampleContextFrameVector
533 getExpandedContext(const SmallVectorImpl
<uint64_t> &Stack
,
534 bool &WasLeafInlined
);
535 // Go through instructions among the given range and record its size for the
537 void computeInlinedContextSizeForRange(uint64_t StartAddress
,
538 uint64_t EndAddress
);
540 void computeInlinedContextSizeForFunc(const BinaryFunction
*Func
);
542 const MCDecodedPseudoProbe
*getCallProbeForAddr(uint64_t Address
) const {
543 return ProbeDecoder
.getCallProbeForAddr(Address
);
546 void getInlineContextForProbe(const MCDecodedPseudoProbe
*Probe
,
547 SampleContextFrameVector
&InlineContextStack
,
548 bool IncludeLeaf
= false) const {
549 SmallVector
<MCPseduoProbeFrameLocation
, 16> ProbeInlineContext
;
550 ProbeDecoder
.getInlineContextForProbe(Probe
, ProbeInlineContext
,
552 for (uint32_t I
= 0; I
< ProbeInlineContext
.size(); I
++) {
553 auto &Callsite
= ProbeInlineContext
[I
];
554 // Clear the current context for an unknown probe.
555 if (Callsite
.second
== 0 && I
!= ProbeInlineContext
.size() - 1) {
556 InlineContextStack
.clear();
559 InlineContextStack
.emplace_back(Callsite
.first
,
560 LineLocation(Callsite
.second
, 0));
563 const AddressProbesMap
&getAddress2ProbesMap() const {
564 return ProbeDecoder
.getAddress2ProbesMap();
566 const MCPseudoProbeFuncDesc
*getFuncDescForGUID(uint64_t GUID
) {
567 return ProbeDecoder
.getFuncDescForGUID(GUID
);
570 const MCPseudoProbeFuncDesc
*
571 getInlinerDescForProbe(const MCDecodedPseudoProbe
*Probe
) {
572 return ProbeDecoder
.getInlinerDescForProbe(Probe
);
575 bool getTrackFuncContextSize() { return TrackFuncContextSize
; }
577 bool getIsLoadedByMMap() { return IsLoadedByMMap
; }
579 void setIsLoadedByMMap(bool Value
) { IsLoadedByMMap
= Value
; }
581 bool getMissingMMapWarned() { return MissingMMapWarned
; }
583 void setMissingMMapWarned(bool Value
) { MissingMMapWarned
= Value
; }
586 } // end namespace sampleprof
587 } // end namespace llvm