xref: /llvm-project/bolt/lib/Profile/BoltAddressTranslation.cpp (revision 565f40d66b8dff1dfd1e30171ca8f51dc37eb27f)
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/Support/DataExtractor.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 FuncAddress) {
26   const uint64_t BBOutputOffset =
27       BB.getOutputAddressRange().first - FuncAddress;
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   // In case of conflicts (same Key mapping to different Vals), the last
43   // update takes precedence. Of course it is not ideal to have conflicts and
44   // those happen when we have an empty BB that either contained only
45   // NOPs or a jump to the next block (successor). Either way, the successor
46   // and this deleted block will both share the same output address (the same
47   // key), and we need to map back. We choose here to privilege the successor by
48   // allowing it to overwrite the previously inserted key in the map.
49   Map[BBOutputOffset] = BBInputOffset << 1;
50 
51   const auto &IOAddressMap =
52       BB.getFunction()->getBinaryContext().getIOAddressMap();
53 
54   for (const auto &[InputOffset, Sym] : BB.getLocSyms()) {
55     const auto InputAddress = BB.getFunction()->getAddress() + InputOffset;
56     const auto OutputAddress = IOAddressMap.lookup(InputAddress);
57     assert(OutputAddress && "Unknown instruction address");
58     const auto OutputOffset = *OutputAddress - FuncAddress;
59 
60     // Is this the first instruction in the BB? No need to duplicate the entry.
61     if (OutputOffset == BBOutputOffset)
62       continue;
63 
64     LLVM_DEBUG(dbgs() << "  Key: " << Twine::utohexstr(OutputOffset) << " Val: "
65                       << Twine::utohexstr(InputOffset) << " (branch)\n");
66     Map.insert(std::pair<uint32_t, uint32_t>(OutputOffset,
67                                              (InputOffset << 1) | BRANCHENTRY));
68   }
69 }
70 
71 void BoltAddressTranslation::write(const BinaryContext &BC, raw_ostream &OS) {
72   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Writing BOLT Address Translation Tables\n");
73   for (auto &BFI : BC.getBinaryFunctions()) {
74     const BinaryFunction &Function = BFI.second;
75     // We don't need a translation table if the body of the function hasn't
76     // changed
77     if (Function.isIgnored() || (!BC.HasRelocations && !Function.isSimple()))
78       continue;
79 
80     LLVM_DEBUG(dbgs() << "Function name: " << Function.getPrintName() << "\n");
81     LLVM_DEBUG(dbgs() << " Address reference: 0x"
82                       << Twine::utohexstr(Function.getOutputAddress()) << "\n");
83 
84     MapTy Map;
85     for (const BinaryBasicBlock *const BB :
86          Function.getLayout().getMainFragment())
87       writeEntriesForBB(Map, *BB, Function.getOutputAddress());
88     Maps.emplace(Function.getOutputAddress(), std::move(Map));
89 
90     if (!Function.isSplit())
91       continue;
92 
93     // Split maps
94     LLVM_DEBUG(dbgs() << " Cold part\n");
95     for (const FunctionFragment &FF :
96          Function.getLayout().getSplitFragments()) {
97       Map.clear();
98       for (const BinaryBasicBlock *const BB : FF)
99         writeEntriesForBB(Map, *BB, FF.getAddress());
100 
101       Maps.emplace(FF.getAddress(), std::move(Map));
102       ColdPartSource.emplace(FF.getAddress(), Function.getOutputAddress());
103     }
104   }
105 
106   const uint32_t NumFuncs = Maps.size();
107   encodeULEB128(NumFuncs, OS);
108   LLVM_DEBUG(dbgs() << "Writing " << NumFuncs << " functions for BAT.\n");
109   for (auto &MapEntry : Maps) {
110     const uint64_t Address = MapEntry.first;
111     MapTy &Map = MapEntry.second;
112     const uint32_t NumEntries = Map.size();
113     LLVM_DEBUG(dbgs() << "Writing " << NumEntries << " entries for 0x"
114                       << Twine::utohexstr(Address) << ".\n");
115     encodeULEB128(Address, OS);
116     encodeULEB128(NumEntries, OS);
117     for (std::pair<const uint32_t, uint32_t> &KeyVal : Map) {
118       encodeULEB128(KeyVal.first, OS);
119       encodeULEB128(KeyVal.second, OS);
120     }
121   }
122   const uint32_t NumColdEntries = ColdPartSource.size();
123   LLVM_DEBUG(dbgs() << "Writing " << NumColdEntries
124                     << " cold part mappings.\n");
125   encodeULEB128(NumColdEntries, OS);
126   for (std::pair<const uint64_t, uint64_t> &ColdEntry : ColdPartSource) {
127     encodeULEB128(ColdEntry.first, OS);
128     encodeULEB128(ColdEntry.second, OS);
129     LLVM_DEBUG(dbgs() << " " << Twine::utohexstr(ColdEntry.first) << " -> "
130                       << Twine::utohexstr(ColdEntry.second) << "\n");
131   }
132 
133   outs() << "BOLT-INFO: Wrote " << Maps.size() << " BAT maps\n";
134   outs() << "BOLT-INFO: Wrote " << NumColdEntries
135          << " BAT cold-to-hot entries\n";
136 }
137 
138 std::error_code BoltAddressTranslation::parse(StringRef Buf) {
139   DataExtractor DE = DataExtractor(Buf, true, 8);
140   uint64_t Offset = 0;
141   if (Buf.size() < 12)
142     return make_error_code(llvm::errc::io_error);
143 
144   const uint32_t NameSz = DE.getU32(&Offset);
145   const uint32_t DescSz = DE.getU32(&Offset);
146   const uint32_t Type = DE.getU32(&Offset);
147 
148   if (Type != BinarySection::NT_BOLT_BAT ||
149       Buf.size() + Offset < alignTo(NameSz, 4) + DescSz)
150     return make_error_code(llvm::errc::io_error);
151 
152   StringRef Name = Buf.slice(Offset, Offset + NameSz);
153   Offset = alignTo(Offset + NameSz, 4);
154   if (Name.substr(0, 4) != "BOLT")
155     return make_error_code(llvm::errc::io_error);
156 
157   Error Err(Error::success());
158   const uint32_t NumFunctions = DE.getULEB128(&Offset, &Err);
159   LLVM_DEBUG(dbgs() << "Parsing " << NumFunctions << " functions\n");
160   for (uint32_t I = 0; I < NumFunctions; ++I) {
161     const uint64_t Address = DE.getULEB128(&Offset, &Err);
162     const uint32_t NumEntries = DE.getULEB128(&Offset, &Err);
163     MapTy Map;
164 
165     LLVM_DEBUG(dbgs() << "Parsing " << NumEntries << " entries for 0x"
166                       << Twine::utohexstr(Address) << "\n");
167     for (uint32_t J = 0; J < NumEntries; ++J) {
168       const uint32_t OutputAddr = DE.getULEB128(&Offset, &Err);
169       const uint32_t InputAddr = DE.getULEB128(&Offset, &Err);
170       Map.insert(std::pair<uint32_t, uint32_t>(OutputAddr, InputAddr));
171       LLVM_DEBUG(dbgs() << Twine::utohexstr(OutputAddr) << " -> "
172                         << Twine::utohexstr(InputAddr) << "\n");
173     }
174     Maps.insert(std::pair<uint64_t, MapTy>(Address, Map));
175   }
176 
177   const uint32_t NumColdEntries = DE.getULEB128(&Offset, &Err);
178   LLVM_DEBUG(dbgs() << "Parsing " << NumColdEntries << " cold part mappings\n");
179   for (uint32_t I = 0; I < NumColdEntries; ++I) {
180     const uint32_t ColdAddress = DE.getULEB128(&Offset, &Err);
181     const uint32_t HotAddress = DE.getULEB128(&Offset, &Err);
182     ColdPartSource.insert(
183         std::pair<uint64_t, uint64_t>(ColdAddress, HotAddress));
184     LLVM_DEBUG(dbgs() << Twine::utohexstr(ColdAddress) << " -> "
185                       << Twine::utohexstr(HotAddress) << "\n");
186   }
187   outs() << "BOLT-INFO: Parsed " << Maps.size() << " BAT entries\n";
188   outs() << "BOLT-INFO: Parsed " << NumColdEntries
189          << " BAT cold-to-hot entries\n";
190 
191   return errorToErrorCode(std::move(Err));
192 }
193 
194 void BoltAddressTranslation::dump(raw_ostream &OS) {
195   const size_t NumTables = Maps.size();
196   OS << "BAT tables for " << NumTables << " functions:\n";
197   for (const auto &MapEntry : Maps) {
198     OS << "Function Address: 0x" << Twine::utohexstr(MapEntry.first) << "\n";
199     OS << "BB mappings:\n";
200     for (const auto &Entry : MapEntry.second) {
201       const bool IsBranch = Entry.second & BRANCHENTRY;
202       const uint32_t Val = Entry.second >> 1; // dropping BRANCHENTRY bit
203       OS << "0x" << Twine::utohexstr(Entry.first) << " -> "
204          << "0x" << Twine::utohexstr(Val);
205       if (IsBranch)
206         OS << " (branch)";
207       OS << "\n";
208     }
209     OS << "\n";
210   }
211   const size_t NumColdParts = ColdPartSource.size();
212   if (!NumColdParts)
213     return;
214 
215   OS << NumColdParts << " cold mappings:\n";
216   for (const auto &Entry : ColdPartSource) {
217     OS << "0x" << Twine::utohexstr(Entry.first) << " -> "
218        << Twine::utohexstr(Entry.second) << "\n";
219   }
220   OS << "\n";
221 }
222 
223 uint64_t BoltAddressTranslation::translate(uint64_t FuncAddress,
224                                            uint64_t Offset,
225                                            bool IsBranchSrc) const {
226   auto Iter = Maps.find(FuncAddress);
227   if (Iter == Maps.end())
228     return Offset;
229 
230   const MapTy &Map = Iter->second;
231   auto KeyVal = Map.upper_bound(Offset);
232   if (KeyVal == Map.begin())
233     return Offset;
234 
235   --KeyVal;
236 
237   const uint32_t Val = KeyVal->second >> 1; // dropping BRANCHENTRY bit
238   // Branch source addresses are translated to the first instruction of the
239   // source BB to avoid accounting for modifications BOLT may have made in the
240   // BB regarding deletion/addition of instructions.
241   if (IsBranchSrc)
242     return Val;
243   return Offset - KeyVal->first + Val;
244 }
245 
246 std::optional<BoltAddressTranslation::FallthroughListTy>
247 BoltAddressTranslation::getFallthroughsInTrace(uint64_t FuncAddress,
248                                                uint64_t From,
249                                                uint64_t To) const {
250   SmallVector<std::pair<uint64_t, uint64_t>, 16> Res;
251 
252   // Filter out trivial case
253   if (From >= To)
254     return Res;
255 
256   From -= FuncAddress;
257   To -= FuncAddress;
258 
259   auto Iter = Maps.find(FuncAddress);
260   if (Iter == Maps.end())
261     return std::nullopt;
262 
263   const MapTy &Map = Iter->second;
264   auto FromIter = Map.upper_bound(From);
265   if (FromIter == Map.begin())
266     return Res;
267   // Skip instruction entries, to create fallthroughs we are only interested in
268   // BB boundaries
269   do {
270     if (FromIter == Map.begin())
271       return Res;
272     --FromIter;
273   } while (FromIter->second & BRANCHENTRY);
274 
275   auto ToIter = Map.upper_bound(To);
276   if (ToIter == Map.begin())
277     return Res;
278   --ToIter;
279   if (FromIter->first >= ToIter->first)
280     return Res;
281 
282   for (auto Iter = FromIter; Iter != ToIter;) {
283     const uint32_t Src = Iter->first;
284     if (Iter->second & BRANCHENTRY) {
285       ++Iter;
286       continue;
287     }
288 
289     ++Iter;
290     while (Iter->second & BRANCHENTRY && Iter != ToIter)
291       ++Iter;
292     if (Iter->second & BRANCHENTRY)
293       break;
294     Res.emplace_back(Src, Iter->first);
295   }
296 
297   return Res;
298 }
299 
300 uint64_t BoltAddressTranslation::fetchParentAddress(uint64_t Address) const {
301   auto Iter = ColdPartSource.find(Address);
302   if (Iter == ColdPartSource.end())
303     return 0;
304   return Iter->second;
305 }
306 
307 bool BoltAddressTranslation::enabledFor(
308     llvm::object::ELFObjectFileBase *InputFile) const {
309   for (const SectionRef &Section : InputFile->sections()) {
310     Expected<StringRef> SectionNameOrErr = Section.getName();
311     if (Error E = SectionNameOrErr.takeError())
312       continue;
313 
314     if (SectionNameOrErr.get() == SECTION_NAME)
315       return true;
316   }
317   return false;
318 }
319 } // namespace bolt
320 } // namespace llvm
321