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