xref: /llvm-project/bolt/lib/Profile/BoltAddressTranslation.cpp (revision bbe07989d7225aaff9613b71dbd7f00e8d738b22)
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     uint64_t InOffset = 0, OutOffset = 0;
118     // Output and Input addresses and delta-encoded
119     for (std::pair<const uint32_t, uint32_t> &KeyVal : Map) {
120       encodeULEB128(KeyVal.first - OutOffset, OS);
121       encodeSLEB128(KeyVal.second - InOffset, OS);
122       std::tie(OutOffset, InOffset) = KeyVal;
123     }
124   }
125   const uint32_t NumColdEntries = ColdPartSource.size();
126   LLVM_DEBUG(dbgs() << "Writing " << NumColdEntries
127                     << " cold part mappings.\n");
128   encodeULEB128(NumColdEntries, OS);
129   for (std::pair<const uint64_t, uint64_t> &ColdEntry : ColdPartSource) {
130     encodeULEB128(ColdEntry.first, OS);
131     encodeULEB128(ColdEntry.second, OS);
132     LLVM_DEBUG(dbgs() << " " << Twine::utohexstr(ColdEntry.first) << " -> "
133                       << Twine::utohexstr(ColdEntry.second) << "\n");
134   }
135 
136   outs() << "BOLT-INFO: Wrote " << Maps.size() << " BAT maps\n";
137   outs() << "BOLT-INFO: Wrote " << NumColdEntries
138          << " BAT cold-to-hot entries\n";
139 }
140 
141 std::error_code BoltAddressTranslation::parse(StringRef Buf) {
142   DataExtractor DE = DataExtractor(Buf, true, 8);
143   uint64_t Offset = 0;
144   if (Buf.size() < 12)
145     return make_error_code(llvm::errc::io_error);
146 
147   const uint32_t NameSz = DE.getU32(&Offset);
148   const uint32_t DescSz = DE.getU32(&Offset);
149   const uint32_t Type = DE.getU32(&Offset);
150 
151   if (Type != BinarySection::NT_BOLT_BAT ||
152       Buf.size() + Offset < alignTo(NameSz, 4) + DescSz)
153     return make_error_code(llvm::errc::io_error);
154 
155   StringRef Name = Buf.slice(Offset, Offset + NameSz);
156   Offset = alignTo(Offset + NameSz, 4);
157   if (Name.substr(0, 4) != "BOLT")
158     return make_error_code(llvm::errc::io_error);
159 
160   Error Err(Error::success());
161   const uint32_t NumFunctions = DE.getULEB128(&Offset, &Err);
162   LLVM_DEBUG(dbgs() << "Parsing " << NumFunctions << " functions\n");
163   for (uint32_t I = 0; I < NumFunctions; ++I) {
164     const uint64_t Address = DE.getULEB128(&Offset, &Err);
165     const uint32_t NumEntries = DE.getULEB128(&Offset, &Err);
166     MapTy Map;
167 
168     LLVM_DEBUG(dbgs() << "Parsing " << NumEntries << " entries for 0x"
169                       << Twine::utohexstr(Address) << "\n");
170     uint64_t InputOffset = 0, OutputOffset = 0;
171     for (uint32_t J = 0; J < NumEntries; ++J) {
172       const uint64_t OutputDelta = DE.getULEB128(&Offset, &Err);
173       const int64_t InputDelta = DE.getSLEB128(&Offset, &Err);
174       OutputOffset += OutputDelta;
175       InputOffset += InputDelta;
176       Map.insert(std::pair<uint32_t, uint32_t>(OutputOffset, InputOffset));
177       LLVM_DEBUG(dbgs() << Twine::utohexstr(OutputOffset) << " -> "
178                         << Twine::utohexstr(InputOffset) << " (" << OutputDelta
179                         << ", " << InputDelta << ")\n");
180     }
181     Maps.insert(std::pair<uint64_t, MapTy>(Address, Map));
182   }
183 
184   const uint32_t NumColdEntries = DE.getULEB128(&Offset, &Err);
185   LLVM_DEBUG(dbgs() << "Parsing " << NumColdEntries << " cold part mappings\n");
186   for (uint32_t I = 0; I < NumColdEntries; ++I) {
187     const uint32_t ColdAddress = DE.getULEB128(&Offset, &Err);
188     const uint32_t HotAddress = DE.getULEB128(&Offset, &Err);
189     ColdPartSource.insert(
190         std::pair<uint64_t, uint64_t>(ColdAddress, HotAddress));
191     LLVM_DEBUG(dbgs() << Twine::utohexstr(ColdAddress) << " -> "
192                       << Twine::utohexstr(HotAddress) << "\n");
193   }
194   outs() << "BOLT-INFO: Parsed " << Maps.size() << " BAT entries\n";
195   outs() << "BOLT-INFO: Parsed " << NumColdEntries
196          << " BAT cold-to-hot entries\n";
197 
198   return errorToErrorCode(std::move(Err));
199 }
200 
201 void BoltAddressTranslation::dump(raw_ostream &OS) {
202   const size_t NumTables = Maps.size();
203   OS << "BAT tables for " << NumTables << " functions:\n";
204   for (const auto &MapEntry : Maps) {
205     OS << "Function Address: 0x" << Twine::utohexstr(MapEntry.first) << "\n";
206     OS << "BB mappings:\n";
207     for (const auto &Entry : MapEntry.second) {
208       const bool IsBranch = Entry.second & BRANCHENTRY;
209       const uint32_t Val = Entry.second >> 1; // dropping BRANCHENTRY bit
210       OS << "0x" << Twine::utohexstr(Entry.first) << " -> "
211          << "0x" << Twine::utohexstr(Val);
212       if (IsBranch)
213         OS << " (branch)";
214       OS << "\n";
215     }
216     OS << "\n";
217   }
218   const size_t NumColdParts = ColdPartSource.size();
219   if (!NumColdParts)
220     return;
221 
222   OS << NumColdParts << " cold mappings:\n";
223   for (const auto &Entry : ColdPartSource) {
224     OS << "0x" << Twine::utohexstr(Entry.first) << " -> "
225        << Twine::utohexstr(Entry.second) << "\n";
226   }
227   OS << "\n";
228 }
229 
230 uint64_t BoltAddressTranslation::translate(uint64_t FuncAddress,
231                                            uint64_t Offset,
232                                            bool IsBranchSrc) const {
233   auto Iter = Maps.find(FuncAddress);
234   if (Iter == Maps.end())
235     return Offset;
236 
237   const MapTy &Map = Iter->second;
238   auto KeyVal = Map.upper_bound(Offset);
239   if (KeyVal == Map.begin())
240     return Offset;
241 
242   --KeyVal;
243 
244   const uint32_t Val = KeyVal->second >> 1; // dropping BRANCHENTRY bit
245   // Branch source addresses are translated to the first instruction of the
246   // source BB to avoid accounting for modifications BOLT may have made in the
247   // BB regarding deletion/addition of instructions.
248   if (IsBranchSrc)
249     return Val;
250   return Offset - KeyVal->first + Val;
251 }
252 
253 std::optional<BoltAddressTranslation::FallthroughListTy>
254 BoltAddressTranslation::getFallthroughsInTrace(uint64_t FuncAddress,
255                                                uint64_t From,
256                                                uint64_t To) const {
257   SmallVector<std::pair<uint64_t, uint64_t>, 16> Res;
258 
259   // Filter out trivial case
260   if (From >= To)
261     return Res;
262 
263   From -= FuncAddress;
264   To -= FuncAddress;
265 
266   auto Iter = Maps.find(FuncAddress);
267   if (Iter == Maps.end())
268     return std::nullopt;
269 
270   const MapTy &Map = Iter->second;
271   auto FromIter = Map.upper_bound(From);
272   if (FromIter == Map.begin())
273     return Res;
274   // Skip instruction entries, to create fallthroughs we are only interested in
275   // BB boundaries
276   do {
277     if (FromIter == Map.begin())
278       return Res;
279     --FromIter;
280   } while (FromIter->second & BRANCHENTRY);
281 
282   auto ToIter = Map.upper_bound(To);
283   if (ToIter == Map.begin())
284     return Res;
285   --ToIter;
286   if (FromIter->first >= ToIter->first)
287     return Res;
288 
289   for (auto Iter = FromIter; Iter != ToIter;) {
290     const uint32_t Src = Iter->first;
291     if (Iter->second & BRANCHENTRY) {
292       ++Iter;
293       continue;
294     }
295 
296     ++Iter;
297     while (Iter->second & BRANCHENTRY && Iter != ToIter)
298       ++Iter;
299     if (Iter->second & BRANCHENTRY)
300       break;
301     Res.emplace_back(Src, Iter->first);
302   }
303 
304   return Res;
305 }
306 
307 uint64_t BoltAddressTranslation::fetchParentAddress(uint64_t Address) const {
308   auto Iter = ColdPartSource.find(Address);
309   if (Iter == ColdPartSource.end())
310     return 0;
311   return Iter->second;
312 }
313 
314 bool BoltAddressTranslation::enabledFor(
315     llvm::object::ELFObjectFileBase *InputFile) const {
316   for (const SectionRef &Section : InputFile->sections()) {
317     Expected<StringRef> SectionNameOrErr = Section.getName();
318     if (Error E = SectionNameOrErr.takeError())
319       continue;
320 
321     if (SectionNameOrErr.get() == SECTION_NAME)
322       return true;
323   }
324   return false;
325 }
326 } // namespace bolt
327 } // namespace llvm
328