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