1 //===-- ProfiledBinary.cpp - Binary decoder ---------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ProfiledBinary.h"
10 #include "ErrorHandling.h"
11 #include "ProfileGenerator.h"
12 #include "llvm/ADT/Triple.h"
13 #include "llvm/Demangle/Demangle.h"
14 #include "llvm/IR/DebugInfoMetadata.h"
15 #include "llvm/Support/CommandLine.h"
16 #include "llvm/Support/Format.h"
17 #include "llvm/Support/TargetRegistry.h"
18 #include "llvm/Support/TargetSelect.h"
19 
20 #define DEBUG_TYPE "load-binary"
21 
22 using namespace llvm;
23 using namespace sampleprof;
24 
25 cl::opt<bool> ShowDisassemblyOnly("show-disassembly-only", cl::ReallyHidden,
26                                   cl::init(false), cl::ZeroOrMore,
27                                   cl::desc("Print disassembled code."));
28 
29 cl::opt<bool> ShowSourceLocations("show-source-locations", cl::ReallyHidden,
30                                   cl::init(false), cl::ZeroOrMore,
31                                   cl::desc("Print source locations."));
32 
33 cl::opt<bool> ShowCanonicalFnName("show-canonical-fname", cl::ReallyHidden,
34                                   cl::init(false), cl::ZeroOrMore,
35                                   cl::desc("Print canonical function name."));
36 
37 cl::opt<bool> ShowPseudoProbe(
38     "show-pseudo-probe", cl::ReallyHidden, cl::init(false), cl::ZeroOrMore,
39     cl::desc("Print pseudo probe section and disassembled info."));
40 
41 static cl::list<std::string> DisassembleFunctions(
42     "disassemble-functions", cl::CommaSeparated,
43     cl::desc("List of functions to print disassembly for. Accept demangled "
44              "names only. Only work with show-disassembly-only"));
45 
46 namespace llvm {
47 namespace sampleprof {
48 
49 static const Target *getTarget(const ObjectFile *Obj) {
50   Triple TheTriple = Obj->makeTriple();
51   std::string Error;
52   std::string ArchName;
53   const Target *TheTarget =
54       TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
55   if (!TheTarget)
56     exitWithError(Error, Obj->getFileName());
57   return TheTarget;
58 }
59 
60 void BinarySizeContextTracker::addInstructionForContext(
61     const SampleContextFrameVector &Context, uint32_t InstrSize) {
62   ContextTrieNode *CurNode = &RootContext;
63   bool IsLeaf = true;
64   for (const auto &Callsite : reverse(Context)) {
65     StringRef CallerName = Callsite.CallerName;
66     LineLocation CallsiteLoc = IsLeaf ? LineLocation(0, 0) : Callsite.Callsite;
67     CurNode = CurNode->getOrCreateChildContext(CallsiteLoc, CallerName);
68     IsLeaf = false;
69   }
70 
71   CurNode->addFunctionSize(InstrSize);
72 }
73 
74 uint32_t
75 BinarySizeContextTracker::getFuncSizeForContext(const SampleContext &Context) {
76   ContextTrieNode *CurrNode = &RootContext;
77   ContextTrieNode *PrevNode = nullptr;
78   SampleContextFrames Frames = Context.getContextFrames();
79   int32_t I = Frames.size() - 1;
80   Optional<uint32_t> Size;
81 
82   // Start from top-level context-less function, traverse down the reverse
83   // context trie to find the best/longest match for given context, then
84   // retrieve the size.
85 
86   while (CurrNode && I >= 0) {
87     // Process from leaf function to callers (added to context).
88     const auto &ChildFrame = Frames[I--];
89     PrevNode = CurrNode;
90     CurrNode =
91         CurrNode->getChildContext(ChildFrame.Callsite, ChildFrame.CallerName);
92     if (CurrNode && CurrNode->getFunctionSize().hasValue())
93       Size = CurrNode->getFunctionSize().getValue();
94   }
95 
96   // If we traversed all nodes along the path of the context and haven't
97   // found a size yet, pivot to look for size from sibling nodes, i.e size
98   // of inlinee under different context.
99   if (!Size.hasValue()) {
100     if (!CurrNode)
101       CurrNode = PrevNode;
102     while (!Size.hasValue() && CurrNode &&
103            !CurrNode->getAllChildContext().empty()) {
104       CurrNode = &CurrNode->getAllChildContext().begin()->second;
105       if (CurrNode->getFunctionSize().hasValue())
106         Size = CurrNode->getFunctionSize().getValue();
107     }
108   }
109 
110   assert(Size.hasValue() && "We should at least find one context size.");
111   return Size.getValue();
112 }
113 
114 void BinarySizeContextTracker::trackInlineesOptimizedAway(
115     MCPseudoProbeDecoder &ProbeDecoder) {
116   ProbeFrameStack ProbeContext;
117   for (const auto &Child : ProbeDecoder.getDummyInlineRoot().getChildren())
118     trackInlineesOptimizedAway(ProbeDecoder, *Child.second.get(), ProbeContext);
119 }
120 
121 void BinarySizeContextTracker::trackInlineesOptimizedAway(
122     MCPseudoProbeDecoder &ProbeDecoder,
123     MCDecodedPseudoProbeInlineTree &ProbeNode, ProbeFrameStack &ProbeContext) {
124   StringRef FuncName =
125       ProbeDecoder.getFuncDescForGUID(ProbeNode.Guid)->FuncName;
126   ProbeContext.emplace_back(FuncName, 0);
127 
128   // This ProbeContext has a probe, so it has code before inlining and
129   // optimization. Make sure we mark its size as known.
130   if (!ProbeNode.getProbes().empty()) {
131     ContextTrieNode *SizeContext = &RootContext;
132     for (auto &ProbeFrame : reverse(ProbeContext)) {
133       StringRef CallerName = ProbeFrame.first;
134       LineLocation CallsiteLoc(ProbeFrame.second, 0);
135       SizeContext =
136           SizeContext->getOrCreateChildContext(CallsiteLoc, CallerName);
137     }
138     // Add 0 size to make known.
139     SizeContext->addFunctionSize(0);
140   }
141 
142   // DFS down the probe inline tree
143   for (const auto &ChildNode : ProbeNode.getChildren()) {
144     InlineSite Location = ChildNode.first;
145     ProbeContext.back().second = std::get<1>(Location);
146     trackInlineesOptimizedAway(ProbeDecoder, *ChildNode.second.get(), ProbeContext);
147   }
148 
149   ProbeContext.pop_back();
150 }
151 
152 void ProfiledBinary::load() {
153   // Attempt to open the binary.
154   OwningBinary<Binary> OBinary = unwrapOrError(createBinary(Path), Path);
155   Binary &Binary = *OBinary.getBinary();
156 
157   auto *Obj = dyn_cast<ELFObjectFileBase>(&Binary);
158   if (!Obj)
159     exitWithError("not a valid Elf image", Path);
160 
161   TheTriple = Obj->makeTriple();
162   // Current only support X86
163   if (!TheTriple.isX86())
164     exitWithError("unsupported target", TheTriple.getTriple());
165   LLVM_DEBUG(dbgs() << "Loading " << Path << "\n");
166 
167   // Find the preferred load address for text sections.
168   setPreferredTextSegmentAddresses(Obj);
169 
170   // Decode pseudo probe related section
171   decodePseudoProbe(Obj);
172 
173   // Disassemble the text sections.
174   disassemble(Obj);
175 
176   // Track size for optimized inlinees when probe is available
177   if (UsePseudoProbes && TrackFuncContextSize)
178     FuncSizeTracker.trackInlineesOptimizedAway(ProbeDecoder);
179 
180   // Use function start and return address to infer prolog and epilog
181   ProEpilogTracker.inferPrologOffsets(FuncStartOffsetMap);
182   ProEpilogTracker.inferEpilogOffsets(RetAddrs);
183 
184   // TODO: decode other sections.
185 }
186 
187 bool ProfiledBinary::inlineContextEqual(uint64_t Address1, uint64_t Address2) {
188   uint64_t Offset1 = virtualAddrToOffset(Address1);
189   uint64_t Offset2 = virtualAddrToOffset(Address2);
190   const SampleContextFrameVector &Context1 = getFrameLocationStack(Offset1);
191   const SampleContextFrameVector &Context2 = getFrameLocationStack(Offset2);
192   if (Context1.size() != Context2.size())
193     return false;
194   if (Context1.empty())
195     return false;
196   // The leaf frame contains location within the leaf, and it
197   // needs to be remove that as it's not part of the calling context
198   return std::equal(Context1.begin(), Context1.begin() + Context1.size() - 1,
199                     Context2.begin(), Context2.begin() + Context2.size() - 1);
200 }
201 
202 SampleContextFrameVector
203 ProfiledBinary::getExpandedContext(const SmallVectorImpl<uint64_t> &Stack,
204                                    bool &WasLeafInlined) {
205   SampleContextFrameVector ContextVec;
206   // Process from frame root to leaf
207   for (auto Address : Stack) {
208     uint64_t Offset = virtualAddrToOffset(Address);
209     const SampleContextFrameVector &ExpandedContext =
210         getFrameLocationStack(Offset);
211     // An instruction without a valid debug line will be ignored by sample
212     // processing
213     if (ExpandedContext.empty())
214       return SampleContextFrameVector();
215     // Set WasLeafInlined to the size of inlined frame count for the last
216     // address which is leaf
217     WasLeafInlined = (ExpandedContext.size() > 1);
218     ContextVec.append(ExpandedContext);
219   }
220 
221   assert(ContextVec.size() && "Context length should be at least 1");
222 
223   // Compress the context string except for the leaf frame
224   auto LeafFrame = ContextVec.back();
225   LeafFrame.Callsite = LineLocation(0, 0);
226   ContextVec.pop_back();
227   CSProfileGenerator::compressRecursionContext(ContextVec);
228   CSProfileGenerator::trimContext(ContextVec);
229   ContextVec.push_back(LeafFrame);
230   return ContextVec;
231 }
232 
233 template <class ELFT>
234 void ProfiledBinary::setPreferredTextSegmentAddresses(const ELFFile<ELFT> &Obj, StringRef FileName) {
235   const auto &PhdrRange = unwrapOrError(Obj.program_headers(), FileName);
236   for (const typename ELFT::Phdr &Phdr : PhdrRange) {
237     if ((Phdr.p_type == ELF::PT_LOAD) && (Phdr.p_flags & ELF::PF_X)) {
238         // Segments will always be loaded at a page boundary.
239         PreferredTextSegmentAddresses.push_back(Phdr.p_vaddr & ~(Phdr.p_align - 1U));
240         TextSegmentOffsets.push_back(Phdr.p_offset & ~(Phdr.p_align - 1U));
241       }
242   }
243 
244   if (PreferredTextSegmentAddresses.empty())
245     exitWithError("no executable segment found", FileName);
246 }
247 
248 void ProfiledBinary::setPreferredTextSegmentAddresses(const ELFObjectFileBase *Obj) {
249   if (const auto *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj))
250     setPreferredTextSegmentAddresses(ELFObj->getELFFile(), Obj->getFileName());
251   else if (const auto *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj))
252     setPreferredTextSegmentAddresses(ELFObj->getELFFile(), Obj->getFileName());
253   else if (const auto *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj))
254     setPreferredTextSegmentAddresses(ELFObj->getELFFile(), Obj->getFileName());
255   else if (const auto *ELFObj = cast<ELF64BEObjectFile>(Obj))
256     setPreferredTextSegmentAddresses(ELFObj->getELFFile(), Obj->getFileName());
257   else
258     llvm_unreachable("invalid ELF object format");
259 }
260 
261 void ProfiledBinary::decodePseudoProbe(const ELFObjectFileBase *Obj) {
262   StringRef FileName = Obj->getFileName();
263   for (section_iterator SI = Obj->section_begin(), SE = Obj->section_end();
264        SI != SE; ++SI) {
265     const SectionRef &Section = *SI;
266     StringRef SectionName = unwrapOrError(Section.getName(), FileName);
267 
268     if (SectionName == ".pseudo_probe_desc") {
269       StringRef Contents = unwrapOrError(Section.getContents(), FileName);
270       if (!ProbeDecoder.buildGUID2FuncDescMap(
271               reinterpret_cast<const uint8_t *>(Contents.data()),
272               Contents.size()))
273         exitWithError("Pseudo Probe decoder fail in .pseudo_probe_desc section");
274     } else if (SectionName == ".pseudo_probe") {
275       StringRef Contents = unwrapOrError(Section.getContents(), FileName);
276       if (!ProbeDecoder.buildAddress2ProbeMap(
277               reinterpret_cast<const uint8_t *>(Contents.data()),
278               Contents.size()))
279         exitWithError("Pseudo Probe decoder fail in .pseudo_probe section");
280       // set UsePseudoProbes flag, used for PerfReader
281       UsePseudoProbes = true;
282     }
283   }
284 
285   if (ShowPseudoProbe)
286     ProbeDecoder.printGUID2FuncDescMap(outs());
287 }
288 
289 bool ProfiledBinary::dissassembleSymbol(std::size_t SI, ArrayRef<uint8_t> Bytes,
290                                         SectionSymbolsTy &Symbols,
291                                         const SectionRef &Section) {
292   std::size_t SE = Symbols.size();
293   uint64_t SectionOffset = Section.getAddress() - getPreferredBaseAddress();
294   uint64_t SectSize = Section.getSize();
295   uint64_t StartOffset = Symbols[SI].Addr - getPreferredBaseAddress();
296   uint64_t NextStartOffset =
297       (SI + 1 < SE) ? Symbols[SI + 1].Addr - getPreferredBaseAddress()
298                     : SectionOffset + SectSize;
299   if (StartOffset >= NextStartOffset)
300     return true;
301 
302   StringRef SymbolName =
303       ShowCanonicalFnName
304           ? FunctionSamples::getCanonicalFnName(Symbols[SI].Name)
305           : Symbols[SI].Name;
306   bool ShowDisassembly =
307       ShowDisassemblyOnly && (DisassembleFunctionSet.empty() ||
308                               DisassembleFunctionSet.count(SymbolName));
309   if (ShowDisassembly)
310     outs() << '<' << SymbolName << ">:\n";
311 
312   auto WarnInvalidInsts = [](uint64_t Start, uint64_t End) {
313     WithColor::warning() << "Invalid instructions at "
314                          << format("%8" PRIx64, Start) << " - "
315                          << format("%8" PRIx64, End) << "\n";
316   };
317 
318   uint64_t Offset = StartOffset;
319   uint64_t EndOffset = 0;
320   // Size of a consecutive invalid instruction range starting from Offset -1
321   // backwards.
322   uint64_t InvalidInstLength = 0;
323   while (Offset < NextStartOffset) {
324     MCInst Inst;
325     uint64_t Size;
326     // Disassemble an instruction.
327     bool Disassembled =
328         DisAsm->getInstruction(Inst, Size, Bytes.slice(Offset - SectionOffset),
329                                Offset + getPreferredBaseAddress(), nulls());
330     if (Size == 0)
331       Size = 1;
332 
333     if (ShowDisassembly) {
334       if (ShowPseudoProbe) {
335         ProbeDecoder.printProbeForAddress(outs(),
336                                           Offset + getPreferredBaseAddress());
337       }
338       outs() << format("%8" PRIx64 ":", Offset + getPreferredBaseAddress());
339       size_t Start = outs().tell();
340       if (Disassembled)
341         IPrinter->printInst(&Inst, Offset + Size, "", *STI.get(), outs());
342       else
343         outs() << "\t<unknown>";
344       if (ShowSourceLocations) {
345         unsigned Cur = outs().tell() - Start;
346         if (Cur < 40)
347           outs().indent(40 - Cur);
348         InstructionPointer IP(this, Offset);
349         outs() << getReversedLocWithContext(
350             symbolize(IP, ShowCanonicalFnName, ShowPseudoProbe));
351       }
352       outs() << "\n";
353     }
354 
355     if (Disassembled) {
356       const MCInstrDesc &MCDesc = MII->get(Inst.getOpcode());
357 
358       // Record instruction size.
359       Offset2InstSizeMap[Offset] = Size;
360 
361       // Populate address maps.
362       CodeAddrOffsets.push_back(Offset);
363       if (MCDesc.isCall())
364         CallAddrs.insert(Offset);
365       else if (MCDesc.isReturn())
366         RetAddrs.insert(Offset);
367 
368       EndOffset = Offset;
369 
370       if (InvalidInstLength) {
371         WarnInvalidInsts(Offset - InvalidInstLength, Offset - 1);
372         InvalidInstLength = 0;
373       }
374     } else {
375       InvalidInstLength += Size;
376     }
377 
378     Offset += Size;
379   }
380 
381   if (InvalidInstLength)
382     WarnInvalidInsts(Offset - InvalidInstLength, Offset - 1);
383 
384   if (ShowDisassembly)
385     outs() << "\n";
386 
387   FuncStartOffsetMap.emplace(StartOffset,
388                              std::make_pair(Symbols[SI].Name.str(), EndOffset));
389   return true;
390 }
391 
392 void ProfiledBinary::setUpDisassembler(const ELFObjectFileBase *Obj) {
393   const Target *TheTarget = getTarget(Obj);
394   std::string TripleName = TheTriple.getTriple();
395   StringRef FileName = Obj->getFileName();
396 
397   MRI.reset(TheTarget->createMCRegInfo(TripleName));
398   if (!MRI)
399     exitWithError("no register info for target " + TripleName, FileName);
400 
401   MCTargetOptions MCOptions;
402   AsmInfo.reset(TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
403   if (!AsmInfo)
404     exitWithError("no assembly info for target " + TripleName, FileName);
405 
406   SubtargetFeatures Features = Obj->getFeatures();
407   STI.reset(
408       TheTarget->createMCSubtargetInfo(TripleName, "", Features.getString()));
409   if (!STI)
410     exitWithError("no subtarget info for target " + TripleName, FileName);
411 
412   MII.reset(TheTarget->createMCInstrInfo());
413   if (!MII)
414     exitWithError("no instruction info for target " + TripleName, FileName);
415 
416   MCContext Ctx(Triple(TripleName), AsmInfo.get(), MRI.get(), STI.get());
417   std::unique_ptr<MCObjectFileInfo> MOFI(
418       TheTarget->createMCObjectFileInfo(Ctx, /*PIC=*/false));
419   Ctx.setObjectFileInfo(MOFI.get());
420   DisAsm.reset(TheTarget->createMCDisassembler(*STI, Ctx));
421   if (!DisAsm)
422     exitWithError("no disassembler for target " + TripleName, FileName);
423 
424   MIA.reset(TheTarget->createMCInstrAnalysis(MII.get()));
425 
426   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
427   IPrinter.reset(TheTarget->createMCInstPrinter(
428       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
429   IPrinter->setPrintBranchImmAsAddress(true);
430 }
431 
432 void ProfiledBinary::disassemble(const ELFObjectFileBase *Obj) {
433   // Set up disassembler and related components.
434   setUpDisassembler(Obj);
435 
436   // Create a mapping from virtual address to symbol name. The symbols in text
437   // sections are the candidates to dissassemble.
438   std::map<SectionRef, SectionSymbolsTy> AllSymbols;
439   StringRef FileName = Obj->getFileName();
440   for (const SymbolRef &Symbol : Obj->symbols()) {
441     const uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
442     const StringRef Name = unwrapOrError(Symbol.getName(), FileName);
443     section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
444     if (SecI != Obj->section_end())
445       AllSymbols[*SecI].push_back(SymbolInfoTy(Addr, Name, ELF::STT_NOTYPE));
446   }
447 
448   // Sort all the symbols. Use a stable sort to stabilize the output.
449   for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
450     stable_sort(SecSyms.second);
451 
452   DisassembleFunctionSet.insert(DisassembleFunctions.begin(),
453                                 DisassembleFunctions.end());
454   assert((DisassembleFunctionSet.empty() || ShowDisassemblyOnly) &&
455          "Functions to disassemble should be only specified together with "
456          "--show-disassembly-only");
457 
458   if (ShowDisassemblyOnly)
459     outs() << "\nDisassembly of " << FileName << ":\n";
460 
461   // Dissassemble a text section.
462   for (section_iterator SI = Obj->section_begin(), SE = Obj->section_end();
463        SI != SE; ++SI) {
464     const SectionRef &Section = *SI;
465     if (!Section.isText())
466       continue;
467 
468     uint64_t ImageLoadAddr = getPreferredBaseAddress();
469     uint64_t SectionOffset = Section.getAddress() - ImageLoadAddr;
470     uint64_t SectSize = Section.getSize();
471     if (!SectSize)
472       continue;
473 
474     // Register the text section.
475     TextSections.insert({SectionOffset, SectSize});
476 
477     if (ShowDisassemblyOnly) {
478       StringRef SectionName = unwrapOrError(Section.getName(), FileName);
479       outs() << "\nDisassembly of section " << SectionName;
480       outs() << " [" << format("0x%" PRIx64, Section.getAddress()) << ", "
481              << format("0x%" PRIx64, Section.getAddress() + SectSize)
482              << "]:\n\n";
483     }
484 
485     // Get the section data.
486     ArrayRef<uint8_t> Bytes =
487         arrayRefFromStringRef(unwrapOrError(Section.getContents(), FileName));
488 
489     // Get the list of all the symbols in this section.
490     SectionSymbolsTy &Symbols = AllSymbols[Section];
491 
492     // Disassemble symbol by symbol.
493     for (std::size_t SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
494       if (!dissassembleSymbol(SI, Bytes, Symbols, Section))
495         exitWithError("disassembling error", FileName);
496     }
497   }
498 }
499 
500 void ProfiledBinary::setupSymbolizer() {
501   symbolize::LLVMSymbolizer::Options SymbolizerOpts;
502   SymbolizerOpts.PrintFunctions =
503       DILineInfoSpecifier::FunctionNameKind::LinkageName;
504   SymbolizerOpts.Demangle = false;
505   SymbolizerOpts.DefaultArch = TheTriple.getArchName().str();
506   SymbolizerOpts.UseSymbolTable = false;
507   SymbolizerOpts.RelativeAddresses = false;
508   Symbolizer = std::make_unique<symbolize::LLVMSymbolizer>(SymbolizerOpts);
509 }
510 
511 SampleContextFrameVector ProfiledBinary::symbolize(const InstructionPointer &IP,
512                                                    bool UseCanonicalFnName,
513                                                    bool UseProbeDiscriminator) {
514   assert(this == IP.Binary &&
515          "Binary should only symbolize its own instruction");
516   auto Addr = object::SectionedAddress{IP.Offset + getPreferredBaseAddress(),
517                                        object::SectionedAddress::UndefSection};
518   DIInliningInfo InlineStack =
519       unwrapOrError(Symbolizer->symbolizeInlinedCode(Path, Addr), getName());
520 
521   SampleContextFrameVector CallStack;
522   for (int32_t I = InlineStack.getNumberOfFrames() - 1; I >= 0; I--) {
523     const auto &CallerFrame = InlineStack.getFrame(I);
524     if (CallerFrame.FunctionName == "<invalid>")
525       break;
526 
527     StringRef FunctionName(CallerFrame.FunctionName);
528     if (UseCanonicalFnName)
529       FunctionName = FunctionSamples::getCanonicalFnName(FunctionName);
530 
531     uint32_t Discriminator = CallerFrame.Discriminator;
532     uint32_t LineOffset = CallerFrame.Line - CallerFrame.StartLine;
533     if (UseProbeDiscriminator) {
534       LineOffset =
535           PseudoProbeDwarfDiscriminator::extractProbeIndex(Discriminator);
536       Discriminator = 0;
537     } else {
538       Discriminator = DILocation::getBaseDiscriminatorFromDiscriminator(
539           CallerFrame.Discriminator,
540           /* IsFSDiscriminator */ false);
541     }
542 
543     LineLocation Line(LineOffset, Discriminator);
544     auto It = NameStrings.insert(FunctionName.str());
545     CallStack.emplace_back(*It.first, Line);
546   }
547 
548   return CallStack;
549 }
550 
551 void ProfiledBinary::computeInlinedContextSizeForRange(uint64_t StartOffset,
552                                                        uint64_t EndOffset) {
553   uint32_t Index = getIndexForOffset(StartOffset);
554   if (CodeAddrOffsets[Index] != StartOffset)
555     WithColor::warning() << "Invalid start instruction at "
556                          << format("%8" PRIx64, StartOffset) << "\n";
557 
558   uint64_t Offset = CodeAddrOffsets[Index];
559   while (Offset <= EndOffset) {
560     const SampleContextFrameVector &SymbolizedCallStack =
561         getFrameLocationStack(Offset, UsePseudoProbes);
562     uint64_t Size = Offset2InstSizeMap[Offset];
563 
564     // Record instruction size for the corresponding context
565     FuncSizeTracker.addInstructionForContext(SymbolizedCallStack, Size);
566 
567     Offset = CodeAddrOffsets[++Index];
568   }
569 }
570 
571 InstructionPointer::InstructionPointer(const ProfiledBinary *Binary,
572                                        uint64_t Address, bool RoundToNext)
573     : Binary(Binary), Address(Address) {
574   Index = Binary->getIndexForAddr(Address);
575   if (RoundToNext) {
576     // we might get address which is not the code
577     // it should round to the next valid address
578     this->Address = Binary->getAddressforIndex(Index);
579   }
580 }
581 
582 void InstructionPointer::advance() {
583   Index++;
584   Address = Binary->getAddressforIndex(Index);
585 }
586 
587 void InstructionPointer::backward() {
588   Index--;
589   Address = Binary->getAddressforIndex(Index);
590 }
591 
592 void InstructionPointer::update(uint64_t Addr) {
593   Address = Addr;
594   Index = Binary->getIndexForAddr(Address);
595 }
596 
597 } // end namespace sampleprof
598 } // end namespace llvm
599