1 //===- bolt/Core/BinaryContext.cpp - Low-level context --------------------===//
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 // This file implements the BinaryContext class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "bolt/Core/BinaryContext.h"
14 #include "bolt/Core/BinaryEmitter.h"
15 #include "bolt/Core/BinaryFunction.h"
16 #include "bolt/Utils/CommandLineOpts.h"
17 #include "bolt/Utils/NameResolver.h"
18 #include "bolt/Utils/Utils.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
21 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
22 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
23 #include "llvm/MC/MCAsmLayout.h"
24 #include "llvm/MC/MCAssembler.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
27 #include "llvm/MC/MCInstPrinter.h"
28 #include "llvm/MC/MCObjectStreamer.h"
29 #include "llvm/MC/MCObjectWriter.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSectionELF.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSubtargetInfo.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Error.h"
37 #include "llvm/Support/Regex.h"
38 #include <algorithm>
39 #include <functional>
40 #include <iterator>
41 #include <unordered_set>
42 
43 using namespace llvm;
44 
45 #undef  DEBUG_TYPE
46 #define DEBUG_TYPE "bolt"
47 
48 namespace opts {
49 
50 cl::opt<bool> NoHugePages("no-huge-pages",
51                           cl::desc("use regular size pages for code alignment"),
52                           cl::Hidden, cl::cat(BoltCategory));
53 
54 static cl::opt<bool>
55 PrintDebugInfo("print-debug-info",
56   cl::desc("print debug info when printing functions"),
57   cl::Hidden,
58   cl::ZeroOrMore,
59   cl::cat(BoltCategory));
60 
61 cl::opt<bool> PrintRelocations(
62     "print-relocations",
63     cl::desc("print relocations when printing functions/objects"), cl::Hidden,
64     cl::cat(BoltCategory));
65 
66 static cl::opt<bool>
67 PrintMemData("print-mem-data",
68   cl::desc("print memory data annotations when printing functions"),
69   cl::Hidden,
70   cl::ZeroOrMore,
71   cl::cat(BoltCategory));
72 
73 } // namespace opts
74 
75 namespace llvm {
76 namespace bolt {
77 
78 BinaryContext::BinaryContext(std::unique_ptr<MCContext> Ctx,
79                              std::unique_ptr<DWARFContext> DwCtx,
80                              std::unique_ptr<Triple> TheTriple,
81                              const Target *TheTarget, std::string TripleName,
82                              std::unique_ptr<MCCodeEmitter> MCE,
83                              std::unique_ptr<MCObjectFileInfo> MOFI,
84                              std::unique_ptr<const MCAsmInfo> AsmInfo,
85                              std::unique_ptr<const MCInstrInfo> MII,
86                              std::unique_ptr<const MCSubtargetInfo> STI,
87                              std::unique_ptr<MCInstPrinter> InstPrinter,
88                              std::unique_ptr<const MCInstrAnalysis> MIA,
89                              std::unique_ptr<MCPlusBuilder> MIB,
90                              std::unique_ptr<const MCRegisterInfo> MRI,
91                              std::unique_ptr<MCDisassembler> DisAsm)
92     : Ctx(std::move(Ctx)), DwCtx(std::move(DwCtx)),
93       TheTriple(std::move(TheTriple)), TheTarget(TheTarget),
94       TripleName(TripleName), MCE(std::move(MCE)), MOFI(std::move(MOFI)),
95       AsmInfo(std::move(AsmInfo)), MII(std::move(MII)), STI(std::move(STI)),
96       InstPrinter(std::move(InstPrinter)), MIA(std::move(MIA)),
97       MIB(std::move(MIB)), MRI(std::move(MRI)), DisAsm(std::move(DisAsm)) {
98   Relocation::Arch = this->TheTriple->getArch();
99   RegularPageSize = isAArch64() ? RegularPageSizeAArch64 : RegularPageSizeX86;
100   PageAlign = opts::NoHugePages ? RegularPageSize : HugePageSize;
101 }
102 
103 BinaryContext::~BinaryContext() {
104   for (BinarySection *Section : Sections)
105     delete Section;
106   for (BinaryFunction *InjectedFunction : InjectedBinaryFunctions)
107     delete InjectedFunction;
108   for (std::pair<const uint64_t, JumpTable *> JTI : JumpTables)
109     delete JTI.second;
110   clearBinaryData();
111 }
112 
113 /// Create BinaryContext for a given architecture \p ArchName and
114 /// triple \p TripleName.
115 Expected<std::unique_ptr<BinaryContext>>
116 BinaryContext::createBinaryContext(const ObjectFile *File, bool IsPIC,
117                                    std::unique_ptr<DWARFContext> DwCtx) {
118   StringRef ArchName = "";
119   StringRef FeaturesStr = "";
120   switch (File->getArch()) {
121   case llvm::Triple::x86_64:
122     ArchName = "x86-64";
123     FeaturesStr = "+nopl";
124     break;
125   case llvm::Triple::aarch64:
126     ArchName = "aarch64";
127     FeaturesStr = "+all";
128     break;
129   default:
130     return createStringError(std::errc::not_supported,
131                              "BOLT-ERROR: Unrecognized machine in ELF file");
132   }
133 
134   auto TheTriple = std::make_unique<Triple>(File->makeTriple());
135   const std::string TripleName = TheTriple->str();
136 
137   std::string Error;
138   const Target *TheTarget =
139       TargetRegistry::lookupTarget(std::string(ArchName), *TheTriple, Error);
140   if (!TheTarget)
141     return createStringError(make_error_code(std::errc::not_supported),
142                              Twine("BOLT-ERROR: ", Error));
143 
144   std::unique_ptr<const MCRegisterInfo> MRI(
145       TheTarget->createMCRegInfo(TripleName));
146   if (!MRI)
147     return createStringError(
148         make_error_code(std::errc::not_supported),
149         Twine("BOLT-ERROR: no register info for target ", TripleName));
150 
151   // Set up disassembler.
152   std::unique_ptr<MCAsmInfo> AsmInfo(
153       TheTarget->createMCAsmInfo(*MRI, TripleName, MCTargetOptions()));
154   if (!AsmInfo)
155     return createStringError(
156         make_error_code(std::errc::not_supported),
157         Twine("BOLT-ERROR: no assembly info for target ", TripleName));
158   // BOLT creates "func@PLT" symbols for PLT entries. In function assembly dump
159   // we want to emit such names as using @PLT without double quotes to convey
160   // variant kind to the assembler. BOLT doesn't rely on the linker so we can
161   // override the default AsmInfo behavior to emit names the way we want.
162   AsmInfo->setAllowAtInName(true);
163 
164   std::unique_ptr<const MCSubtargetInfo> STI(
165       TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
166   if (!STI)
167     return createStringError(
168         make_error_code(std::errc::not_supported),
169         Twine("BOLT-ERROR: no subtarget info for target ", TripleName));
170 
171   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
172   if (!MII)
173     return createStringError(
174         make_error_code(std::errc::not_supported),
175         Twine("BOLT-ERROR: no instruction info for target ", TripleName));
176 
177   std::unique_ptr<MCContext> Ctx(
178       new MCContext(*TheTriple, AsmInfo.get(), MRI.get(), STI.get()));
179   std::unique_ptr<MCObjectFileInfo> MOFI(
180       TheTarget->createMCObjectFileInfo(*Ctx, IsPIC));
181   Ctx->setObjectFileInfo(MOFI.get());
182   // We do not support X86 Large code model. Change this in the future.
183   bool Large = false;
184   if (TheTriple->getArch() == llvm::Triple::aarch64)
185     Large = true;
186   unsigned LSDAEncoding =
187       Large ? dwarf::DW_EH_PE_absptr : dwarf::DW_EH_PE_udata4;
188   unsigned TTypeEncoding =
189       Large ? dwarf::DW_EH_PE_absptr : dwarf::DW_EH_PE_udata4;
190   if (IsPIC) {
191     LSDAEncoding = dwarf::DW_EH_PE_pcrel |
192                    (Large ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
193     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
194                     (Large ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
195   }
196 
197   std::unique_ptr<MCDisassembler> DisAsm(
198       TheTarget->createMCDisassembler(*STI, *Ctx));
199 
200   if (!DisAsm)
201     return createStringError(
202         make_error_code(std::errc::not_supported),
203         Twine("BOLT-ERROR: no disassembler info for target ", TripleName));
204 
205   std::unique_ptr<const MCInstrAnalysis> MIA(
206       TheTarget->createMCInstrAnalysis(MII.get()));
207   if (!MIA)
208     return createStringError(
209         make_error_code(std::errc::not_supported),
210         Twine("BOLT-ERROR: failed to create instruction analysis for target ",
211               TripleName));
212 
213   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
214   std::unique_ptr<MCInstPrinter> InstructionPrinter(
215       TheTarget->createMCInstPrinter(*TheTriple, AsmPrinterVariant, *AsmInfo,
216                                      *MII, *MRI));
217   if (!InstructionPrinter)
218     return createStringError(
219         make_error_code(std::errc::not_supported),
220         Twine("BOLT-ERROR: no instruction printer for target ", TripleName));
221   InstructionPrinter->setPrintImmHex(true);
222 
223   std::unique_ptr<MCCodeEmitter> MCE(
224       TheTarget->createMCCodeEmitter(*MII, *Ctx));
225 
226   // Make sure we don't miss any output on core dumps.
227   outs().SetUnbuffered();
228   errs().SetUnbuffered();
229   dbgs().SetUnbuffered();
230 
231   auto BC = std::make_unique<BinaryContext>(
232       std::move(Ctx), std::move(DwCtx), std::move(TheTriple), TheTarget,
233       std::string(TripleName), std::move(MCE), std::move(MOFI),
234       std::move(AsmInfo), std::move(MII), std::move(STI),
235       std::move(InstructionPrinter), std::move(MIA), nullptr, std::move(MRI),
236       std::move(DisAsm));
237 
238   BC->TTypeEncoding = TTypeEncoding;
239   BC->LSDAEncoding = LSDAEncoding;
240 
241   BC->MAB = std::unique_ptr<MCAsmBackend>(
242       BC->TheTarget->createMCAsmBackend(*BC->STI, *BC->MRI, MCTargetOptions()));
243 
244   BC->setFilename(File->getFileName());
245 
246   BC->HasFixedLoadAddress = !IsPIC;
247 
248   BC->SymbolicDisAsm = std::unique_ptr<MCDisassembler>(
249       BC->TheTarget->createMCDisassembler(*BC->STI, *BC->Ctx));
250 
251   if (!BC->SymbolicDisAsm)
252     return createStringError(
253         make_error_code(std::errc::not_supported),
254         Twine("BOLT-ERROR: no disassembler info for target ", TripleName));
255 
256   return std::move(BC);
257 }
258 
259 bool BinaryContext::forceSymbolRelocations(StringRef SymbolName) const {
260   if (opts::HotText &&
261       (SymbolName == "__hot_start" || SymbolName == "__hot_end"))
262     return true;
263 
264   if (opts::HotData &&
265       (SymbolName == "__hot_data_start" || SymbolName == "__hot_data_end"))
266     return true;
267 
268   if (SymbolName == "_end")
269     return true;
270 
271   return false;
272 }
273 
274 std::unique_ptr<MCObjectWriter>
275 BinaryContext::createObjectWriter(raw_pwrite_stream &OS) {
276   return MAB->createObjectWriter(OS);
277 }
278 
279 bool BinaryContext::validateObjectNesting() const {
280   auto Itr = BinaryDataMap.begin();
281   auto End = BinaryDataMap.end();
282   bool Valid = true;
283   while (Itr != End) {
284     auto Next = std::next(Itr);
285     while (Next != End &&
286            Itr->second->getSection() == Next->second->getSection() &&
287            Itr->second->containsRange(Next->second->getAddress(),
288                                       Next->second->getSize())) {
289       if (Next->second->Parent != Itr->second) {
290         errs() << "BOLT-WARNING: object nesting incorrect for:\n"
291                << "BOLT-WARNING:  " << *Itr->second << "\n"
292                << "BOLT-WARNING:  " << *Next->second << "\n";
293         Valid = false;
294       }
295       ++Next;
296     }
297     Itr = Next;
298   }
299   return Valid;
300 }
301 
302 bool BinaryContext::validateHoles() const {
303   bool Valid = true;
304   for (BinarySection &Section : sections()) {
305     for (const Relocation &Rel : Section.relocations()) {
306       uint64_t RelAddr = Rel.Offset + Section.getAddress();
307       const BinaryData *BD = getBinaryDataContainingAddress(RelAddr);
308       if (!BD) {
309         errs() << "BOLT-WARNING: no BinaryData found for relocation at address"
310                << " 0x" << Twine::utohexstr(RelAddr) << " in "
311                << Section.getName() << "\n";
312         Valid = false;
313       } else if (!BD->getAtomicRoot()) {
314         errs() << "BOLT-WARNING: no atomic BinaryData found for relocation at "
315                << "address 0x" << Twine::utohexstr(RelAddr) << " in "
316                << Section.getName() << "\n";
317         Valid = false;
318       }
319     }
320   }
321   return Valid;
322 }
323 
324 void BinaryContext::updateObjectNesting(BinaryDataMapType::iterator GAI) {
325   const uint64_t Address = GAI->second->getAddress();
326   const uint64_t Size = GAI->second->getSize();
327 
328   auto fixParents = [&](BinaryDataMapType::iterator Itr,
329                         BinaryData *NewParent) {
330     BinaryData *OldParent = Itr->second->Parent;
331     Itr->second->Parent = NewParent;
332     ++Itr;
333     while (Itr != BinaryDataMap.end() && OldParent &&
334            Itr->second->Parent == OldParent) {
335       Itr->second->Parent = NewParent;
336       ++Itr;
337     }
338   };
339 
340   // Check if the previous symbol contains the newly added symbol.
341   if (GAI != BinaryDataMap.begin()) {
342     BinaryData *Prev = std::prev(GAI)->second;
343     while (Prev) {
344       if (Prev->getSection() == GAI->second->getSection() &&
345           Prev->containsRange(Address, Size)) {
346         fixParents(GAI, Prev);
347       } else {
348         fixParents(GAI, nullptr);
349       }
350       Prev = Prev->Parent;
351     }
352   }
353 
354   // Check if the newly added symbol contains any subsequent symbols.
355   if (Size != 0) {
356     BinaryData *BD = GAI->second->Parent ? GAI->second->Parent : GAI->second;
357     auto Itr = std::next(GAI);
358     while (
359         Itr != BinaryDataMap.end() &&
360         BD->containsRange(Itr->second->getAddress(), Itr->second->getSize())) {
361       Itr->second->Parent = BD;
362       ++Itr;
363     }
364   }
365 }
366 
367 iterator_range<BinaryContext::binary_data_iterator>
368 BinaryContext::getSubBinaryData(BinaryData *BD) {
369   auto Start = std::next(BinaryDataMap.find(BD->getAddress()));
370   auto End = Start;
371   while (End != BinaryDataMap.end() && BD->isAncestorOf(End->second))
372     ++End;
373   return make_range(Start, End);
374 }
375 
376 std::pair<const MCSymbol *, uint64_t>
377 BinaryContext::handleAddressRef(uint64_t Address, BinaryFunction &BF,
378                                 bool IsPCRel) {
379   uint64_t Addend = 0;
380 
381   if (isAArch64()) {
382     // Check if this is an access to a constant island and create bookkeeping
383     // to keep track of it and emit it later as part of this function.
384     if (MCSymbol *IslandSym = BF.getOrCreateIslandAccess(Address))
385       return std::make_pair(IslandSym, Addend);
386 
387     // Detect custom code written in assembly that refers to arbitrary
388     // constant islands from other functions. Write this reference so we
389     // can pull this constant island and emit it as part of this function
390     // too.
391     auto IslandIter = AddressToConstantIslandMap.lower_bound(Address);
392     if (IslandIter != AddressToConstantIslandMap.end()) {
393       if (MCSymbol *IslandSym =
394               IslandIter->second->getOrCreateProxyIslandAccess(Address, BF)) {
395         BF.createIslandDependency(IslandSym, IslandIter->second);
396         return std::make_pair(IslandSym, Addend);
397       }
398     }
399   }
400 
401   // Note that the address does not necessarily have to reside inside
402   // a section, it could be an absolute address too.
403   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
404   if (Section && Section->isText()) {
405     if (BF.containsAddress(Address, /*UseMaxSize=*/isAArch64())) {
406       if (Address != BF.getAddress()) {
407         // The address could potentially escape. Mark it as another entry
408         // point into the function.
409         if (opts::Verbosity >= 1) {
410           outs() << "BOLT-INFO: potentially escaped address 0x"
411                  << Twine::utohexstr(Address) << " in function " << BF << '\n';
412         }
413         BF.HasInternalLabelReference = true;
414         return std::make_pair(
415             BF.addEntryPointAtOffset(Address - BF.getAddress()), Addend);
416       }
417     } else {
418       addInterproceduralReference(&BF, Address);
419     }
420   }
421 
422   // With relocations, catch jump table references outside of the basic block
423   // containing the indirect jump.
424   if (HasRelocations) {
425     const MemoryContentsType MemType = analyzeMemoryAt(Address, BF);
426     if (MemType == MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE && IsPCRel) {
427       const MCSymbol *Symbol =
428           getOrCreateJumpTable(BF, Address, JumpTable::JTT_PIC);
429 
430       return std::make_pair(Symbol, Addend);
431     }
432   }
433 
434   if (BinaryData *BD = getBinaryDataContainingAddress(Address))
435     return std::make_pair(BD->getSymbol(), Address - BD->getAddress());
436 
437   // TODO: use DWARF info to get size/alignment here?
438   MCSymbol *TargetSymbol = getOrCreateGlobalSymbol(Address, "DATAat");
439   LLVM_DEBUG(dbgs() << "Created symbol " << TargetSymbol->getName() << '\n');
440   return std::make_pair(TargetSymbol, Addend);
441 }
442 
443 MemoryContentsType BinaryContext::analyzeMemoryAt(uint64_t Address,
444                                                   BinaryFunction &BF) {
445   if (!isX86())
446     return MemoryContentsType::UNKNOWN;
447 
448   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
449   if (!Section) {
450     // No section - possibly an absolute address. Since we don't allow
451     // internal function addresses to escape the function scope - we
452     // consider it a tail call.
453     if (opts::Verbosity > 1) {
454       errs() << "BOLT-WARNING: no section for address 0x"
455              << Twine::utohexstr(Address) << " referenced from function " << BF
456              << '\n';
457     }
458     return MemoryContentsType::UNKNOWN;
459   }
460 
461   if (Section->isVirtual()) {
462     // The contents are filled at runtime.
463     return MemoryContentsType::UNKNOWN;
464   }
465 
466   // No support for jump tables in code yet.
467   if (Section->isText())
468     return MemoryContentsType::UNKNOWN;
469 
470   // Start with checking for PIC jump table. We expect non-PIC jump tables
471   // to have high 32 bits set to 0.
472   if (analyzeJumpTable(Address, JumpTable::JTT_PIC, BF))
473     return MemoryContentsType::POSSIBLE_PIC_JUMP_TABLE;
474 
475   if (analyzeJumpTable(Address, JumpTable::JTT_NORMAL, BF))
476     return MemoryContentsType::POSSIBLE_JUMP_TABLE;
477 
478   return MemoryContentsType::UNKNOWN;
479 }
480 
481 /// Check if <fragment restored name> == <parent restored name>.cold(.\d+)?
482 bool isPotentialFragmentByName(BinaryFunction &Fragment,
483                                BinaryFunction &Parent) {
484   for (StringRef Name : Parent.getNames()) {
485     std::string NamePrefix = Regex::escape(NameResolver::restore(Name));
486     std::string NameRegex = Twine(NamePrefix, "\\.cold(\\.[0-9]+)?").str();
487     if (Fragment.hasRestoredNameRegex(NameRegex))
488       return true;
489   }
490   return false;
491 }
492 
493 bool BinaryContext::analyzeJumpTable(const uint64_t Address,
494                                      const JumpTable::JumpTableType Type,
495                                      BinaryFunction &BF,
496                                      const uint64_t NextJTAddress,
497                                      JumpTable::OffsetsType *Offsets) {
498   // Is one of the targets __builtin_unreachable?
499   bool HasUnreachable = false;
500 
501   // Number of targets other than __builtin_unreachable.
502   uint64_t NumRealEntries = 0;
503 
504   constexpr uint64_t INVALID_OFFSET = std::numeric_limits<uint64_t>::max();
505   auto addOffset = [&](uint64_t Offset) {
506     if (Offsets)
507       Offsets->emplace_back(Offset);
508   };
509 
510   auto doesBelongToFunction = [&](const uint64_t Addr,
511                                   BinaryFunction *TargetBF) -> bool {
512     if (BF.containsAddress(Addr))
513       return true;
514     // Nothing to do if we failed to identify the containing function.
515     if (!TargetBF)
516       return false;
517     // Case 1: check if BF is a fragment and TargetBF is its parent.
518     if (BF.isFragment()) {
519       // Parent function may or may not be already registered.
520       // Set parent link based on function name matching heuristic.
521       return registerFragment(BF, *TargetBF);
522     }
523     // Case 2: check if TargetBF is a fragment and BF is its parent.
524     return TargetBF->isFragment() && registerFragment(*TargetBF, BF);
525   };
526 
527   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
528   if (!Section)
529     return false;
530 
531   // The upper bound is defined by containing object, section limits, and
532   // the next jump table in memory.
533   uint64_t UpperBound = Section->getEndAddress();
534   const BinaryData *JumpTableBD = getBinaryDataAtAddress(Address);
535   if (JumpTableBD && JumpTableBD->getSize()) {
536     assert(JumpTableBD->getEndAddress() <= UpperBound &&
537            "data object cannot cross a section boundary");
538     UpperBound = JumpTableBD->getEndAddress();
539   }
540   if (NextJTAddress)
541     UpperBound = std::min(NextJTAddress, UpperBound);
542 
543   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: analyzeJumpTable in " << BF.getPrintName()
544                     << '\n');
545   const uint64_t EntrySize = getJumpTableEntrySize(Type);
546   for (uint64_t EntryAddress = Address; EntryAddress <= UpperBound - EntrySize;
547        EntryAddress += EntrySize) {
548     LLVM_DEBUG(dbgs() << "  * Checking 0x" << Twine::utohexstr(EntryAddress)
549                       << " -> ");
550     // Check if there's a proper relocation against the jump table entry.
551     if (HasRelocations) {
552       if (Type == JumpTable::JTT_PIC &&
553           !DataPCRelocations.count(EntryAddress)) {
554         LLVM_DEBUG(
555             dbgs() << "FAIL: JTT_PIC table, no relocation for this address\n");
556         break;
557       }
558       if (Type == JumpTable::JTT_NORMAL && !getRelocationAt(EntryAddress)) {
559         LLVM_DEBUG(
560             dbgs()
561             << "FAIL: JTT_NORMAL table, no relocation for this address\n");
562         break;
563       }
564     }
565 
566     const uint64_t Value =
567         (Type == JumpTable::JTT_PIC)
568             ? Address + *getSignedValueAtAddress(EntryAddress, EntrySize)
569             : *getPointerAtAddress(EntryAddress);
570 
571     // __builtin_unreachable() case.
572     if (Value == BF.getAddress() + BF.getSize()) {
573       addOffset(Value - BF.getAddress());
574       HasUnreachable = true;
575       LLVM_DEBUG(dbgs() << "OK: __builtin_unreachable\n");
576       continue;
577     }
578 
579     // Function or one of its fragments.
580     BinaryFunction *TargetBF = getBinaryFunctionContainingAddress(Value);
581 
582     // We assume that a jump table cannot have function start as an entry.
583     if (!doesBelongToFunction(Value, TargetBF) || Value == BF.getAddress()) {
584       LLVM_DEBUG({
585         if (!BF.containsAddress(Value)) {
586           dbgs() << "FAIL: function doesn't contain this address\n";
587           if (TargetBF) {
588             dbgs() << "  ! function containing this address: "
589                    << TargetBF->getPrintName() << '\n';
590             if (TargetBF->isFragment())
591               dbgs() << "  ! is a fragment\n";
592             for (BinaryFunction *TargetParent : TargetBF->ParentFragments)
593               dbgs() << "  ! its parent is "
594                      << (TargetParent ? TargetParent->getPrintName() : "(none)")
595                      << '\n';
596           }
597         }
598         if (Value == BF.getAddress())
599           dbgs() << "FAIL: jump table cannot have function start as an entry\n";
600       });
601       break;
602     }
603 
604     // Check there's an instruction at this offset.
605     if (TargetBF->getState() == BinaryFunction::State::Disassembled &&
606         !TargetBF->getInstructionAtOffset(Value - TargetBF->getAddress())) {
607       LLVM_DEBUG(dbgs() << "FAIL: no instruction at this offset\n");
608       break;
609     }
610 
611     ++NumRealEntries;
612 
613     if (TargetBF == &BF) {
614       // Address inside the function.
615       addOffset(Value - TargetBF->getAddress());
616       LLVM_DEBUG(dbgs() << "OK: real entry\n");
617     } else {
618       // Address in split fragment.
619       BF.setHasSplitJumpTable(true);
620       // Add invalid offset for proper identification of jump table size.
621       addOffset(INVALID_OFFSET);
622       LLVM_DEBUG(dbgs() << "OK: address in split fragment "
623                         << TargetBF->getPrintName() << '\n');
624     }
625   }
626 
627   // It's a jump table if the number of real entries is more than 1, or there's
628   // one real entry and "unreachable" targets. If there are only multiple
629   // "unreachable" targets, then it's not a jump table.
630   return NumRealEntries + HasUnreachable >= 2;
631 }
632 
633 void BinaryContext::populateJumpTables() {
634   LLVM_DEBUG(dbgs() << "DataPCRelocations: " << DataPCRelocations.size()
635                     << '\n');
636   for (auto JTI = JumpTables.begin(), JTE = JumpTables.end(); JTI != JTE;
637        ++JTI) {
638     JumpTable *JT = JTI->second;
639     BinaryFunction &BF = *JT->Parent;
640 
641     if (!BF.isSimple())
642       continue;
643 
644     uint64_t NextJTAddress = 0;
645     auto NextJTI = std::next(JTI);
646     if (NextJTI != JTE)
647       NextJTAddress = NextJTI->second->getAddress();
648 
649     const bool Success = analyzeJumpTable(JT->getAddress(), JT->Type, BF,
650                                           NextJTAddress, &JT->OffsetEntries);
651     if (!Success) {
652       dbgs() << "failed to analyze jump table in function " << BF << '\n';
653       JT->print(dbgs());
654       if (NextJTI != JTE) {
655         dbgs() << "next jump table at 0x"
656                << Twine::utohexstr(NextJTI->second->getAddress())
657                << " belongs to function " << *NextJTI->second->Parent << '\n';
658         NextJTI->second->print(dbgs());
659       }
660       llvm_unreachable("jump table heuristic failure");
661     }
662 
663     for (uint64_t EntryOffset : JT->OffsetEntries) {
664       if (EntryOffset == BF.getSize())
665         BF.IgnoredBranches.emplace_back(EntryOffset, BF.getSize());
666       else
667         BF.registerReferencedOffset(EntryOffset);
668     }
669 
670     // In strict mode, erase PC-relative relocation record. Later we check that
671     // all such records are erased and thus have been accounted for.
672     if (opts::StrictMode && JT->Type == JumpTable::JTT_PIC) {
673       for (uint64_t Address = JT->getAddress();
674            Address < JT->getAddress() + JT->getSize();
675            Address += JT->EntrySize) {
676         DataPCRelocations.erase(DataPCRelocations.find(Address));
677       }
678     }
679 
680     // Mark to skip the function and all its fragments.
681     if (BF.hasSplitJumpTable())
682       FragmentsToSkip.push_back(&BF);
683   }
684 
685   if (opts::StrictMode && DataPCRelocations.size()) {
686     LLVM_DEBUG({
687       dbgs() << DataPCRelocations.size()
688              << " unclaimed PC-relative relocations left in data:\n";
689       for (uint64_t Reloc : DataPCRelocations)
690         dbgs() << Twine::utohexstr(Reloc) << '\n';
691     });
692     assert(0 && "unclaimed PC-relative relocations left in data\n");
693   }
694   clearList(DataPCRelocations);
695 }
696 
697 void BinaryContext::skipMarkedFragments() {
698   // Unique functions in the vector.
699   std::unordered_set<BinaryFunction *> UniqueFunctions(FragmentsToSkip.begin(),
700                                                        FragmentsToSkip.end());
701   // Copy the functions back to FragmentsToSkip.
702   FragmentsToSkip.assign(UniqueFunctions.begin(), UniqueFunctions.end());
703   auto addToWorklist = [&](BinaryFunction *Function) -> void {
704     if (UniqueFunctions.count(Function))
705       return;
706     FragmentsToSkip.push_back(Function);
707     UniqueFunctions.insert(Function);
708   };
709   // Functions containing split jump tables need to be skipped with all
710   // fragments (transitively).
711   for (size_t I = 0; I != FragmentsToSkip.size(); I++) {
712     BinaryFunction *BF = FragmentsToSkip[I];
713     assert(UniqueFunctions.count(BF) &&
714            "internal error in traversing function fragments");
715     if (opts::Verbosity >= 1)
716       errs() << "BOLT-WARNING: Ignoring " << BF->getPrintName() << '\n';
717     BF->setSimple(false);
718     BF->setHasSplitJumpTable(true);
719 
720     llvm::for_each(BF->Fragments, addToWorklist);
721     llvm::for_each(BF->ParentFragments, addToWorklist);
722   }
723   if (!FragmentsToSkip.empty())
724     errs() << "BOLT-WARNING: skipped " << FragmentsToSkip.size() << " function"
725            << (FragmentsToSkip.size() == 1 ? "" : "s")
726            << " due to cold fragments\n";
727   FragmentsToSkip.clear();
728 }
729 
730 MCSymbol *BinaryContext::getOrCreateGlobalSymbol(uint64_t Address, Twine Prefix,
731                                                  uint64_t Size,
732                                                  uint16_t Alignment,
733                                                  unsigned Flags) {
734   auto Itr = BinaryDataMap.find(Address);
735   if (Itr != BinaryDataMap.end()) {
736     assert(Itr->second->getSize() == Size || !Size);
737     return Itr->second->getSymbol();
738   }
739 
740   std::string Name = (Prefix + "0x" + Twine::utohexstr(Address)).str();
741   assert(!GlobalSymbols.count(Name) && "created name is not unique");
742   return registerNameAtAddress(Name, Address, Size, Alignment, Flags);
743 }
744 
745 MCSymbol *BinaryContext::getOrCreateUndefinedGlobalSymbol(StringRef Name) {
746   return Ctx->getOrCreateSymbol(Name);
747 }
748 
749 BinaryFunction *BinaryContext::createBinaryFunction(
750     const std::string &Name, BinarySection &Section, uint64_t Address,
751     uint64_t Size, uint64_t SymbolSize, uint16_t Alignment) {
752   auto Result = BinaryFunctions.emplace(
753       Address, BinaryFunction(Name, Section, Address, Size, *this));
754   assert(Result.second == true && "unexpected duplicate function");
755   BinaryFunction *BF = &Result.first->second;
756   registerNameAtAddress(Name, Address, SymbolSize ? SymbolSize : Size,
757                         Alignment);
758   setSymbolToFunctionMap(BF->getSymbol(), BF);
759   return BF;
760 }
761 
762 const MCSymbol *
763 BinaryContext::getOrCreateJumpTable(BinaryFunction &Function, uint64_t Address,
764                                     JumpTable::JumpTableType Type) {
765   auto isFragmentOf = [](BinaryFunction *Fragment, BinaryFunction *Parent) {
766     return (Fragment->isFragment() && Fragment->isParentFragment(Parent));
767   };
768 
769   if (JumpTable *JT = getJumpTableContainingAddress(Address)) {
770     assert(JT->Type == Type && "jump table types have to match");
771     bool HasMultipleParents = isFragmentOf(JT->Parent, &Function) ||
772                               isFragmentOf(&Function, JT->Parent);
773     assert((JT->Parent == &Function || HasMultipleParents) &&
774            "cannot re-use jump table of a different function");
775     assert(Address == JT->getAddress() && "unexpected non-empty jump table");
776 
777     // Flush OffsetEntries with INVALID_OFFSET if multiple parents
778     // Duplicate the entry for the parent function for easy access
779     if (HasMultipleParents) {
780       if (opts::Verbosity > 2) {
781         outs() << "BOLT-WARNING: Multiple fragments access same jump table: "
782                << JT->Parent->getPrintName() << "; " << Function.getPrintName()
783                << "\n";
784       }
785       constexpr uint64_t INVALID_OFFSET = std::numeric_limits<uint64_t>::max();
786       for (unsigned I = 0; I < JT->OffsetEntries.size(); ++I)
787         JT->OffsetEntries[I] = INVALID_OFFSET;
788       Function.JumpTables.emplace(Address, JT);
789     }
790     return JT->getFirstLabel();
791   }
792 
793   // Re-use the existing symbol if possible.
794   MCSymbol *JTLabel = nullptr;
795   if (BinaryData *Object = getBinaryDataAtAddress(Address)) {
796     if (!isInternalSymbolName(Object->getSymbol()->getName()))
797       JTLabel = Object->getSymbol();
798   }
799 
800   const uint64_t EntrySize = getJumpTableEntrySize(Type);
801   if (!JTLabel) {
802     const std::string JumpTableName = generateJumpTableName(Function, Address);
803     JTLabel = registerNameAtAddress(JumpTableName, Address, 0, EntrySize);
804   }
805 
806   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: creating jump table " << JTLabel->getName()
807                     << " in function " << Function << '\n');
808 
809   JumpTable *JT = new JumpTable(*JTLabel, Address, EntrySize, Type,
810                                 JumpTable::LabelMapType{{0, JTLabel}}, Function,
811                                 *getSectionForAddress(Address));
812   JumpTables.emplace(Address, JT);
813 
814   // Duplicate the entry for the parent function for easy access.
815   Function.JumpTables.emplace(Address, JT);
816 
817   return JTLabel;
818 }
819 
820 std::pair<uint64_t, const MCSymbol *>
821 BinaryContext::duplicateJumpTable(BinaryFunction &Function, JumpTable *JT,
822                                   const MCSymbol *OldLabel) {
823   auto L = scopeLock();
824   unsigned Offset = 0;
825   bool Found = false;
826   for (std::pair<const unsigned, MCSymbol *> Elmt : JT->Labels) {
827     if (Elmt.second != OldLabel)
828       continue;
829     Offset = Elmt.first;
830     Found = true;
831     break;
832   }
833   assert(Found && "Label not found");
834   (void)Found;
835   MCSymbol *NewLabel = Ctx->createNamedTempSymbol("duplicatedJT");
836   JumpTable *NewJT =
837       new JumpTable(*NewLabel, JT->getAddress(), JT->EntrySize, JT->Type,
838                     JumpTable::LabelMapType{{Offset, NewLabel}}, Function,
839                     *getSectionForAddress(JT->getAddress()));
840   NewJT->Entries = JT->Entries;
841   NewJT->Counts = JT->Counts;
842   uint64_t JumpTableID = ++DuplicatedJumpTables;
843   // Invert it to differentiate from regular jump tables whose IDs are their
844   // addresses in the input binary memory space
845   JumpTableID = ~JumpTableID;
846   JumpTables.emplace(JumpTableID, NewJT);
847   Function.JumpTables.emplace(JumpTableID, NewJT);
848   return std::make_pair(JumpTableID, NewLabel);
849 }
850 
851 std::string BinaryContext::generateJumpTableName(const BinaryFunction &BF,
852                                                  uint64_t Address) {
853   size_t Id;
854   uint64_t Offset = 0;
855   if (const JumpTable *JT = BF.getJumpTableContainingAddress(Address)) {
856     Offset = Address - JT->getAddress();
857     auto Itr = JT->Labels.find(Offset);
858     if (Itr != JT->Labels.end())
859       return std::string(Itr->second->getName());
860     Id = JumpTableIds.at(JT->getAddress());
861   } else {
862     Id = JumpTableIds[Address] = BF.JumpTables.size();
863   }
864   return ("JUMP_TABLE/" + BF.getOneName().str() + "." + std::to_string(Id) +
865           (Offset ? ("." + std::to_string(Offset)) : ""));
866 }
867 
868 bool BinaryContext::hasValidCodePadding(const BinaryFunction &BF) {
869   // FIXME: aarch64 support is missing.
870   if (!isX86())
871     return true;
872 
873   if (BF.getSize() == BF.getMaxSize())
874     return true;
875 
876   ErrorOr<ArrayRef<unsigned char>> FunctionData = BF.getData();
877   assert(FunctionData && "cannot get function as data");
878 
879   uint64_t Offset = BF.getSize();
880   MCInst Instr;
881   uint64_t InstrSize = 0;
882   uint64_t InstrAddress = BF.getAddress() + Offset;
883   using std::placeholders::_1;
884 
885   // Skip instructions that satisfy the predicate condition.
886   auto skipInstructions = [&](std::function<bool(const MCInst &)> Predicate) {
887     const uint64_t StartOffset = Offset;
888     for (; Offset < BF.getMaxSize();
889          Offset += InstrSize, InstrAddress += InstrSize) {
890       if (!DisAsm->getInstruction(Instr, InstrSize, FunctionData->slice(Offset),
891                                   InstrAddress, nulls()))
892         break;
893       if (!Predicate(Instr))
894         break;
895     }
896 
897     return Offset - StartOffset;
898   };
899 
900   // Skip a sequence of zero bytes.
901   auto skipZeros = [&]() {
902     const uint64_t StartOffset = Offset;
903     for (; Offset < BF.getMaxSize(); ++Offset)
904       if ((*FunctionData)[Offset] != 0)
905         break;
906 
907     return Offset - StartOffset;
908   };
909 
910   // Accept the whole padding area filled with breakpoints.
911   auto isBreakpoint = std::bind(&MCPlusBuilder::isBreakpoint, MIB.get(), _1);
912   if (skipInstructions(isBreakpoint) && Offset == BF.getMaxSize())
913     return true;
914 
915   auto isNoop = std::bind(&MCPlusBuilder::isNoop, MIB.get(), _1);
916 
917   // Some functions have a jump to the next function or to the padding area
918   // inserted after the body.
919   auto isSkipJump = [&](const MCInst &Instr) {
920     uint64_t TargetAddress = 0;
921     if (MIB->isUnconditionalBranch(Instr) &&
922         MIB->evaluateBranch(Instr, InstrAddress, InstrSize, TargetAddress)) {
923       if (TargetAddress >= InstrAddress + InstrSize &&
924           TargetAddress <= BF.getAddress() + BF.getMaxSize()) {
925         return true;
926       }
927     }
928     return false;
929   };
930 
931   // Skip over nops, jumps, and zero padding. Allow interleaving (this happens).
932   while (skipInstructions(isNoop) || skipInstructions(isSkipJump) ||
933          skipZeros())
934     ;
935 
936   if (Offset == BF.getMaxSize())
937     return true;
938 
939   if (opts::Verbosity >= 1) {
940     errs() << "BOLT-WARNING: bad padding at address 0x"
941            << Twine::utohexstr(BF.getAddress() + BF.getSize())
942            << " starting at offset " << (Offset - BF.getSize())
943            << " in function " << BF << '\n'
944            << FunctionData->slice(BF.getSize(), BF.getMaxSize() - BF.getSize())
945            << '\n';
946   }
947 
948   return false;
949 }
950 
951 void BinaryContext::adjustCodePadding() {
952   for (auto &BFI : BinaryFunctions) {
953     BinaryFunction &BF = BFI.second;
954     if (!shouldEmit(BF))
955       continue;
956 
957     if (!hasValidCodePadding(BF)) {
958       if (HasRelocations) {
959         if (opts::Verbosity >= 1) {
960           outs() << "BOLT-INFO: function " << BF
961                  << " has invalid padding. Ignoring the function.\n";
962         }
963         BF.setIgnored();
964       } else {
965         BF.setMaxSize(BF.getSize());
966       }
967     }
968   }
969 }
970 
971 MCSymbol *BinaryContext::registerNameAtAddress(StringRef Name, uint64_t Address,
972                                                uint64_t Size,
973                                                uint16_t Alignment,
974                                                unsigned Flags) {
975   // Register the name with MCContext.
976   MCSymbol *Symbol = Ctx->getOrCreateSymbol(Name);
977 
978   auto GAI = BinaryDataMap.find(Address);
979   BinaryData *BD;
980   if (GAI == BinaryDataMap.end()) {
981     ErrorOr<BinarySection &> SectionOrErr = getSectionForAddress(Address);
982     BinarySection &Section =
983         SectionOrErr ? SectionOrErr.get() : absoluteSection();
984     BD = new BinaryData(*Symbol, Address, Size, Alignment ? Alignment : 1,
985                         Section, Flags);
986     GAI = BinaryDataMap.emplace(Address, BD).first;
987     GlobalSymbols[Name] = BD;
988     updateObjectNesting(GAI);
989   } else {
990     BD = GAI->second;
991     if (!BD->hasName(Name)) {
992       GlobalSymbols[Name] = BD;
993       BD->Symbols.push_back(Symbol);
994     }
995   }
996 
997   return Symbol;
998 }
999 
1000 const BinaryData *
1001 BinaryContext::getBinaryDataContainingAddressImpl(uint64_t Address) const {
1002   auto NI = BinaryDataMap.lower_bound(Address);
1003   auto End = BinaryDataMap.end();
1004   if ((NI != End && Address == NI->first) ||
1005       ((NI != BinaryDataMap.begin()) && (NI-- != BinaryDataMap.begin()))) {
1006     if (NI->second->containsAddress(Address))
1007       return NI->second;
1008 
1009     // If this is a sub-symbol, see if a parent data contains the address.
1010     const BinaryData *BD = NI->second->getParent();
1011     while (BD) {
1012       if (BD->containsAddress(Address))
1013         return BD;
1014       BD = BD->getParent();
1015     }
1016   }
1017   return nullptr;
1018 }
1019 
1020 bool BinaryContext::setBinaryDataSize(uint64_t Address, uint64_t Size) {
1021   auto NI = BinaryDataMap.find(Address);
1022   assert(NI != BinaryDataMap.end());
1023   if (NI == BinaryDataMap.end())
1024     return false;
1025   // TODO: it's possible that a jump table starts at the same address
1026   // as a larger blob of private data.  When we set the size of the
1027   // jump table, it might be smaller than the total blob size.  In this
1028   // case we just leave the original size since (currently) it won't really
1029   // affect anything.
1030   assert((!NI->second->Size || NI->second->Size == Size ||
1031           (NI->second->isJumpTable() && NI->second->Size > Size)) &&
1032          "can't change the size of a symbol that has already had its "
1033          "size set");
1034   if (!NI->second->Size) {
1035     NI->second->Size = Size;
1036     updateObjectNesting(NI);
1037     return true;
1038   }
1039   return false;
1040 }
1041 
1042 void BinaryContext::generateSymbolHashes() {
1043   auto isPadding = [](const BinaryData &BD) {
1044     StringRef Contents = BD.getSection().getContents();
1045     StringRef SymData = Contents.substr(BD.getOffset(), BD.getSize());
1046     return (BD.getName().startswith("HOLEat") ||
1047             SymData.find_first_not_of(0) == StringRef::npos);
1048   };
1049 
1050   uint64_t NumCollisions = 0;
1051   for (auto &Entry : BinaryDataMap) {
1052     BinaryData &BD = *Entry.second;
1053     StringRef Name = BD.getName();
1054 
1055     if (!isInternalSymbolName(Name))
1056       continue;
1057 
1058     // First check if a non-anonymous alias exists and move it to the front.
1059     if (BD.getSymbols().size() > 1) {
1060       auto Itr = llvm::find_if(BD.getSymbols(), [&](const MCSymbol *Symbol) {
1061         return !isInternalSymbolName(Symbol->getName());
1062       });
1063       if (Itr != BD.getSymbols().end()) {
1064         size_t Idx = std::distance(BD.getSymbols().begin(), Itr);
1065         std::swap(BD.getSymbols()[0], BD.getSymbols()[Idx]);
1066         continue;
1067       }
1068     }
1069 
1070     // We have to skip 0 size symbols since they will all collide.
1071     if (BD.getSize() == 0) {
1072       continue;
1073     }
1074 
1075     const uint64_t Hash = BD.getSection().hash(BD);
1076     const size_t Idx = Name.find("0x");
1077     std::string NewName =
1078         (Twine(Name.substr(0, Idx)) + "_" + Twine::utohexstr(Hash)).str();
1079     if (getBinaryDataByName(NewName)) {
1080       // Ignore collisions for symbols that appear to be padding
1081       // (i.e. all zeros or a "hole")
1082       if (!isPadding(BD)) {
1083         if (opts::Verbosity) {
1084           errs() << "BOLT-WARNING: collision detected when hashing " << BD
1085                  << " with new name (" << NewName << "), skipping.\n";
1086         }
1087         ++NumCollisions;
1088       }
1089       continue;
1090     }
1091     BD.Symbols.insert(BD.Symbols.begin(), Ctx->getOrCreateSymbol(NewName));
1092     GlobalSymbols[NewName] = &BD;
1093   }
1094   if (NumCollisions) {
1095     errs() << "BOLT-WARNING: " << NumCollisions
1096            << " collisions detected while hashing binary objects";
1097     if (!opts::Verbosity)
1098       errs() << ". Use -v=1 to see the list.";
1099     errs() << '\n';
1100   }
1101 }
1102 
1103 bool BinaryContext::registerFragment(BinaryFunction &TargetFunction,
1104                                      BinaryFunction &Function) const {
1105   if (!isPotentialFragmentByName(TargetFunction, Function))
1106     return false;
1107   assert(TargetFunction.isFragment() && "TargetFunction must be a fragment");
1108   if (TargetFunction.isParentFragment(&Function))
1109     return true;
1110   TargetFunction.addParentFragment(Function);
1111   Function.addFragment(TargetFunction);
1112   if (!HasRelocations) {
1113     TargetFunction.setSimple(false);
1114     Function.setSimple(false);
1115   }
1116   if (opts::Verbosity >= 1) {
1117     outs() << "BOLT-INFO: marking " << TargetFunction << " as a fragment of "
1118            << Function << '\n';
1119   }
1120   return true;
1121 }
1122 
1123 void BinaryContext::addAdrpAddRelocAArch64(BinaryFunction &BF,
1124                                            MCInst &LoadLowBits,
1125                                            MCInst &LoadHiBits,
1126                                            uint64_t Target) {
1127   const MCSymbol *TargetSymbol;
1128   uint64_t Addend = 0;
1129   std::tie(TargetSymbol, Addend) = handleAddressRef(Target, BF,
1130                                                     /*IsPCRel*/ true);
1131   int64_t Val;
1132   MIB->replaceImmWithSymbolRef(LoadHiBits, TargetSymbol, Addend, Ctx.get(), Val,
1133                                ELF::R_AARCH64_ADR_PREL_PG_HI21);
1134   MIB->replaceImmWithSymbolRef(LoadLowBits, TargetSymbol, Addend, Ctx.get(),
1135                                Val, ELF::R_AARCH64_ADD_ABS_LO12_NC);
1136 }
1137 
1138 bool BinaryContext::handleAArch64Veneer(uint64_t Address, bool MatchOnly) {
1139   BinaryFunction *TargetFunction = getBinaryFunctionContainingAddress(Address);
1140   if (TargetFunction)
1141     return false;
1142 
1143   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
1144   assert(Section && "cannot get section for referenced address");
1145   if (!Section->isText())
1146     return false;
1147 
1148   bool Ret = false;
1149   StringRef SectionContents = Section->getContents();
1150   uint64_t Offset = Address - Section->getAddress();
1151   const uint64_t MaxSize = SectionContents.size() - Offset;
1152   const uint8_t *Bytes =
1153       reinterpret_cast<const uint8_t *>(SectionContents.data());
1154   ArrayRef<uint8_t> Data(Bytes + Offset, MaxSize);
1155 
1156   auto matchVeneer = [&](BinaryFunction::InstrMapType &Instructions,
1157                          MCInst &Instruction, uint64_t Offset,
1158                          uint64_t AbsoluteInstrAddr,
1159                          uint64_t TotalSize) -> bool {
1160     MCInst *TargetHiBits, *TargetLowBits;
1161     uint64_t TargetAddress, Count;
1162     Count = MIB->matchLinkerVeneer(Instructions.begin(), Instructions.end(),
1163                                    AbsoluteInstrAddr, Instruction, TargetHiBits,
1164                                    TargetLowBits, TargetAddress);
1165     if (!Count)
1166       return false;
1167 
1168     if (MatchOnly)
1169       return true;
1170 
1171     // NOTE The target symbol was created during disassemble's
1172     // handleExternalReference
1173     const MCSymbol *VeneerSymbol = getOrCreateGlobalSymbol(Address, "FUNCat");
1174     BinaryFunction *Veneer = createBinaryFunction(VeneerSymbol->getName().str(),
1175                                                   *Section, Address, TotalSize);
1176     addAdrpAddRelocAArch64(*Veneer, *TargetLowBits, *TargetHiBits,
1177                            TargetAddress);
1178     MIB->addAnnotation(Instruction, "AArch64Veneer", true);
1179     Veneer->addInstruction(Offset, std::move(Instruction));
1180     --Count;
1181     for (auto It = std::prev(Instructions.end()); Count != 0;
1182          It = std::prev(It), --Count) {
1183       MIB->addAnnotation(It->second, "AArch64Veneer", true);
1184       Veneer->addInstruction(It->first, std::move(It->second));
1185     }
1186 
1187     Veneer->getOrCreateLocalLabel(Address);
1188     Veneer->setMaxSize(TotalSize);
1189     Veneer->updateState(BinaryFunction::State::Disassembled);
1190     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: handling veneer function at 0x" << Address
1191                       << "\n");
1192     return true;
1193   };
1194 
1195   uint64_t Size = 0, TotalSize = 0;
1196   BinaryFunction::InstrMapType VeneerInstructions;
1197   for (Offset = 0; Offset < MaxSize; Offset += Size) {
1198     MCInst Instruction;
1199     const uint64_t AbsoluteInstrAddr = Address + Offset;
1200     if (!SymbolicDisAsm->getInstruction(Instruction, Size, Data.slice(Offset),
1201                                         AbsoluteInstrAddr, nulls()))
1202       break;
1203 
1204     TotalSize += Size;
1205     if (MIB->isBranch(Instruction)) {
1206       Ret = matchVeneer(VeneerInstructions, Instruction, Offset,
1207                         AbsoluteInstrAddr, TotalSize);
1208       break;
1209     }
1210 
1211     VeneerInstructions.emplace(Offset, std::move(Instruction));
1212   }
1213 
1214   return Ret;
1215 }
1216 
1217 void BinaryContext::processInterproceduralReferences() {
1218   for (const std::pair<BinaryFunction *, uint64_t> &It :
1219        InterproceduralReferences) {
1220     BinaryFunction &Function = *It.first;
1221     uint64_t Address = It.second;
1222     if (!Address || Function.isIgnored())
1223       continue;
1224 
1225     BinaryFunction *TargetFunction =
1226         getBinaryFunctionContainingAddress(Address);
1227     if (&Function == TargetFunction)
1228       continue;
1229 
1230     if (TargetFunction) {
1231       if (TargetFunction->isFragment() &&
1232           !registerFragment(*TargetFunction, Function)) {
1233         errs() << "BOLT-WARNING: interprocedural reference between unrelated "
1234                   "fragments: "
1235                << Function.getPrintName() << " and "
1236                << TargetFunction->getPrintName() << '\n';
1237       }
1238       if (uint64_t Offset = Address - TargetFunction->getAddress())
1239         TargetFunction->addEntryPointAtOffset(Offset);
1240 
1241       continue;
1242     }
1243 
1244     // Check if address falls in function padding space - this could be
1245     // unmarked data in code. In this case adjust the padding space size.
1246     ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
1247     assert(Section && "cannot get section for referenced address");
1248 
1249     if (!Section->isText())
1250       continue;
1251 
1252     // PLT requires special handling and could be ignored in this context.
1253     StringRef SectionName = Section->getName();
1254     if (SectionName == ".plt" || SectionName == ".plt.got")
1255       continue;
1256 
1257     // Check if it is aarch64 veneer written at Address
1258     if (isAArch64() && handleAArch64Veneer(Address))
1259       continue;
1260 
1261     if (opts::processAllFunctions()) {
1262       errs() << "BOLT-ERROR: cannot process binaries with unmarked "
1263              << "object in code at address 0x" << Twine::utohexstr(Address)
1264              << " belonging to section " << SectionName << " in current mode\n";
1265       exit(1);
1266     }
1267 
1268     TargetFunction = getBinaryFunctionContainingAddress(Address,
1269                                                         /*CheckPastEnd=*/false,
1270                                                         /*UseMaxSize=*/true);
1271     // We are not going to overwrite non-simple functions, but for simple
1272     // ones - adjust the padding size.
1273     if (TargetFunction && TargetFunction->isSimple()) {
1274       errs() << "BOLT-WARNING: function " << *TargetFunction
1275              << " has an object detected in a padding region at address 0x"
1276              << Twine::utohexstr(Address) << '\n';
1277       TargetFunction->setMaxSize(TargetFunction->getSize());
1278     }
1279   }
1280 
1281   InterproceduralReferences.clear();
1282 }
1283 
1284 void BinaryContext::postProcessSymbolTable() {
1285   fixBinaryDataHoles();
1286   bool Valid = true;
1287   for (auto &Entry : BinaryDataMap) {
1288     BinaryData *BD = Entry.second;
1289     if ((BD->getName().startswith("SYMBOLat") ||
1290          BD->getName().startswith("DATAat")) &&
1291         !BD->getParent() && !BD->getSize() && !BD->isAbsolute() &&
1292         BD->getSection()) {
1293       errs() << "BOLT-WARNING: zero-sized top level symbol: " << *BD << "\n";
1294       Valid = false;
1295     }
1296   }
1297   assert(Valid);
1298   (void)Valid;
1299   generateSymbolHashes();
1300 }
1301 
1302 void BinaryContext::foldFunction(BinaryFunction &ChildBF,
1303                                  BinaryFunction &ParentBF) {
1304   assert(!ChildBF.isMultiEntry() && !ParentBF.isMultiEntry() &&
1305          "cannot merge functions with multiple entry points");
1306 
1307   std::unique_lock<std::shared_timed_mutex> WriteCtxLock(CtxMutex,
1308                                                          std::defer_lock);
1309   std::unique_lock<std::shared_timed_mutex> WriteSymbolMapLock(
1310       SymbolToFunctionMapMutex, std::defer_lock);
1311 
1312   const StringRef ChildName = ChildBF.getOneName();
1313 
1314   // Move symbols over and update bookkeeping info.
1315   for (MCSymbol *Symbol : ChildBF.getSymbols()) {
1316     ParentBF.getSymbols().push_back(Symbol);
1317     WriteSymbolMapLock.lock();
1318     SymbolToFunctionMap[Symbol] = &ParentBF;
1319     WriteSymbolMapLock.unlock();
1320     // NB: there's no need to update BinaryDataMap and GlobalSymbols.
1321   }
1322   ChildBF.getSymbols().clear();
1323 
1324   // Move other names the child function is known under.
1325   llvm::move(ChildBF.Aliases, std::back_inserter(ParentBF.Aliases));
1326   ChildBF.Aliases.clear();
1327 
1328   if (HasRelocations) {
1329     // Merge execution counts of ChildBF into those of ParentBF.
1330     // Without relocations, we cannot reliably merge profiles as both functions
1331     // continue to exist and either one can be executed.
1332     ChildBF.mergeProfileDataInto(ParentBF);
1333 
1334     std::shared_lock<std::shared_timed_mutex> ReadBfsLock(BinaryFunctionsMutex,
1335                                                           std::defer_lock);
1336     std::unique_lock<std::shared_timed_mutex> WriteBfsLock(BinaryFunctionsMutex,
1337                                                            std::defer_lock);
1338     // Remove ChildBF from the global set of functions in relocs mode.
1339     ReadBfsLock.lock();
1340     auto FI = BinaryFunctions.find(ChildBF.getAddress());
1341     ReadBfsLock.unlock();
1342 
1343     assert(FI != BinaryFunctions.end() && "function not found");
1344     assert(&ChildBF == &FI->second && "function mismatch");
1345 
1346     WriteBfsLock.lock();
1347     ChildBF.clearDisasmState();
1348     FI = BinaryFunctions.erase(FI);
1349     WriteBfsLock.unlock();
1350 
1351   } else {
1352     // In non-relocation mode we keep the function, but rename it.
1353     std::string NewName = "__ICF_" + ChildName.str();
1354 
1355     WriteCtxLock.lock();
1356     ChildBF.getSymbols().push_back(Ctx->getOrCreateSymbol(NewName));
1357     WriteCtxLock.unlock();
1358 
1359     ChildBF.setFolded(&ParentBF);
1360   }
1361 }
1362 
1363 void BinaryContext::fixBinaryDataHoles() {
1364   assert(validateObjectNesting() && "object nesting inconsitency detected");
1365 
1366   for (BinarySection &Section : allocatableSections()) {
1367     std::vector<std::pair<uint64_t, uint64_t>> Holes;
1368 
1369     auto isNotHole = [&Section](const binary_data_iterator &Itr) {
1370       BinaryData *BD = Itr->second;
1371       bool isHole = (!BD->getParent() && !BD->getSize() && BD->isObject() &&
1372                      (BD->getName().startswith("SYMBOLat0x") ||
1373                       BD->getName().startswith("DATAat0x") ||
1374                       BD->getName().startswith("ANONYMOUS")));
1375       return !isHole && BD->getSection() == Section && !BD->getParent();
1376     };
1377 
1378     auto BDStart = BinaryDataMap.begin();
1379     auto BDEnd = BinaryDataMap.end();
1380     auto Itr = FilteredBinaryDataIterator(isNotHole, BDStart, BDEnd);
1381     auto End = FilteredBinaryDataIterator(isNotHole, BDEnd, BDEnd);
1382 
1383     uint64_t EndAddress = Section.getAddress();
1384 
1385     while (Itr != End) {
1386       if (Itr->second->getAddress() > EndAddress) {
1387         uint64_t Gap = Itr->second->getAddress() - EndAddress;
1388         Holes.emplace_back(EndAddress, Gap);
1389       }
1390       EndAddress = Itr->second->getEndAddress();
1391       ++Itr;
1392     }
1393 
1394     if (EndAddress < Section.getEndAddress())
1395       Holes.emplace_back(EndAddress, Section.getEndAddress() - EndAddress);
1396 
1397     // If there is already a symbol at the start of the hole, grow that symbol
1398     // to cover the rest.  Otherwise, create a new symbol to cover the hole.
1399     for (std::pair<uint64_t, uint64_t> &Hole : Holes) {
1400       BinaryData *BD = getBinaryDataAtAddress(Hole.first);
1401       if (BD) {
1402         // BD->getSection() can be != Section if there are sections that
1403         // overlap.  In this case it is probably safe to just skip the holes
1404         // since the overlapping section will not(?) have any symbols in it.
1405         if (BD->getSection() == Section)
1406           setBinaryDataSize(Hole.first, Hole.second);
1407       } else {
1408         getOrCreateGlobalSymbol(Hole.first, "HOLEat", Hole.second, 1);
1409       }
1410     }
1411   }
1412 
1413   assert(validateObjectNesting() && "object nesting inconsitency detected");
1414   assert(validateHoles() && "top level hole detected in object map");
1415 }
1416 
1417 void BinaryContext::printGlobalSymbols(raw_ostream &OS) const {
1418   const BinarySection *CurrentSection = nullptr;
1419   bool FirstSection = true;
1420 
1421   for (auto &Entry : BinaryDataMap) {
1422     const BinaryData *BD = Entry.second;
1423     const BinarySection &Section = BD->getSection();
1424     if (FirstSection || Section != *CurrentSection) {
1425       uint64_t Address, Size;
1426       StringRef Name = Section.getName();
1427       if (Section) {
1428         Address = Section.getAddress();
1429         Size = Section.getSize();
1430       } else {
1431         Address = BD->getAddress();
1432         Size = BD->getSize();
1433       }
1434       OS << "BOLT-INFO: Section " << Name << ", "
1435          << "0x" + Twine::utohexstr(Address) << ":"
1436          << "0x" + Twine::utohexstr(Address + Size) << "/" << Size << "\n";
1437       CurrentSection = &Section;
1438       FirstSection = false;
1439     }
1440 
1441     OS << "BOLT-INFO: ";
1442     const BinaryData *P = BD->getParent();
1443     while (P) {
1444       OS << "  ";
1445       P = P->getParent();
1446     }
1447     OS << *BD << "\n";
1448   }
1449 }
1450 
1451 Expected<unsigned> BinaryContext::getDwarfFile(
1452     StringRef Directory, StringRef FileName, unsigned FileNumber,
1453     Optional<MD5::MD5Result> Checksum, Optional<StringRef> Source,
1454     unsigned CUID, unsigned DWARFVersion) {
1455   DwarfLineTable &Table = DwarfLineTablesCUMap[CUID];
1456   return Table.tryGetFile(Directory, FileName, Checksum, Source, DWARFVersion,
1457                           FileNumber);
1458 }
1459 
1460 unsigned BinaryContext::addDebugFilenameToUnit(const uint32_t DestCUID,
1461                                                const uint32_t SrcCUID,
1462                                                unsigned FileIndex) {
1463   DWARFCompileUnit *SrcUnit = DwCtx->getCompileUnitForOffset(SrcCUID);
1464   const DWARFDebugLine::LineTable *LineTable =
1465       DwCtx->getLineTableForUnit(SrcUnit);
1466   const std::vector<DWARFDebugLine::FileNameEntry> &FileNames =
1467       LineTable->Prologue.FileNames;
1468   // Dir indexes start at 1, as DWARF file numbers, and a dir index 0
1469   // means empty dir.
1470   assert(FileIndex > 0 && FileIndex <= FileNames.size() &&
1471          "FileIndex out of range for the compilation unit.");
1472   StringRef Dir = "";
1473   if (FileNames[FileIndex - 1].DirIdx != 0) {
1474     if (Optional<const char *> DirName = dwarf::toString(
1475             LineTable->Prologue
1476                 .IncludeDirectories[FileNames[FileIndex - 1].DirIdx - 1])) {
1477       Dir = *DirName;
1478     }
1479   }
1480   StringRef FileName = "";
1481   if (Optional<const char *> FName =
1482           dwarf::toString(FileNames[FileIndex - 1].Name))
1483     FileName = *FName;
1484   assert(FileName != "");
1485   DWARFCompileUnit *DstUnit = DwCtx->getCompileUnitForOffset(DestCUID);
1486   return cantFail(getDwarfFile(Dir, FileName, 0, None, None, DestCUID,
1487                                DstUnit->getVersion()));
1488 }
1489 
1490 std::vector<BinaryFunction *> BinaryContext::getSortedFunctions() {
1491   std::vector<BinaryFunction *> SortedFunctions(BinaryFunctions.size());
1492   llvm::transform(BinaryFunctions, SortedFunctions.begin(),
1493                   [](std::pair<const uint64_t, BinaryFunction> &BFI) {
1494                     return &BFI.second;
1495                   });
1496 
1497   llvm::stable_sort(SortedFunctions,
1498                     [](const BinaryFunction *A, const BinaryFunction *B) {
1499                       if (A->hasValidIndex() && B->hasValidIndex()) {
1500                         return A->getIndex() < B->getIndex();
1501                       }
1502                       return A->hasValidIndex();
1503                     });
1504   return SortedFunctions;
1505 }
1506 
1507 std::vector<BinaryFunction *> BinaryContext::getAllBinaryFunctions() {
1508   std::vector<BinaryFunction *> AllFunctions;
1509   AllFunctions.reserve(BinaryFunctions.size() + InjectedBinaryFunctions.size());
1510   llvm::transform(BinaryFunctions, std::back_inserter(AllFunctions),
1511                   [](std::pair<const uint64_t, BinaryFunction> &BFI) {
1512                     return &BFI.second;
1513                   });
1514   llvm::copy(InjectedBinaryFunctions, std::back_inserter(AllFunctions));
1515 
1516   return AllFunctions;
1517 }
1518 
1519 Optional<DWARFUnit *> BinaryContext::getDWOCU(uint64_t DWOId) {
1520   auto Iter = DWOCUs.find(DWOId);
1521   if (Iter == DWOCUs.end())
1522     return None;
1523 
1524   return Iter->second;
1525 }
1526 
1527 DWARFContext *BinaryContext::getDWOContext() const {
1528   if (DWOCUs.empty())
1529     return nullptr;
1530   return &DWOCUs.begin()->second->getContext();
1531 }
1532 
1533 /// Handles DWO sections that can either be in .o, .dwo or .dwp files.
1534 void BinaryContext::preprocessDWODebugInfo() {
1535   for (const std::unique_ptr<DWARFUnit> &CU : DwCtx->compile_units()) {
1536     DWARFUnit *const DwarfUnit = CU.get();
1537     if (llvm::Optional<uint64_t> DWOId = DwarfUnit->getDWOId()) {
1538       DWARFUnit *DWOCU = DwarfUnit->getNonSkeletonUnitDIE(false).getDwarfUnit();
1539       if (!DWOCU->isDWOUnit()) {
1540         std::string DWOName = dwarf::toString(
1541             DwarfUnit->getUnitDIE().find(
1542                 {dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}),
1543             "");
1544         outs() << "BOLT-WARNING: Debug Fission: DWO debug information for "
1545                << DWOName
1546                << " was not retrieved and won't be updated. Please check "
1547                   "relative path.\n";
1548         continue;
1549       }
1550       DWOCUs[*DWOId] = DWOCU;
1551     }
1552   }
1553 }
1554 
1555 void BinaryContext::preprocessDebugInfo() {
1556   struct CURange {
1557     uint64_t LowPC;
1558     uint64_t HighPC;
1559     DWARFUnit *Unit;
1560 
1561     bool operator<(const CURange &Other) const { return LowPC < Other.LowPC; }
1562   };
1563 
1564   // Building a map of address ranges to CUs similar to .debug_aranges and use
1565   // it to assign CU to functions.
1566   std::vector<CURange> AllRanges;
1567   AllRanges.reserve(DwCtx->getNumCompileUnits());
1568   for (const std::unique_ptr<DWARFUnit> &CU : DwCtx->compile_units()) {
1569     Expected<DWARFAddressRangesVector> RangesOrError =
1570         CU->getUnitDIE().getAddressRanges();
1571     if (!RangesOrError) {
1572       consumeError(RangesOrError.takeError());
1573       continue;
1574     }
1575     for (DWARFAddressRange &Range : *RangesOrError) {
1576       // Parts of the debug info could be invalidated due to corresponding code
1577       // being removed from the binary by the linker. Hence we check if the
1578       // address is a valid one.
1579       if (containsAddress(Range.LowPC))
1580         AllRanges.emplace_back(CURange{Range.LowPC, Range.HighPC, CU.get()});
1581     }
1582 
1583     ContainsDwarf5 |= CU->getVersion() >= 5;
1584     ContainsDwarfLegacy |= CU->getVersion() < 5;
1585   }
1586 
1587   llvm::sort(AllRanges);
1588   for (auto &KV : BinaryFunctions) {
1589     const uint64_t FunctionAddress = KV.first;
1590     BinaryFunction &Function = KV.second;
1591 
1592     auto It = llvm::partition_point(
1593         AllRanges, [=](CURange R) { return R.HighPC <= FunctionAddress; });
1594     if (It != AllRanges.end() && It->LowPC <= FunctionAddress)
1595       Function.setDWARFUnit(It->Unit);
1596   }
1597 
1598   // Discover units with debug info that needs to be updated.
1599   for (const auto &KV : BinaryFunctions) {
1600     const BinaryFunction &BF = KV.second;
1601     if (shouldEmit(BF) && BF.getDWARFUnit())
1602       ProcessedCUs.insert(BF.getDWARFUnit());
1603   }
1604 
1605   // Clear debug info for functions from units that we are not going to process.
1606   for (auto &KV : BinaryFunctions) {
1607     BinaryFunction &BF = KV.second;
1608     if (BF.getDWARFUnit() && !ProcessedCUs.count(BF.getDWARFUnit()))
1609       BF.setDWARFUnit(nullptr);
1610   }
1611 
1612   if (opts::Verbosity >= 1) {
1613     outs() << "BOLT-INFO: " << ProcessedCUs.size() << " out of "
1614            << DwCtx->getNumCompileUnits() << " CUs will be updated\n";
1615   }
1616 
1617   preprocessDWODebugInfo();
1618 
1619   // Populate MCContext with DWARF files from all units.
1620   StringRef GlobalPrefix = AsmInfo->getPrivateGlobalPrefix();
1621   for (const std::unique_ptr<DWARFUnit> &CU : DwCtx->compile_units()) {
1622     const uint64_t CUID = CU->getOffset();
1623     DwarfLineTable &BinaryLineTable = getDwarfLineTable(CUID);
1624     BinaryLineTable.setLabel(Ctx->getOrCreateSymbol(
1625         GlobalPrefix + "line_table_start" + Twine(CUID)));
1626 
1627     if (!ProcessedCUs.count(CU.get()))
1628       continue;
1629 
1630     const DWARFDebugLine::LineTable *LineTable =
1631         DwCtx->getLineTableForUnit(CU.get());
1632     const std::vector<DWARFDebugLine::FileNameEntry> &FileNames =
1633         LineTable->Prologue.FileNames;
1634 
1635     uint16_t DwarfVersion = LineTable->Prologue.getVersion();
1636     if (DwarfVersion >= 5) {
1637       Optional<MD5::MD5Result> Checksum = None;
1638       if (LineTable->Prologue.ContentTypes.HasMD5)
1639         Checksum = LineTable->Prologue.FileNames[0].Checksum;
1640       Optional<const char *> Name =
1641           dwarf::toString(CU->getUnitDIE().find(dwarf::DW_AT_name), nullptr);
1642       if (Optional<uint64_t> DWOID = CU->getDWOId()) {
1643         auto Iter = DWOCUs.find(*DWOID);
1644         assert(Iter != DWOCUs.end() && "DWO CU was not found.");
1645         Name = dwarf::toString(
1646             Iter->second->getUnitDIE().find(dwarf::DW_AT_name), nullptr);
1647       }
1648       BinaryLineTable.setRootFile(CU->getCompilationDir(), *Name, Checksum,
1649                                   None);
1650     }
1651 
1652     BinaryLineTable.setDwarfVersion(DwarfVersion);
1653 
1654     // Assign a unique label to every line table, one per CU.
1655     // Make sure empty debug line tables are registered too.
1656     if (FileNames.empty()) {
1657       cantFail(
1658           getDwarfFile("", "<unknown>", 0, None, None, CUID, DwarfVersion));
1659       continue;
1660     }
1661     const uint32_t Offset = DwarfVersion < 5 ? 1 : 0;
1662     for (size_t I = 0, Size = FileNames.size(); I != Size; ++I) {
1663       // Dir indexes start at 1, as DWARF file numbers, and a dir index 0
1664       // means empty dir.
1665       StringRef Dir = "";
1666       if (FileNames[I].DirIdx != 0 || DwarfVersion >= 5)
1667         if (Optional<const char *> DirName = dwarf::toString(
1668                 LineTable->Prologue
1669                     .IncludeDirectories[FileNames[I].DirIdx - Offset]))
1670           Dir = *DirName;
1671       StringRef FileName = "";
1672       if (Optional<const char *> FName = dwarf::toString(FileNames[I].Name))
1673         FileName = *FName;
1674       assert(FileName != "");
1675       Optional<MD5::MD5Result> Checksum = None;
1676       if (DwarfVersion >= 5 && LineTable->Prologue.ContentTypes.HasMD5)
1677         Checksum = LineTable->Prologue.FileNames[I].Checksum;
1678       cantFail(
1679           getDwarfFile(Dir, FileName, 0, Checksum, None, CUID, DwarfVersion));
1680     }
1681   }
1682 }
1683 
1684 bool BinaryContext::shouldEmit(const BinaryFunction &Function) const {
1685   if (Function.isPseudo())
1686     return false;
1687 
1688   if (opts::processAllFunctions())
1689     return true;
1690 
1691   if (Function.isIgnored())
1692     return false;
1693 
1694   // In relocation mode we will emit non-simple functions with CFG.
1695   // If the function does not have a CFG it should be marked as ignored.
1696   return HasRelocations || Function.isSimple();
1697 }
1698 
1699 void BinaryContext::printCFI(raw_ostream &OS, const MCCFIInstruction &Inst) {
1700   uint32_t Operation = Inst.getOperation();
1701   switch (Operation) {
1702   case MCCFIInstruction::OpSameValue:
1703     OS << "OpSameValue Reg" << Inst.getRegister();
1704     break;
1705   case MCCFIInstruction::OpRememberState:
1706     OS << "OpRememberState";
1707     break;
1708   case MCCFIInstruction::OpRestoreState:
1709     OS << "OpRestoreState";
1710     break;
1711   case MCCFIInstruction::OpOffset:
1712     OS << "OpOffset Reg" << Inst.getRegister() << " " << Inst.getOffset();
1713     break;
1714   case MCCFIInstruction::OpDefCfaRegister:
1715     OS << "OpDefCfaRegister Reg" << Inst.getRegister();
1716     break;
1717   case MCCFIInstruction::OpDefCfaOffset:
1718     OS << "OpDefCfaOffset " << Inst.getOffset();
1719     break;
1720   case MCCFIInstruction::OpDefCfa:
1721     OS << "OpDefCfa Reg" << Inst.getRegister() << " " << Inst.getOffset();
1722     break;
1723   case MCCFIInstruction::OpRelOffset:
1724     OS << "OpRelOffset Reg" << Inst.getRegister() << " " << Inst.getOffset();
1725     break;
1726   case MCCFIInstruction::OpAdjustCfaOffset:
1727     OS << "OfAdjustCfaOffset " << Inst.getOffset();
1728     break;
1729   case MCCFIInstruction::OpEscape:
1730     OS << "OpEscape";
1731     break;
1732   case MCCFIInstruction::OpRestore:
1733     OS << "OpRestore Reg" << Inst.getRegister();
1734     break;
1735   case MCCFIInstruction::OpUndefined:
1736     OS << "OpUndefined Reg" << Inst.getRegister();
1737     break;
1738   case MCCFIInstruction::OpRegister:
1739     OS << "OpRegister Reg" << Inst.getRegister() << " Reg"
1740        << Inst.getRegister2();
1741     break;
1742   case MCCFIInstruction::OpWindowSave:
1743     OS << "OpWindowSave";
1744     break;
1745   case MCCFIInstruction::OpGnuArgsSize:
1746     OS << "OpGnuArgsSize";
1747     break;
1748   default:
1749     OS << "Op#" << Operation;
1750     break;
1751   }
1752 }
1753 
1754 MarkerSymType BinaryContext::getMarkerType(const SymbolRef &Symbol) const {
1755   // For aarch64, the ABI defines mapping symbols so we identify data in the
1756   // code section (see IHI0056B). $x identifies a symbol starting code or the
1757   // end of a data chunk inside code, $d indentifies start of data.
1758   if (!isAArch64() || ELFSymbolRef(Symbol).getSize())
1759     return MarkerSymType::NONE;
1760 
1761   Expected<StringRef> NameOrError = Symbol.getName();
1762   Expected<object::SymbolRef::Type> TypeOrError = Symbol.getType();
1763 
1764   if (!TypeOrError || !NameOrError)
1765     return MarkerSymType::NONE;
1766 
1767   if (*TypeOrError != SymbolRef::ST_Unknown)
1768     return MarkerSymType::NONE;
1769 
1770   if (*NameOrError == "$x" || NameOrError->startswith("$x."))
1771     return MarkerSymType::CODE;
1772 
1773   if (*NameOrError == "$d" || NameOrError->startswith("$d."))
1774     return MarkerSymType::DATA;
1775 
1776   return MarkerSymType::NONE;
1777 }
1778 
1779 bool BinaryContext::isMarker(const SymbolRef &Symbol) const {
1780   return getMarkerType(Symbol) != MarkerSymType::NONE;
1781 }
1782 
1783 static void printDebugInfo(raw_ostream &OS, const MCInst &Instruction,
1784                            const BinaryFunction *Function,
1785                            DWARFContext *DwCtx) {
1786   DebugLineTableRowRef RowRef =
1787       DebugLineTableRowRef::fromSMLoc(Instruction.getLoc());
1788   if (RowRef == DebugLineTableRowRef::NULL_ROW)
1789     return;
1790 
1791   const DWARFDebugLine::LineTable *LineTable;
1792   if (Function && Function->getDWARFUnit() &&
1793       Function->getDWARFUnit()->getOffset() == RowRef.DwCompileUnitIndex) {
1794     LineTable = Function->getDWARFLineTable();
1795   } else {
1796     LineTable = DwCtx->getLineTableForUnit(
1797         DwCtx->getCompileUnitForOffset(RowRef.DwCompileUnitIndex));
1798   }
1799   assert(LineTable && "line table expected for instruction with debug info");
1800 
1801   const DWARFDebugLine::Row &Row = LineTable->Rows[RowRef.RowIndex - 1];
1802   StringRef FileName = "";
1803   if (Optional<const char *> FName =
1804           dwarf::toString(LineTable->Prologue.FileNames[Row.File - 1].Name))
1805     FileName = *FName;
1806   OS << " # debug line " << FileName << ":" << Row.Line;
1807   if (Row.Column)
1808     OS << ":" << Row.Column;
1809   if (Row.Discriminator)
1810     OS << " discriminator:" << Row.Discriminator;
1811 }
1812 
1813 void BinaryContext::printInstruction(raw_ostream &OS, const MCInst &Instruction,
1814                                      uint64_t Offset,
1815                                      const BinaryFunction *Function,
1816                                      bool PrintMCInst, bool PrintMemData,
1817                                      bool PrintRelocations,
1818                                      StringRef Endl) const {
1819   if (MIB->isEHLabel(Instruction)) {
1820     OS << "  EH_LABEL: " << *MIB->getTargetSymbol(Instruction) << Endl;
1821     return;
1822   }
1823   OS << format("    %08" PRIx64 ": ", Offset);
1824   if (MIB->isCFI(Instruction)) {
1825     uint32_t Offset = Instruction.getOperand(0).getImm();
1826     OS << "\t!CFI\t$" << Offset << "\t; ";
1827     if (Function)
1828       printCFI(OS, *Function->getCFIFor(Instruction));
1829     OS << Endl;
1830     return;
1831   }
1832   InstPrinter->printInst(&Instruction, 0, "", *STI, OS);
1833   if (MIB->isCall(Instruction)) {
1834     if (MIB->isTailCall(Instruction))
1835       OS << " # TAILCALL ";
1836     if (MIB->isInvoke(Instruction)) {
1837       const Optional<MCPlus::MCLandingPad> EHInfo = MIB->getEHInfo(Instruction);
1838       OS << " # handler: ";
1839       if (EHInfo->first)
1840         OS << *EHInfo->first;
1841       else
1842         OS << '0';
1843       OS << "; action: " << EHInfo->second;
1844       const int64_t GnuArgsSize = MIB->getGnuArgsSize(Instruction);
1845       if (GnuArgsSize >= 0)
1846         OS << "; GNU_args_size = " << GnuArgsSize;
1847     }
1848   } else if (MIB->isIndirectBranch(Instruction)) {
1849     if (uint64_t JTAddress = MIB->getJumpTable(Instruction)) {
1850       OS << " # JUMPTABLE @0x" << Twine::utohexstr(JTAddress);
1851     } else {
1852       OS << " # UNKNOWN CONTROL FLOW";
1853     }
1854   }
1855   if (Optional<uint32_t> Offset = MIB->getOffset(Instruction))
1856     OS << " # Offset: " << *Offset;
1857 
1858   MIB->printAnnotations(Instruction, OS);
1859 
1860   if (opts::PrintDebugInfo)
1861     printDebugInfo(OS, Instruction, Function, DwCtx.get());
1862 
1863   if ((opts::PrintRelocations || PrintRelocations) && Function) {
1864     const uint64_t Size = computeCodeSize(&Instruction, &Instruction + 1);
1865     Function->printRelocations(OS, Offset, Size);
1866   }
1867 
1868   OS << Endl;
1869 
1870   if (PrintMCInst) {
1871     Instruction.dump_pretty(OS, InstPrinter.get());
1872     OS << Endl;
1873   }
1874 }
1875 
1876 Optional<uint64_t>
1877 BinaryContext::getBaseAddressForMapping(uint64_t MMapAddress,
1878                                         uint64_t FileOffset) const {
1879   // Find a segment with a matching file offset.
1880   for (auto &KV : SegmentMapInfo) {
1881     const SegmentInfo &SegInfo = KV.second;
1882     if (alignDown(SegInfo.FileOffset, SegInfo.Alignment) == FileOffset) {
1883       // Use segment's aligned memory offset to calculate the base address.
1884       const uint64_t MemOffset = alignDown(SegInfo.Address, SegInfo.Alignment);
1885       return MMapAddress - MemOffset;
1886     }
1887   }
1888 
1889   return NoneType();
1890 }
1891 
1892 ErrorOr<BinarySection &> BinaryContext::getSectionForAddress(uint64_t Address) {
1893   auto SI = AddressToSection.upper_bound(Address);
1894   if (SI != AddressToSection.begin()) {
1895     --SI;
1896     uint64_t UpperBound = SI->first + SI->second->getSize();
1897     if (!SI->second->getSize())
1898       UpperBound += 1;
1899     if (UpperBound > Address)
1900       return *SI->second;
1901   }
1902   return std::make_error_code(std::errc::bad_address);
1903 }
1904 
1905 ErrorOr<StringRef>
1906 BinaryContext::getSectionNameForAddress(uint64_t Address) const {
1907   if (ErrorOr<const BinarySection &> Section = getSectionForAddress(Address))
1908     return Section->getName();
1909   return std::make_error_code(std::errc::bad_address);
1910 }
1911 
1912 BinarySection &BinaryContext::registerSection(BinarySection *Section) {
1913   auto Res = Sections.insert(Section);
1914   (void)Res;
1915   assert(Res.second && "can't register the same section twice.");
1916 
1917   // Only register allocatable sections in the AddressToSection map.
1918   if (Section->isAllocatable() && Section->getAddress())
1919     AddressToSection.insert(std::make_pair(Section->getAddress(), Section));
1920   NameToSection.insert(
1921       std::make_pair(std::string(Section->getName()), Section));
1922   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: registering " << *Section << "\n");
1923   return *Section;
1924 }
1925 
1926 BinarySection &BinaryContext::registerSection(SectionRef Section) {
1927   return registerSection(new BinarySection(*this, Section));
1928 }
1929 
1930 BinarySection &
1931 BinaryContext::registerSection(StringRef SectionName,
1932                                const BinarySection &OriginalSection) {
1933   return registerSection(
1934       new BinarySection(*this, SectionName, OriginalSection));
1935 }
1936 
1937 BinarySection &
1938 BinaryContext::registerOrUpdateSection(StringRef Name, unsigned ELFType,
1939                                        unsigned ELFFlags, uint8_t *Data,
1940                                        uint64_t Size, unsigned Alignment) {
1941   auto NamedSections = getSectionByName(Name);
1942   if (NamedSections.begin() != NamedSections.end()) {
1943     assert(std::next(NamedSections.begin()) == NamedSections.end() &&
1944            "can only update unique sections");
1945     BinarySection *Section = NamedSections.begin()->second;
1946 
1947     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: updating " << *Section << " -> ");
1948     const bool Flag = Section->isAllocatable();
1949     (void)Flag;
1950     Section->update(Data, Size, Alignment, ELFType, ELFFlags);
1951     LLVM_DEBUG(dbgs() << *Section << "\n");
1952     // FIXME: Fix section flags/attributes for MachO.
1953     if (isELF())
1954       assert(Flag == Section->isAllocatable() &&
1955              "can't change section allocation status");
1956     return *Section;
1957   }
1958 
1959   return registerSection(
1960       new BinarySection(*this, Name, Data, Size, Alignment, ELFType, ELFFlags));
1961 }
1962 
1963 bool BinaryContext::deregisterSection(BinarySection &Section) {
1964   BinarySection *SectionPtr = &Section;
1965   auto Itr = Sections.find(SectionPtr);
1966   if (Itr != Sections.end()) {
1967     auto Range = AddressToSection.equal_range(SectionPtr->getAddress());
1968     while (Range.first != Range.second) {
1969       if (Range.first->second == SectionPtr) {
1970         AddressToSection.erase(Range.first);
1971         break;
1972       }
1973       ++Range.first;
1974     }
1975 
1976     auto NameRange =
1977         NameToSection.equal_range(std::string(SectionPtr->getName()));
1978     while (NameRange.first != NameRange.second) {
1979       if (NameRange.first->second == SectionPtr) {
1980         NameToSection.erase(NameRange.first);
1981         break;
1982       }
1983       ++NameRange.first;
1984     }
1985 
1986     Sections.erase(Itr);
1987     delete SectionPtr;
1988     return true;
1989   }
1990   return false;
1991 }
1992 
1993 void BinaryContext::printSections(raw_ostream &OS) const {
1994   for (BinarySection *const &Section : Sections)
1995     OS << "BOLT-INFO: " << *Section << "\n";
1996 }
1997 
1998 BinarySection &BinaryContext::absoluteSection() {
1999   if (ErrorOr<BinarySection &> Section = getUniqueSectionByName("<absolute>"))
2000     return *Section;
2001   return registerOrUpdateSection("<absolute>", ELF::SHT_NULL, 0u);
2002 }
2003 
2004 ErrorOr<uint64_t> BinaryContext::getUnsignedValueAtAddress(uint64_t Address,
2005                                                            size_t Size) const {
2006   const ErrorOr<const BinarySection &> Section = getSectionForAddress(Address);
2007   if (!Section)
2008     return std::make_error_code(std::errc::bad_address);
2009 
2010   if (Section->isVirtual())
2011     return 0;
2012 
2013   DataExtractor DE(Section->getContents(), AsmInfo->isLittleEndian(),
2014                    AsmInfo->getCodePointerSize());
2015   auto ValueOffset = static_cast<uint64_t>(Address - Section->getAddress());
2016   return DE.getUnsigned(&ValueOffset, Size);
2017 }
2018 
2019 ErrorOr<uint64_t> BinaryContext::getSignedValueAtAddress(uint64_t Address,
2020                                                          size_t Size) const {
2021   const ErrorOr<const BinarySection &> Section = getSectionForAddress(Address);
2022   if (!Section)
2023     return std::make_error_code(std::errc::bad_address);
2024 
2025   if (Section->isVirtual())
2026     return 0;
2027 
2028   DataExtractor DE(Section->getContents(), AsmInfo->isLittleEndian(),
2029                    AsmInfo->getCodePointerSize());
2030   auto ValueOffset = static_cast<uint64_t>(Address - Section->getAddress());
2031   return DE.getSigned(&ValueOffset, Size);
2032 }
2033 
2034 void BinaryContext::addRelocation(uint64_t Address, MCSymbol *Symbol,
2035                                   uint64_t Type, uint64_t Addend,
2036                                   uint64_t Value) {
2037   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
2038   assert(Section && "cannot find section for address");
2039   Section->addRelocation(Address - Section->getAddress(), Symbol, Type, Addend,
2040                          Value);
2041 }
2042 
2043 void BinaryContext::addDynamicRelocation(uint64_t Address, MCSymbol *Symbol,
2044                                          uint64_t Type, uint64_t Addend,
2045                                          uint64_t Value) {
2046   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
2047   assert(Section && "cannot find section for address");
2048   Section->addDynamicRelocation(Address - Section->getAddress(), Symbol, Type,
2049                                 Addend, Value);
2050 }
2051 
2052 bool BinaryContext::removeRelocationAt(uint64_t Address) {
2053   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
2054   assert(Section && "cannot find section for address");
2055   return Section->removeRelocationAt(Address - Section->getAddress());
2056 }
2057 
2058 const Relocation *BinaryContext::getRelocationAt(uint64_t Address) {
2059   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
2060   if (!Section)
2061     return nullptr;
2062 
2063   return Section->getRelocationAt(Address - Section->getAddress());
2064 }
2065 
2066 const Relocation *BinaryContext::getDynamicRelocationAt(uint64_t Address) {
2067   ErrorOr<BinarySection &> Section = getSectionForAddress(Address);
2068   if (!Section)
2069     return nullptr;
2070 
2071   return Section->getDynamicRelocationAt(Address - Section->getAddress());
2072 }
2073 
2074 void BinaryContext::markAmbiguousRelocations(BinaryData &BD,
2075                                              const uint64_t Address) {
2076   auto setImmovable = [&](BinaryData &BD) {
2077     BinaryData *Root = BD.getAtomicRoot();
2078     LLVM_DEBUG(if (Root->isMoveable()) {
2079       dbgs() << "BOLT-DEBUG: setting " << *Root << " as immovable "
2080              << "due to ambiguous relocation referencing 0x"
2081              << Twine::utohexstr(Address) << '\n';
2082     });
2083     Root->setIsMoveable(false);
2084   };
2085 
2086   if (Address == BD.getAddress()) {
2087     setImmovable(BD);
2088 
2089     // Set previous symbol as immovable
2090     BinaryData *Prev = getBinaryDataContainingAddress(Address - 1);
2091     if (Prev && Prev->getEndAddress() == BD.getAddress())
2092       setImmovable(*Prev);
2093   }
2094 
2095   if (Address == BD.getEndAddress()) {
2096     setImmovable(BD);
2097 
2098     // Set next symbol as immovable
2099     BinaryData *Next = getBinaryDataContainingAddress(BD.getEndAddress());
2100     if (Next && Next->getAddress() == BD.getEndAddress())
2101       setImmovable(*Next);
2102   }
2103 }
2104 
2105 BinaryFunction *BinaryContext::getFunctionForSymbol(const MCSymbol *Symbol,
2106                                                     uint64_t *EntryDesc) {
2107   std::shared_lock<std::shared_timed_mutex> Lock(SymbolToFunctionMapMutex);
2108   auto BFI = SymbolToFunctionMap.find(Symbol);
2109   if (BFI == SymbolToFunctionMap.end())
2110     return nullptr;
2111 
2112   BinaryFunction *BF = BFI->second;
2113   if (EntryDesc)
2114     *EntryDesc = BF->getEntryIDForSymbol(Symbol);
2115 
2116   return BF;
2117 }
2118 
2119 void BinaryContext::exitWithBugReport(StringRef Message,
2120                                       const BinaryFunction &Function) const {
2121   errs() << "=======================================\n";
2122   errs() << "BOLT is unable to proceed because it couldn't properly understand "
2123             "this function.\n";
2124   errs() << "If you are running the most recent version of BOLT, you may "
2125             "want to "
2126             "report this and paste this dump.\nPlease check that there is no "
2127             "sensitive contents being shared in this dump.\n";
2128   errs() << "\nOffending function: " << Function.getPrintName() << "\n\n";
2129   ScopedPrinter SP(errs());
2130   SP.printBinaryBlock("Function contents", *Function.getData());
2131   errs() << "\n";
2132   Function.dump();
2133   errs() << "ERROR: " << Message;
2134   errs() << "\n=======================================\n";
2135   exit(1);
2136 }
2137 
2138 BinaryFunction *
2139 BinaryContext::createInjectedBinaryFunction(const std::string &Name,
2140                                             bool IsSimple) {
2141   InjectedBinaryFunctions.push_back(new BinaryFunction(Name, *this, IsSimple));
2142   BinaryFunction *BF = InjectedBinaryFunctions.back();
2143   setSymbolToFunctionMap(BF->getSymbol(), BF);
2144   BF->CurrentState = BinaryFunction::State::CFG;
2145   return BF;
2146 }
2147 
2148 std::pair<size_t, size_t>
2149 BinaryContext::calculateEmittedSize(BinaryFunction &BF, bool FixBranches) {
2150   // Adjust branch instruction to match the current layout.
2151   if (FixBranches)
2152     BF.fixBranches();
2153 
2154   // Create local MC context to isolate the effect of ephemeral code emission.
2155   IndependentCodeEmitter MCEInstance = createIndependentMCCodeEmitter();
2156   MCContext *LocalCtx = MCEInstance.LocalCtx.get();
2157   MCAsmBackend *MAB =
2158       TheTarget->createMCAsmBackend(*STI, *MRI, MCTargetOptions());
2159 
2160   SmallString<256> Code;
2161   raw_svector_ostream VecOS(Code);
2162 
2163   std::unique_ptr<MCObjectWriter> OW = MAB->createObjectWriter(VecOS);
2164   std::unique_ptr<MCStreamer> Streamer(TheTarget->createMCObjectStreamer(
2165       *TheTriple, *LocalCtx, std::unique_ptr<MCAsmBackend>(MAB), std::move(OW),
2166       std::unique_ptr<MCCodeEmitter>(MCEInstance.MCE.release()), *STI,
2167       /*RelaxAll=*/false,
2168       /*IncrementalLinkerCompatible=*/false,
2169       /*DWARFMustBeAtTheEnd=*/false));
2170 
2171   Streamer->initSections(false, *STI);
2172 
2173   MCSection *Section = MCEInstance.LocalMOFI->getTextSection();
2174   Section->setHasInstructions(true);
2175 
2176   // Create symbols in the LocalCtx so that they get destroyed with it.
2177   MCSymbol *StartLabel = LocalCtx->createTempSymbol();
2178   MCSymbol *EndLabel = LocalCtx->createTempSymbol();
2179   MCSymbol *ColdStartLabel = LocalCtx->createTempSymbol();
2180   MCSymbol *ColdEndLabel = LocalCtx->createTempSymbol();
2181 
2182   Streamer->switchSection(Section);
2183   Streamer->emitLabel(StartLabel);
2184   emitFunctionBody(*Streamer, BF, /*EmitColdPart=*/false,
2185                    /*EmitCodeOnly=*/true);
2186   Streamer->emitLabel(EndLabel);
2187 
2188   if (BF.isSplit()) {
2189     MCSectionELF *ColdSection =
2190         LocalCtx->getELFSection(BF.getColdCodeSectionName(), ELF::SHT_PROGBITS,
2191                                 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC);
2192     ColdSection->setHasInstructions(true);
2193 
2194     Streamer->switchSection(ColdSection);
2195     Streamer->emitLabel(ColdStartLabel);
2196     emitFunctionBody(*Streamer, BF, /*EmitColdPart=*/true,
2197                      /*EmitCodeOnly=*/true);
2198     Streamer->emitLabel(ColdEndLabel);
2199     // To avoid calling MCObjectStreamer::flushPendingLabels() which is private
2200     Streamer->emitBytes(StringRef(""));
2201     Streamer->switchSection(Section);
2202   }
2203 
2204   // To avoid calling MCObjectStreamer::flushPendingLabels() which is private or
2205   // MCStreamer::Finish(), which does more than we want
2206   Streamer->emitBytes(StringRef(""));
2207 
2208   MCAssembler &Assembler =
2209       static_cast<MCObjectStreamer *>(Streamer.get())->getAssembler();
2210   MCAsmLayout Layout(Assembler);
2211   Assembler.layout(Layout);
2212 
2213   const uint64_t HotSize =
2214       Layout.getSymbolOffset(*EndLabel) - Layout.getSymbolOffset(*StartLabel);
2215   const uint64_t ColdSize = BF.isSplit()
2216                                 ? Layout.getSymbolOffset(*ColdEndLabel) -
2217                                       Layout.getSymbolOffset(*ColdStartLabel)
2218                                 : 0ULL;
2219 
2220   // Clean-up the effect of the code emission.
2221   for (const MCSymbol &Symbol : Assembler.symbols()) {
2222     MCSymbol *MutableSymbol = const_cast<MCSymbol *>(&Symbol);
2223     MutableSymbol->setUndefined();
2224     MutableSymbol->setIsRegistered(false);
2225   }
2226 
2227   return std::make_pair(HotSize, ColdSize);
2228 }
2229 
2230 bool BinaryContext::validateEncoding(const MCInst &Inst,
2231                                      ArrayRef<uint8_t> InputEncoding) const {
2232   SmallString<256> Code;
2233   SmallVector<MCFixup, 4> Fixups;
2234   raw_svector_ostream VecOS(Code);
2235 
2236   MCE->encodeInstruction(Inst, VecOS, Fixups, *STI);
2237   auto EncodedData = ArrayRef<uint8_t>((uint8_t *)Code.data(), Code.size());
2238   if (InputEncoding != EncodedData) {
2239     if (opts::Verbosity > 1) {
2240       errs() << "BOLT-WARNING: mismatched encoding detected\n"
2241              << "      input: " << InputEncoding << '\n'
2242              << "     output: " << EncodedData << '\n';
2243     }
2244     return false;
2245   }
2246 
2247   return true;
2248 }
2249 
2250 uint64_t BinaryContext::getHotThreshold() const {
2251   static uint64_t Threshold = 0;
2252   if (Threshold == 0) {
2253     Threshold = std::max(
2254         (uint64_t)opts::ExecutionCountThreshold,
2255         NumProfiledFuncs ? SumExecutionCount / (2 * NumProfiledFuncs) : 1);
2256   }
2257   return Threshold;
2258 }
2259 
2260 BinaryFunction *BinaryContext::getBinaryFunctionContainingAddress(
2261     uint64_t Address, bool CheckPastEnd, bool UseMaxSize) {
2262   auto FI = BinaryFunctions.upper_bound(Address);
2263   if (FI == BinaryFunctions.begin())
2264     return nullptr;
2265   --FI;
2266 
2267   const uint64_t UsedSize =
2268       UseMaxSize ? FI->second.getMaxSize() : FI->second.getSize();
2269 
2270   if (Address >= FI->first + UsedSize + (CheckPastEnd ? 1 : 0))
2271     return nullptr;
2272 
2273   return &FI->second;
2274 }
2275 
2276 BinaryFunction *BinaryContext::getBinaryFunctionAtAddress(uint64_t Address) {
2277   // First, try to find a function starting at the given address. If the
2278   // function was folded, this will get us the original folded function if it
2279   // wasn't removed from the list, e.g. in non-relocation mode.
2280   auto BFI = BinaryFunctions.find(Address);
2281   if (BFI != BinaryFunctions.end())
2282     return &BFI->second;
2283 
2284   // We might have folded the function matching the object at the given
2285   // address. In such case, we look for a function matching the symbol
2286   // registered at the original address. The new function (the one that the
2287   // original was folded into) will hold the symbol.
2288   if (const BinaryData *BD = getBinaryDataAtAddress(Address)) {
2289     uint64_t EntryID = 0;
2290     BinaryFunction *BF = getFunctionForSymbol(BD->getSymbol(), &EntryID);
2291     if (BF && EntryID == 0)
2292       return BF;
2293   }
2294   return nullptr;
2295 }
2296 
2297 DebugAddressRangesVector BinaryContext::translateModuleAddressRanges(
2298     const DWARFAddressRangesVector &InputRanges) const {
2299   DebugAddressRangesVector OutputRanges;
2300 
2301   for (const DWARFAddressRange Range : InputRanges) {
2302     auto BFI = BinaryFunctions.lower_bound(Range.LowPC);
2303     while (BFI != BinaryFunctions.end()) {
2304       const BinaryFunction &Function = BFI->second;
2305       if (Function.getAddress() >= Range.HighPC)
2306         break;
2307       const DebugAddressRangesVector FunctionRanges =
2308           Function.getOutputAddressRanges();
2309       llvm::move(FunctionRanges, std::back_inserter(OutputRanges));
2310       std::advance(BFI, 1);
2311     }
2312   }
2313 
2314   return OutputRanges;
2315 }
2316 
2317 } // namespace bolt
2318 } // namespace llvm
2319