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