xref: /llvm-project/bolt/lib/Profile/BoltAddressTranslation.cpp (revision 6304e38281d7f0546a6468dba7415ef52496e4c0)
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 
14 #define DEBUG_TYPE "bolt-bat"
15 
16 namespace llvm {
17 namespace bolt {
18 
19 const char *BoltAddressTranslation::SECTION_NAME = ".note.bolt_bat";
20 
21 void BoltAddressTranslation::writeEntriesForBB(MapTy &Map,
22                                                const BinaryBasicBlock &BB,
23                                                uint64_t FuncAddress) {
24   const uint64_t BBOutputOffset =
25       BB.getOutputAddressRange().first - FuncAddress;
26   const uint32_t BBInputOffset = BB.getInputOffset();
27 
28   // Every output BB must track back to an input BB for profile collection
29   // in bolted binaries. If we are missing an offset, it means this block was
30   // created by a pass. We will skip writing any entries for it, and this means
31   // any traffic happening in this block will map to the previous block in the
32   // layout. This covers the case where an input basic block is split into two,
33   // and the second one lacks any offset.
34   if (BBInputOffset == BinaryBasicBlock::INVALID_OFFSET)
35     return;
36 
37   LLVM_DEBUG(dbgs() << "BB " << BB.getName() << "\n");
38   LLVM_DEBUG(dbgs() << "  Key: " << Twine::utohexstr(BBOutputOffset)
39                     << " Val: " << Twine::utohexstr(BBInputOffset) << "\n");
40   // In case of conflicts (same Key mapping to different Vals), the last
41   // update takes precedence. Of course it is not ideal to have conflicts and
42   // those happen when we have an empty BB that either contained only
43   // NOPs or a jump to the next block (successor). Either way, the successor
44   // and this deleted block will both share the same output address (the same
45   // key), and we need to map back. We choose here to privilege the successor by
46   // allowing it to overwrite the previously inserted key in the map.
47   Map[BBOutputOffset] = BBInputOffset;
48 
49   for (const auto &IOPair : BB.getOffsetTranslationTable()) {
50     const uint64_t OutputOffset = IOPair.first + BBOutputOffset;
51     const uint32_t InputOffset = IOPair.second;
52 
53     // Is this the first instruction in the BB? No need to duplicate the entry.
54     if (OutputOffset == BBOutputOffset)
55       continue;
56 
57     LLVM_DEBUG(dbgs() << "  Key: " << Twine::utohexstr(OutputOffset) << " Val: "
58                       << Twine::utohexstr(InputOffset) << " (branch)\n");
59     Map.insert(
60         std::pair<uint32_t, uint32_t>(OutputOffset, InputOffset | BRANCHENTRY));
61   }
62 }
63 
64 void BoltAddressTranslation::write(const BinaryContext &BC, raw_ostream &OS) {
65   LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Writing BOLT Address Translation Tables\n");
66   for (auto &BFI : BC.getBinaryFunctions()) {
67     const BinaryFunction &Function = BFI.second;
68     // We don't need a translation table if the body of the function hasn't
69     // changed
70     if (Function.isIgnored() || (!BC.HasRelocations && !Function.isSimple()))
71       continue;
72 
73     LLVM_DEBUG(dbgs() << "Function name: " << Function.getPrintName() << "\n");
74     LLVM_DEBUG(dbgs() << " Address reference: 0x"
75                       << Twine::utohexstr(Function.getOutputAddress()) << "\n");
76     MapTy Map;
77     const bool IsSplit = Function.isSplit();
78     for (const BinaryBasicBlock *const BB : Function.getLayout().blocks()) {
79       if (IsSplit && BB->isCold())
80         break;
81       writeEntriesForBB(Map, *BB, Function.getOutputAddress());
82     }
83     Maps.insert(std::pair<uint64_t, MapTy>(Function.getOutputAddress(), Map));
84 
85     if (!IsSplit)
86       continue;
87 
88     // Cold map
89     Map.clear();
90     LLVM_DEBUG(dbgs() << " Cold part\n");
91     for (const BinaryBasicBlock *const BB : Function.getLayout().blocks()) {
92       if (!BB->isCold())
93         continue;
94       writeEntriesForBB(Map, *BB, Function.cold().getAddress());
95     }
96     Maps.insert(std::pair<uint64_t, MapTy>(Function.cold().getAddress(), Map));
97     ColdPartSource.insert(std::pair<uint64_t, uint64_t>(
98         Function.cold().getAddress(), Function.getOutputAddress()));
99   }
100 
101   const uint32_t NumFuncs = Maps.size();
102   OS.write(reinterpret_cast<const char *>(&NumFuncs), 4);
103   LLVM_DEBUG(dbgs() << "Writing " << NumFuncs << " functions for BAT.\n");
104   for (auto &MapEntry : Maps) {
105     const uint64_t Address = MapEntry.first;
106     MapTy &Map = MapEntry.second;
107     const uint32_t NumEntries = Map.size();
108     LLVM_DEBUG(dbgs() << "Writing " << NumEntries << " entries for 0x"
109                       << Twine::utohexstr(Address) << ".\n");
110     OS.write(reinterpret_cast<const char *>(&Address), 8);
111     OS.write(reinterpret_cast<const char *>(&NumEntries), 4);
112     for (std::pair<const uint32_t, uint32_t> &KeyVal : Map) {
113       OS.write(reinterpret_cast<const char *>(&KeyVal.first), 4);
114       OS.write(reinterpret_cast<const char *>(&KeyVal.second), 4);
115     }
116   }
117   const uint32_t NumColdEntries = ColdPartSource.size();
118   LLVM_DEBUG(dbgs() << "Writing " << NumColdEntries
119                     << " cold part mappings.\n");
120   OS.write(reinterpret_cast<const char *>(&NumColdEntries), 4);
121   for (std::pair<const uint64_t, uint64_t> &ColdEntry : ColdPartSource) {
122     OS.write(reinterpret_cast<const char *>(&ColdEntry.first), 8);
123     OS.write(reinterpret_cast<const char *>(&ColdEntry.second), 8);
124     LLVM_DEBUG(dbgs() << " " << Twine::utohexstr(ColdEntry.first) << " -> "
125                       << Twine::utohexstr(ColdEntry.second) << "\n");
126   }
127 
128   outs() << "BOLT-INFO: Wrote " << Maps.size() << " BAT maps\n";
129   outs() << "BOLT-INFO: Wrote " << NumColdEntries
130          << " BAT cold-to-hot entries\n";
131 }
132 
133 std::error_code BoltAddressTranslation::parse(StringRef Buf) {
134   DataExtractor DE = DataExtractor(Buf, true, 8);
135   uint64_t Offset = 0;
136   if (Buf.size() < 12)
137     return make_error_code(llvm::errc::io_error);
138 
139   const uint32_t NameSz = DE.getU32(&Offset);
140   const uint32_t DescSz = DE.getU32(&Offset);
141   const uint32_t Type = DE.getU32(&Offset);
142 
143   if (Type != BinarySection::NT_BOLT_BAT ||
144       Buf.size() + Offset < alignTo(NameSz, 4) + DescSz)
145     return make_error_code(llvm::errc::io_error);
146 
147   StringRef Name = Buf.slice(Offset, Offset + NameSz);
148   Offset = alignTo(Offset + NameSz, 4);
149   if (Name.substr(0, 4) != "BOLT")
150     return make_error_code(llvm::errc::io_error);
151 
152   if (Buf.size() - Offset < 4)
153     return make_error_code(llvm::errc::io_error);
154 
155   const uint32_t NumFunctions = DE.getU32(&Offset);
156   LLVM_DEBUG(dbgs() << "Parsing " << NumFunctions << " functions\n");
157   for (uint32_t I = 0; I < NumFunctions; ++I) {
158     if (Buf.size() - Offset < 12)
159       return make_error_code(llvm::errc::io_error);
160 
161     const uint64_t Address = DE.getU64(&Offset);
162     const uint32_t NumEntries = DE.getU32(&Offset);
163     MapTy Map;
164 
165     LLVM_DEBUG(dbgs() << "Parsing " << NumEntries << " entries for 0x"
166                       << Twine::utohexstr(Address) << "\n");
167     if (Buf.size() - Offset < 8 * NumEntries)
168       return make_error_code(llvm::errc::io_error);
169     for (uint32_t J = 0; J < NumEntries; ++J) {
170       const uint32_t OutputAddr = DE.getU32(&Offset);
171       const uint32_t InputAddr = DE.getU32(&Offset);
172       Map.insert(std::pair<uint32_t, uint32_t>(OutputAddr, InputAddr));
173       LLVM_DEBUG(dbgs() << Twine::utohexstr(OutputAddr) << " -> "
174                         << Twine::utohexstr(InputAddr) << "\n");
175     }
176     Maps.insert(std::pair<uint64_t, MapTy>(Address, Map));
177   }
178 
179   if (Buf.size() - Offset < 4)
180     return make_error_code(llvm::errc::io_error);
181 
182   const uint32_t NumColdEntries = DE.getU32(&Offset);
183   LLVM_DEBUG(dbgs() << "Parsing " << NumColdEntries << " cold part mappings\n");
184   for (uint32_t I = 0; I < NumColdEntries; ++I) {
185     if (Buf.size() - Offset < 16)
186       return make_error_code(llvm::errc::io_error);
187     const uint32_t ColdAddress = DE.getU64(&Offset);
188     const uint32_t HotAddress = DE.getU64(&Offset);
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 std::error_code();
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 & ~BRANCHENTRY;
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 & ~BRANCHENTRY;
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 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 NoneType();
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