xref: /llvm-project/bolt/lib/Profile/BoltAddressTranslation.cpp (revision 2d3c827c053c112491dc1102ff31fc7d703adc36)
1 //===- bolt/Profile/BoltAddressTranslation.cpp ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "bolt/Profile/BoltAddressTranslation.h"
10 #include "bolt/Core/BinaryFunction.h"
11 #include "llvm/ADT/APInt.h"
12 #include "llvm/Support/Errc.h"
13 #include "llvm/Support/Error.h"
14 #include "llvm/Support/LEB128.h"
15 
16 #define DEBUG_TYPE "bolt-bat"
17 
18 namespace llvm {
19 namespace bolt {
20 
21 const char *BoltAddressTranslation::SECTION_NAME = ".note.bolt_bat";
22 
23 void BoltAddressTranslation::writeEntriesForBB(MapTy &Map,
24                                                const BinaryBasicBlock &BB,
25                                                uint64_t FuncInputAddress,
26                                                uint64_t FuncOutputAddress) {
27   const uint64_t BBOutputOffset =
28       BB.getOutputAddressRange().first - FuncOutputAddress;
29   const uint32_t BBInputOffset = BB.getInputOffset();
30 
31   // Every output BB must track back to an input BB for profile collection
32   // in bolted binaries. If we are missing an offset, it means this block was
33   // created by a pass. We will skip writing any entries for it, and this means
34   // any traffic happening in this block will map to the previous block in the
35   // layout. This covers the case where an input basic block is split into two,
36   // and the second one lacks any offset.
37   if (BBInputOffset == BinaryBasicBlock::INVALID_OFFSET)
38     return;
39 
40   LLVM_DEBUG(dbgs() << "BB " << BB.getName() << "\n");
41   LLVM_DEBUG(dbgs() << "  Key: " << Twine::utohexstr(BBOutputOffset)
42                     << " Val: " << Twine::utohexstr(BBInputOffset) << "\n");
43   // NB: in `writeEntriesForBB` we use the input address because hashes are
44   // saved early in `saveMetadata` before output addresses are assigned.
45   const BBHashMapTy &BBHashMap = getBBHashMap(FuncInputAddress);
46   (void)BBHashMap;
47   LLVM_DEBUG(
48       dbgs() << formatv(" Hash: {0:x}\n", BBHashMap.getBBHash(BBInputOffset)));
49   LLVM_DEBUG(
50       dbgs() << formatv(" Index: {0}\n", BBHashMap.getBBIndex(BBInputOffset)));
51   // In case of conflicts (same Key mapping to different Vals), the last
52   // update takes precedence. Of course it is not ideal to have conflicts and
53   // those happen when we have an empty BB that either contained only
54   // NOPs or a jump to the next block (successor). Either way, the successor
55   // and this deleted block will both share the same output address (the same
56   // key), and we need to map back. We choose here to privilege the successor by
57   // allowing it to overwrite the previously inserted key in the map.
58   Map[BBOutputOffset] = BBInputOffset << 1;
59 
60   const auto &IOAddressMap =
61       BB.getFunction()->getBinaryContext().getIOAddressMap();
62 
63   for (const auto &[InputOffset, Sym] : BB.getLocSyms()) {
64     const auto InputAddress = BB.getFunction()->getAddress() + InputOffset;
65     const auto OutputAddress = IOAddressMap.lookup(InputAddress);
66     assert(OutputAddress && "Unknown instruction address");
67     const auto OutputOffset = *OutputAddress - FuncOutputAddress;
68 
69     // Is this the first instruction in the BB? No need to duplicate the entry.
70     if (OutputOffset == BBOutputOffset)
71       continue;
72 
73     LLVM_DEBUG(dbgs() << "  Key: " << Twine::utohexstr(OutputOffset) << " Val: "
74                       << Twine::utohexstr(InputOffset) << " (branch)\n");
75     Map.insert(std::pair<uint32_t, uint32_t>(OutputOffset,
76                                              (InputOffset << 1) | BRANCHENTRY));
77   }
78 }
79 
80 void BoltAddressTranslation::write(const BinaryContext &BC, raw_ostream &OS) {
81   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Writing BOLT Address Translation Tables\n");
82   for (auto &BFI : BC.getBinaryFunctions()) {
83     const BinaryFunction &Function = BFI.second;
84     const uint64_t InputAddress = Function.getAddress();
85     const uint64_t OutputAddress = Function.getOutputAddress();
86     // We don't need a translation table if the body of the function hasn't
87     // changed
88     if (Function.isIgnored() || (!BC.HasRelocations && !Function.isSimple()))
89       continue;
90 
91     uint32_t NumSecondaryEntryPoints = 0;
92     Function.forEachEntryPoint([&](uint64_t Offset, const MCSymbol *) {
93       if (!Offset)
94         return true;
95       ++NumSecondaryEntryPoints;
96       SecondaryEntryPointsMap[OutputAddress].push_back(Offset);
97       return true;
98     });
99 
100     LLVM_DEBUG(dbgs() << "Function name: " << Function.getPrintName() << "\n");
101     LLVM_DEBUG(dbgs() << " Address reference: 0x"
102                       << Twine::utohexstr(Function.getOutputAddress()) << "\n");
103     LLVM_DEBUG(dbgs() << formatv(" Hash: {0:x}\n", getBFHash(OutputAddress)));
104     LLVM_DEBUG(dbgs() << " Secondary Entry Points: " << NumSecondaryEntryPoints
105                       << '\n');
106 
107     MapTy Map;
108     for (const BinaryBasicBlock *const BB :
109          Function.getLayout().getMainFragment())
110       writeEntriesForBB(Map, *BB, InputAddress, OutputAddress);
111     Maps.emplace(Function.getOutputAddress(), std::move(Map));
112     ReverseMap.emplace(OutputAddress, InputAddress);
113 
114     if (!Function.isSplit())
115       continue;
116 
117     // Split maps
118     LLVM_DEBUG(dbgs() << " Cold part\n");
119     for (const FunctionFragment &FF :
120          Function.getLayout().getSplitFragments()) {
121       ColdPartSource.emplace(FF.getAddress(), Function.getOutputAddress());
122       Map.clear();
123       for (const BinaryBasicBlock *const BB : FF)
124         writeEntriesForBB(Map, *BB, InputAddress, FF.getAddress());
125 
126       Maps.emplace(FF.getAddress(), std::move(Map));
127     }
128   }
129 
130   // Output addresses are delta-encoded
131   uint64_t PrevAddress = 0;
132   writeMaps</*Cold=*/false>(Maps, PrevAddress, OS);
133   writeMaps</*Cold=*/true>(Maps, PrevAddress, OS);
134 
135   BC.outs() << "BOLT-INFO: Wrote " << Maps.size() << " BAT maps\n";
136   BC.outs() << "BOLT-INFO: Wrote " << FuncHashes.getNumFunctions()
137             << " function and " << FuncHashes.getNumBasicBlocks()
138             << " basic block hashes\n";
139 }
140 
141 APInt BoltAddressTranslation::calculateBranchEntriesBitMask(MapTy &Map,
142                                                             size_t EqualElems) {
143   APInt BitMask(alignTo(EqualElems, 8), 0);
144   size_t Index = 0;
145   for (std::pair<const uint32_t, uint32_t> &KeyVal : Map) {
146     if (Index == EqualElems)
147       break;
148     const uint32_t OutputOffset = KeyVal.second;
149     if (OutputOffset & BRANCHENTRY)
150       BitMask.setBit(Index);
151     ++Index;
152   }
153   return BitMask;
154 }
155 
156 size_t BoltAddressTranslation::getNumEqualOffsets(const MapTy &Map) const {
157   size_t EqualOffsets = 0;
158   for (const std::pair<const uint32_t, uint32_t> &KeyVal : Map) {
159     const uint32_t OutputOffset = KeyVal.first;
160     const uint32_t InputOffset = KeyVal.second >> 1;
161     if (OutputOffset == InputOffset)
162       ++EqualOffsets;
163     else
164       break;
165   }
166   return EqualOffsets;
167 }
168 
169 template <bool Cold>
170 void BoltAddressTranslation::writeMaps(std::map<uint64_t, MapTy> &Maps,
171                                        uint64_t &PrevAddress, raw_ostream &OS) {
172   const uint32_t NumFuncs =
173       llvm::count_if(llvm::make_first_range(Maps), [&](const uint64_t Address) {
174         return Cold == ColdPartSource.count(Address);
175       });
176   encodeULEB128(NumFuncs, OS);
177   LLVM_DEBUG(dbgs() << "Writing " << NumFuncs << (Cold ? " cold" : "")
178                     << " functions for BAT.\n");
179   size_t PrevIndex = 0;
180   for (auto &MapEntry : Maps) {
181     const uint64_t Address = MapEntry.first;
182     // Only process cold fragments in cold mode, and vice versa.
183     if (Cold != ColdPartSource.count(Address))
184       continue;
185     // NB: in `writeMaps` we use the input address because hashes are saved
186     // early in `saveMetadata` before output addresses are assigned.
187     const uint64_t HotInputAddress =
188         ReverseMap[Cold ? ColdPartSource[Address] : Address];
189     MapTy &Map = MapEntry.second;
190     const uint32_t NumEntries = Map.size();
191     LLVM_DEBUG(dbgs() << "Writing " << NumEntries << " entries for 0x"
192                       << Twine::utohexstr(Address) << ".\n");
193     encodeULEB128(Address - PrevAddress, OS);
194     PrevAddress = Address;
195     const uint32_t NumSecondaryEntryPoints =
196         SecondaryEntryPointsMap.count(Address)
197             ? SecondaryEntryPointsMap[Address].size()
198             : 0;
199     if (Cold) {
200       size_t HotIndex =
201           std::distance(ColdPartSource.begin(), ColdPartSource.find(Address));
202       encodeULEB128(HotIndex - PrevIndex, OS);
203       PrevIndex = HotIndex;
204     } else {
205       // Function hash
206       size_t BFHash = getBFHash(HotInputAddress);
207       LLVM_DEBUG(dbgs() << "Hash: " << formatv("{0:x}\n", BFHash));
208       OS.write(reinterpret_cast<char *>(&BFHash), 8);
209       // Number of basic blocks
210       size_t NumBasicBlocks = getBBHashMap(HotInputAddress).getNumBasicBlocks();
211       LLVM_DEBUG(dbgs() << "Basic blocks: " << NumBasicBlocks << '\n');
212       encodeULEB128(NumBasicBlocks, OS);
213       // Secondary entry points
214       encodeULEB128(NumSecondaryEntryPoints, OS);
215       LLVM_DEBUG(dbgs() << "Secondary Entry Points: " << NumSecondaryEntryPoints
216                         << '\n');
217     }
218     encodeULEB128(NumEntries, OS);
219     // For hot fragments only: encode the number of equal offsets
220     // (output = input) in the beginning of the function. Only encode one offset
221     // in these cases.
222     const size_t EqualElems = Cold ? 0 : getNumEqualOffsets(Map);
223     if (!Cold) {
224       encodeULEB128(EqualElems, OS);
225       if (EqualElems) {
226         const size_t BranchEntriesBytes = alignTo(EqualElems, 8) / 8;
227         APInt BranchEntries = calculateBranchEntriesBitMask(Map, EqualElems);
228         OS.write(reinterpret_cast<const char *>(BranchEntries.getRawData()),
229                  BranchEntriesBytes);
230         LLVM_DEBUG({
231           dbgs() << "BranchEntries: ";
232           SmallString<8> BitMaskStr;
233           BranchEntries.toString(BitMaskStr, 2, false);
234           dbgs() << BitMaskStr << '\n';
235         });
236       }
237     }
238     const BBHashMapTy &BBHashMap = getBBHashMap(HotInputAddress);
239     size_t Index = 0;
240     uint64_t InOffset = 0;
241     size_t PrevBBIndex = 0;
242     // Output and Input addresses and delta-encoded
243     for (std::pair<const uint32_t, uint32_t> &KeyVal : Map) {
244       const uint64_t OutputAddress = KeyVal.first + Address;
245       encodeULEB128(OutputAddress - PrevAddress, OS);
246       PrevAddress = OutputAddress;
247       if (Index++ >= EqualElems)
248         encodeSLEB128(KeyVal.second - InOffset, OS);
249       InOffset = KeyVal.second; // Keeping InOffset as if BRANCHENTRY is encoded
250       if ((InOffset & BRANCHENTRY) == 0) {
251         const bool IsBlock = BBHashMap.isInputBlock(InOffset >> 1);
252         unsigned BBIndex = IsBlock ? BBHashMap.getBBIndex(InOffset >> 1) : 0;
253         size_t BBHash = IsBlock ? BBHashMap.getBBHash(InOffset >> 1) : 0;
254         OS.write(reinterpret_cast<char *>(&BBHash), 8);
255         // Basic block index in the input binary
256         encodeULEB128(BBIndex - PrevBBIndex, OS);
257         PrevBBIndex = BBIndex;
258         LLVM_DEBUG(dbgs() << formatv("{0:x} -> {1:x} {2:x} {3}\n", KeyVal.first,
259                                      InOffset >> 1, BBHash, BBIndex));
260       }
261     }
262     uint32_t PrevOffset = 0;
263     if (!Cold && NumSecondaryEntryPoints) {
264       LLVM_DEBUG(dbgs() << "Secondary entry points: ");
265       // Secondary entry point offsets, delta-encoded
266       for (uint32_t Offset : SecondaryEntryPointsMap[Address]) {
267         encodeULEB128(Offset - PrevOffset, OS);
268         LLVM_DEBUG(dbgs() << formatv("{0:x} ", Offset));
269         PrevOffset = Offset;
270       }
271       LLVM_DEBUG(dbgs() << '\n');
272     }
273   }
274 }
275 
276 std::error_code BoltAddressTranslation::parse(raw_ostream &OS, StringRef Buf) {
277   DataExtractor DE = DataExtractor(Buf, true, 8);
278   uint64_t Offset = 0;
279   if (Buf.size() < 12)
280     return make_error_code(llvm::errc::io_error);
281 
282   const uint32_t NameSz = DE.getU32(&Offset);
283   const uint32_t DescSz = DE.getU32(&Offset);
284   const uint32_t Type = DE.getU32(&Offset);
285 
286   if (Type != BinarySection::NT_BOLT_BAT ||
287       Buf.size() + Offset < alignTo(NameSz, 4) + DescSz)
288     return make_error_code(llvm::errc::io_error);
289 
290   StringRef Name = Buf.slice(Offset, Offset + NameSz);
291   Offset = alignTo(Offset + NameSz, 4);
292   if (Name.substr(0, 4) != "BOLT")
293     return make_error_code(llvm::errc::io_error);
294 
295   Error Err(Error::success());
296   std::vector<uint64_t> HotFuncs;
297   uint64_t PrevAddress = 0;
298   parseMaps</*Cold=*/false>(HotFuncs, PrevAddress, DE, Offset, Err);
299   parseMaps</*Cold=*/true>(HotFuncs, PrevAddress, DE, Offset, Err);
300   OS << "BOLT-INFO: Parsed " << Maps.size() << " BAT entries\n";
301   return errorToErrorCode(std::move(Err));
302 }
303 
304 template <bool Cold>
305 void BoltAddressTranslation::parseMaps(std::vector<uint64_t> &HotFuncs,
306                                        uint64_t &PrevAddress, DataExtractor &DE,
307                                        uint64_t &Offset, Error &Err) {
308   const uint32_t NumFunctions = DE.getULEB128(&Offset, &Err);
309   LLVM_DEBUG(dbgs() << "Parsing " << NumFunctions << (Cold ? " cold" : "")
310                     << " functions\n");
311   size_t HotIndex = 0;
312   for (uint32_t I = 0; I < NumFunctions; ++I) {
313     const uint64_t Address = PrevAddress + DE.getULEB128(&Offset, &Err);
314     uint64_t HotAddress = Cold ? 0 : Address;
315     PrevAddress = Address;
316     uint32_t SecondaryEntryPoints = 0;
317     if (Cold) {
318       HotIndex += DE.getULEB128(&Offset, &Err);
319       HotAddress = HotFuncs[HotIndex];
320       ColdPartSource.emplace(Address, HotAddress);
321     } else {
322       HotFuncs.push_back(Address);
323       // Function hash
324       const size_t FuncHash = DE.getU64(&Offset, &Err);
325       FuncHashes.addEntry(Address, FuncHash);
326       LLVM_DEBUG(dbgs() << formatv("{0:x}: hash {1:x}\n", Address, FuncHash));
327       // Number of basic blocks
328       const size_t NumBasicBlocks = DE.getULEB128(&Offset, &Err);
329       NumBasicBlocksMap.emplace(Address, NumBasicBlocks);
330       LLVM_DEBUG(dbgs() << formatv("{0:x}: #bbs {1}, {2} bytes\n", Address,
331                                    NumBasicBlocks,
332                                    getULEB128Size(NumBasicBlocks)));
333       // Secondary entry points
334       SecondaryEntryPoints = DE.getULEB128(&Offset, &Err);
335       LLVM_DEBUG(
336           dbgs() << formatv("{0:x}: secondary entry points {1}, {2} bytes\n",
337                             Address, SecondaryEntryPoints,
338                             getULEB128Size(SecondaryEntryPoints)));
339     }
340     const uint32_t NumEntries = DE.getULEB128(&Offset, &Err);
341     // Equal offsets, hot fragments only.
342     size_t EqualElems = 0;
343     APInt BEBitMask;
344     if (!Cold) {
345       EqualElems = DE.getULEB128(&Offset, &Err);
346       LLVM_DEBUG(dbgs() << formatv("Equal offsets: {0}, {1} bytes\n",
347                                    EqualElems, getULEB128Size(EqualElems)));
348       if (EqualElems) {
349         const size_t BranchEntriesBytes = alignTo(EqualElems, 8) / 8;
350         BEBitMask = APInt(alignTo(EqualElems, 8), 0);
351         LoadIntFromMemory(
352             BEBitMask,
353             reinterpret_cast<const uint8_t *>(
354                 DE.getBytes(&Offset, BranchEntriesBytes, &Err).data()),
355             BranchEntriesBytes);
356         LLVM_DEBUG({
357           dbgs() << "BEBitMask: ";
358           SmallString<8> BitMaskStr;
359           BEBitMask.toString(BitMaskStr, 2, false);
360           dbgs() << BitMaskStr << ", " << BranchEntriesBytes << " bytes\n";
361         });
362       }
363     }
364     MapTy Map;
365 
366     LLVM_DEBUG(dbgs() << "Parsing " << NumEntries << " entries for 0x"
367                       << Twine::utohexstr(Address) << "\n");
368     uint64_t InputOffset = 0;
369     size_t BBIndex = 0;
370     for (uint32_t J = 0; J < NumEntries; ++J) {
371       const uint64_t OutputDelta = DE.getULEB128(&Offset, &Err);
372       const uint64_t OutputAddress = PrevAddress + OutputDelta;
373       const uint64_t OutputOffset = OutputAddress - Address;
374       PrevAddress = OutputAddress;
375       int64_t InputDelta = 0;
376       if (J < EqualElems) {
377         InputOffset = (OutputOffset << 1) | BEBitMask[J];
378       } else {
379         InputDelta = DE.getSLEB128(&Offset, &Err);
380         InputOffset += InputDelta;
381       }
382       Map.insert(std::pair<uint32_t, uint32_t>(OutputOffset, InputOffset));
383       size_t BBHash = 0;
384       size_t BBIndexDelta = 0;
385       const bool IsBranchEntry = InputOffset & BRANCHENTRY;
386       if (!IsBranchEntry) {
387         BBHash = DE.getU64(&Offset, &Err);
388         BBIndexDelta = DE.getULEB128(&Offset, &Err);
389         BBIndex += BBIndexDelta;
390         // Map basic block hash to hot fragment by input offset
391         getBBHashMap(HotAddress).addEntry(InputOffset >> 1, BBIndex, BBHash);
392       }
393       LLVM_DEBUG({
394         dbgs() << formatv(
395             "{0:x} -> {1:x} ({2}/{3}b -> {4}/{5}b), {6:x}", OutputOffset,
396             InputOffset, OutputDelta, getULEB128Size(OutputDelta), InputDelta,
397             (J < EqualElems) ? 0 : getSLEB128Size(InputDelta), OutputAddress);
398         if (!IsBranchEntry) {
399           dbgs() << formatv(" {0:x} {1}/{2}b", BBHash, BBIndex,
400                             getULEB128Size(BBIndexDelta));
401         }
402         dbgs() << '\n';
403       });
404     }
405     Maps.insert(std::pair<uint64_t, MapTy>(Address, Map));
406     if (!Cold && SecondaryEntryPoints) {
407       uint32_t EntryPointOffset = 0;
408       LLVM_DEBUG(dbgs() << "Secondary entry points: ");
409       for (uint32_t EntryPointId = 0; EntryPointId != SecondaryEntryPoints;
410            ++EntryPointId) {
411         uint32_t OffsetDelta = DE.getULEB128(&Offset, &Err);
412         EntryPointOffset += OffsetDelta;
413         SecondaryEntryPointsMap[Address].push_back(EntryPointOffset);
414         LLVM_DEBUG(dbgs() << formatv("{0:x}/{1}b ", EntryPointOffset,
415                                      getULEB128Size(OffsetDelta)));
416       }
417       LLVM_DEBUG(dbgs() << '\n');
418     }
419   }
420 }
421 
422 void BoltAddressTranslation::dump(raw_ostream &OS) {
423   const size_t NumTables = Maps.size();
424   OS << "BAT tables for " << NumTables << " functions:\n";
425   for (const auto &MapEntry : Maps) {
426     const uint64_t Address = MapEntry.first;
427     const uint64_t HotAddress = fetchParentAddress(Address);
428     OS << "Function Address: 0x" << Twine::utohexstr(Address);
429     if (HotAddress == 0)
430       OS << formatv(", hash: {0:x}", getBFHash(Address));
431     OS << "\n";
432     OS << "BB mappings:\n";
433     const BBHashMapTy &BBHashMap =
434         getBBHashMap(HotAddress ? HotAddress : Address);
435     for (const auto &Entry : MapEntry.second) {
436       const bool IsBranch = Entry.second & BRANCHENTRY;
437       const uint32_t Val = Entry.second >> 1; // dropping BRANCHENTRY bit
438       OS << "0x" << Twine::utohexstr(Entry.first) << " -> "
439          << "0x" << Twine::utohexstr(Val);
440       if (IsBranch)
441         OS << " (branch)";
442       else
443         OS << formatv(" hash: {0:x}", BBHashMap.getBBHash(Val));
444       OS << "\n";
445     }
446     if (SecondaryEntryPointsMap.count(Address)) {
447       const std::vector<uint32_t> &SecondaryEntryPoints =
448           SecondaryEntryPointsMap[Address];
449       OS << SecondaryEntryPoints.size() << " secondary entry points:\n";
450       for (uint32_t EntryPointOffset : SecondaryEntryPoints)
451         OS << formatv("{0:x}\n", EntryPointOffset);
452     }
453     OS << "\n";
454   }
455   const size_t NumColdParts = ColdPartSource.size();
456   if (!NumColdParts)
457     return;
458 
459   OS << NumColdParts << " cold mappings:\n";
460   for (const auto &Entry : ColdPartSource) {
461     OS << "0x" << Twine::utohexstr(Entry.first) << " -> "
462        << Twine::utohexstr(Entry.second) << "\n";
463   }
464   OS << "\n";
465 }
466 
467 uint64_t BoltAddressTranslation::translate(uint64_t FuncAddress,
468                                            uint64_t Offset,
469                                            bool IsBranchSrc) const {
470   auto Iter = Maps.find(FuncAddress);
471   if (Iter == Maps.end())
472     return Offset;
473 
474   const MapTy &Map = Iter->second;
475   auto KeyVal = Map.upper_bound(Offset);
476   if (KeyVal == Map.begin())
477     return Offset;
478 
479   --KeyVal;
480 
481   const uint32_t Val = KeyVal->second >> 1; // dropping BRANCHENTRY bit
482   // Branch source addresses are translated to the first instruction of the
483   // source BB to avoid accounting for modifications BOLT may have made in the
484   // BB regarding deletion/addition of instructions.
485   if (IsBranchSrc)
486     return Val;
487   return Offset - KeyVal->first + Val;
488 }
489 
490 std::optional<BoltAddressTranslation::FallthroughListTy>
491 BoltAddressTranslation::getFallthroughsInTrace(uint64_t FuncAddress,
492                                                uint64_t From,
493                                                uint64_t To) const {
494   SmallVector<std::pair<uint64_t, uint64_t>, 16> Res;
495 
496   // Filter out trivial case
497   if (From >= To)
498     return Res;
499 
500   From -= FuncAddress;
501   To -= FuncAddress;
502 
503   auto Iter = Maps.find(FuncAddress);
504   if (Iter == Maps.end())
505     return std::nullopt;
506 
507   const MapTy &Map = Iter->second;
508   auto FromIter = Map.upper_bound(From);
509   if (FromIter == Map.begin())
510     return Res;
511   // Skip instruction entries, to create fallthroughs we are only interested in
512   // BB boundaries
513   do {
514     if (FromIter == Map.begin())
515       return Res;
516     --FromIter;
517   } while (FromIter->second & BRANCHENTRY);
518 
519   auto ToIter = Map.upper_bound(To);
520   if (ToIter == Map.begin())
521     return Res;
522   --ToIter;
523   if (FromIter->first >= ToIter->first)
524     return Res;
525 
526   for (auto Iter = FromIter; Iter != ToIter;) {
527     const uint32_t Src = Iter->first;
528     if (Iter->second & BRANCHENTRY) {
529       ++Iter;
530       continue;
531     }
532 
533     ++Iter;
534     while (Iter->second & BRANCHENTRY && Iter != ToIter)
535       ++Iter;
536     if (Iter->second & BRANCHENTRY)
537       break;
538     Res.emplace_back(Src, Iter->first);
539   }
540 
541   return Res;
542 }
543 
544 uint64_t BoltAddressTranslation::fetchParentAddress(uint64_t Address) const {
545   auto Iter = ColdPartSource.find(Address);
546   if (Iter == ColdPartSource.end())
547     return 0;
548   return Iter->second;
549 }
550 
551 bool BoltAddressTranslation::enabledFor(
552     llvm::object::ELFObjectFileBase *InputFile) const {
553   for (const SectionRef &Section : InputFile->sections()) {
554     Expected<StringRef> SectionNameOrErr = Section.getName();
555     if (Error E = SectionNameOrErr.takeError())
556       continue;
557 
558     if (SectionNameOrErr.get() == SECTION_NAME)
559       return true;
560   }
561   return false;
562 }
563 
564 void BoltAddressTranslation::saveMetadata(BinaryContext &BC) {
565   for (BinaryFunction &BF : llvm::make_second_range(BC.getBinaryFunctions())) {
566     // We don't need a translation table if the body of the function hasn't
567     // changed
568     if (BF.isIgnored() || (!BC.HasRelocations && !BF.isSimple()))
569       continue;
570     // Prepare function and block hashes
571     FuncHashes.addEntry(BF.getAddress(), BF.computeHash());
572     BF.computeBlockHashes();
573     BBHashMapTy &BBHashMap = getBBHashMap(BF.getAddress());
574     // Set BF/BB metadata
575     for (const BinaryBasicBlock &BB : BF)
576       BBHashMap.addEntry(BB.getInputOffset(), BB.getIndex(), BB.getHash());
577   }
578 }
579 
580 std::unordered_map<uint32_t, std::vector<uint32_t>>
581 BoltAddressTranslation::getBFBranches(uint64_t OutputAddress) const {
582   std::unordered_map<uint32_t, std::vector<uint32_t>> Branches;
583   auto FuncIt = Maps.find(OutputAddress);
584   assert(FuncIt != Maps.end());
585   std::vector<uint32_t> InputOffsets;
586   for (const auto &KV : FuncIt->second)
587     InputOffsets.emplace_back(KV.second);
588   // Sort with LSB BRANCHENTRY bit.
589   llvm::sort(InputOffsets);
590   uint32_t BBOffset{0};
591   for (uint32_t InOffset : InputOffsets) {
592     if (InOffset & BRANCHENTRY)
593       Branches[BBOffset].push_back(InOffset >> 1);
594     else
595       BBOffset = InOffset >> 1;
596   }
597   return Branches;
598 }
599 
600 unsigned
601 BoltAddressTranslation::getSecondaryEntryPointId(uint64_t Address,
602                                                  uint32_t Offset) const {
603   auto FunctionIt = SecondaryEntryPointsMap.find(Address);
604   if (FunctionIt == SecondaryEntryPointsMap.end())
605     return 0;
606   const std::vector<uint32_t> &Offsets = FunctionIt->second;
607   auto OffsetIt = std::find(Offsets.begin(), Offsets.end(), Offset);
608   if (OffsetIt == Offsets.end())
609     return 0;
610   // Adding one here because main entry point is not stored in BAT, and
611   // enumeration for secondary entry points starts with 1.
612   return OffsetIt - Offsets.begin() + 1;
613 }
614 
615 std::pair<const BinaryFunction *, unsigned>
616 BoltAddressTranslation::translateSymbol(const BinaryContext &BC,
617                                         const MCSymbol &Symbol,
618                                         uint32_t Offset) const {
619   // The symbol could be a secondary entry in a cold fragment.
620   uint64_t SymbolValue = cantFail(errorOrToExpected(BC.getSymbolValue(Symbol)));
621 
622   const BinaryFunction *Callee = BC.getFunctionForSymbol(&Symbol);
623   assert(Callee);
624 
625   // Containing function, not necessarily the same as symbol value.
626   const uint64_t CalleeAddress = Callee->getAddress();
627   const uint32_t OutputOffset = SymbolValue - CalleeAddress;
628 
629   const uint64_t ParentAddress = fetchParentAddress(CalleeAddress);
630   const uint64_t HotAddress = ParentAddress ? ParentAddress : CalleeAddress;
631 
632   const BinaryFunction *ParentBF = BC.getBinaryFunctionAtAddress(HotAddress);
633 
634   const uint32_t InputOffset =
635       translate(CalleeAddress, OutputOffset, /*IsBranchSrc*/ false) + Offset;
636 
637   unsigned SecondaryEntryId{0};
638   if (InputOffset)
639     SecondaryEntryId = getSecondaryEntryPointId(HotAddress, InputOffset);
640 
641   return std::pair(ParentBF, SecondaryEntryId);
642 }
643 
644 } // namespace bolt
645 } // namespace llvm
646