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/Errc.h" 12 #include "llvm/Support/Error.h" 13 #include "llvm/Support/LEB128.h" 14 15 #define DEBUG_TYPE "bolt-bat" 16 17 namespace llvm { 18 namespace bolt { 19 20 const char *BoltAddressTranslation::SECTION_NAME = ".note.bolt_bat"; 21 22 void BoltAddressTranslation::writeEntriesForBB(MapTy &Map, 23 const BinaryBasicBlock &BB, 24 uint64_t FuncAddress) { 25 const uint64_t BBOutputOffset = 26 BB.getOutputAddressRange().first - FuncAddress; 27 const uint32_t BBInputOffset = BB.getInputOffset(); 28 29 // Every output BB must track back to an input BB for profile collection 30 // in bolted binaries. If we are missing an offset, it means this block was 31 // created by a pass. We will skip writing any entries for it, and this means 32 // any traffic happening in this block will map to the previous block in the 33 // layout. This covers the case where an input basic block is split into two, 34 // and the second one lacks any offset. 35 if (BBInputOffset == BinaryBasicBlock::INVALID_OFFSET) 36 return; 37 38 LLVM_DEBUG(dbgs() << "BB " << BB.getName() << "\n"); 39 LLVM_DEBUG(dbgs() << " Key: " << Twine::utohexstr(BBOutputOffset) 40 << " Val: " << Twine::utohexstr(BBInputOffset) << "\n"); 41 // In case of conflicts (same Key mapping to different Vals), the last 42 // update takes precedence. Of course it is not ideal to have conflicts and 43 // those happen when we have an empty BB that either contained only 44 // NOPs or a jump to the next block (successor). Either way, the successor 45 // and this deleted block will both share the same output address (the same 46 // key), and we need to map back. We choose here to privilege the successor by 47 // allowing it to overwrite the previously inserted key in the map. 48 Map[BBOutputOffset] = BBInputOffset << 1; 49 50 const auto &IOAddressMap = 51 BB.getFunction()->getBinaryContext().getIOAddressMap(); 52 53 for (const auto &[InputOffset, Sym] : BB.getLocSyms()) { 54 const auto InputAddress = BB.getFunction()->getAddress() + InputOffset; 55 const auto OutputAddress = IOAddressMap.lookup(InputAddress); 56 assert(OutputAddress && "Unknown instruction address"); 57 const auto OutputOffset = *OutputAddress - FuncAddress; 58 59 // Is this the first instruction in the BB? No need to duplicate the entry. 60 if (OutputOffset == BBOutputOffset) 61 continue; 62 63 LLVM_DEBUG(dbgs() << " Key: " << Twine::utohexstr(OutputOffset) << " Val: " 64 << Twine::utohexstr(InputOffset) << " (branch)\n"); 65 Map.insert(std::pair<uint32_t, uint32_t>(OutputOffset, 66 (InputOffset << 1) | BRANCHENTRY)); 67 } 68 } 69 70 void BoltAddressTranslation::write(const BinaryContext &BC, raw_ostream &OS) { 71 LLVM_DEBUG(dbgs() << "BOLT-DEBUG: Writing BOLT Address Translation Tables\n"); 72 for (auto &BFI : BC.getBinaryFunctions()) { 73 const BinaryFunction &Function = BFI.second; 74 // We don't need a translation table if the body of the function hasn't 75 // changed 76 if (Function.isIgnored() || (!BC.HasRelocations && !Function.isSimple())) 77 continue; 78 79 LLVM_DEBUG(dbgs() << "Function name: " << Function.getPrintName() << "\n"); 80 LLVM_DEBUG(dbgs() << " Address reference: 0x" 81 << Twine::utohexstr(Function.getOutputAddress()) << "\n"); 82 83 MapTy Map; 84 for (const BinaryBasicBlock *const BB : 85 Function.getLayout().getMainFragment()) 86 writeEntriesForBB(Map, *BB, Function.getOutputAddress()); 87 Maps.emplace(Function.getOutputAddress(), std::move(Map)); 88 89 if (!Function.isSplit()) 90 continue; 91 92 // Split maps 93 LLVM_DEBUG(dbgs() << " Cold part\n"); 94 for (const FunctionFragment &FF : 95 Function.getLayout().getSplitFragments()) { 96 Map.clear(); 97 for (const BinaryBasicBlock *const BB : FF) 98 writeEntriesForBB(Map, *BB, FF.getAddress()); 99 100 Maps.emplace(FF.getAddress(), std::move(Map)); 101 ColdPartSource.emplace(FF.getAddress(), Function.getOutputAddress()); 102 } 103 } 104 105 writeMaps</*Cold=*/false>(Maps, OS); 106 writeMaps</*Cold=*/true>(Maps, OS); 107 108 outs() << "BOLT-INFO: Wrote " << Maps.size() << " BAT maps\n"; 109 } 110 111 template <bool Cold> 112 void BoltAddressTranslation::writeMaps(std::map<uint64_t, MapTy> &Maps, 113 raw_ostream &OS) { 114 const uint32_t NumFuncs = 115 llvm::count_if(llvm::make_first_range(Maps), [&](const uint64_t Address) { 116 return Cold == ColdPartSource.count(Address); 117 }); 118 encodeULEB128(NumFuncs, OS); 119 LLVM_DEBUG(dbgs() << "Writing " << NumFuncs << (Cold ? " cold" : "") 120 << " functions for BAT.\n"); 121 size_t PrevIndex = 0; 122 // Output addresses are delta-encoded 123 uint64_t PrevAddress = 0; 124 for (auto &MapEntry : Maps) { 125 const uint64_t Address = MapEntry.first; 126 // Only process cold fragments in cold mode, and vice versa. 127 if (Cold != ColdPartSource.count(Address)) 128 continue; 129 MapTy &Map = MapEntry.second; 130 const uint32_t NumEntries = Map.size(); 131 LLVM_DEBUG(dbgs() << "Writing " << NumEntries << " entries for 0x" 132 << Twine::utohexstr(Address) << ".\n"); 133 encodeULEB128(Address - PrevAddress, OS); 134 PrevAddress = Address; 135 if (Cold) { 136 size_t HotIndex = 137 std::distance(ColdPartSource.begin(), ColdPartSource.find(Address)); 138 encodeULEB128(HotIndex - PrevIndex, OS); 139 PrevIndex = HotIndex; 140 } 141 encodeULEB128(NumEntries, OS); 142 uint64_t InOffset = 0, OutOffset = 0; 143 // Output and Input addresses and delta-encoded 144 for (std::pair<const uint32_t, uint32_t> &KeyVal : Map) { 145 encodeULEB128(KeyVal.first - OutOffset, OS); 146 encodeSLEB128(KeyVal.second - InOffset, OS); 147 std::tie(OutOffset, InOffset) = KeyVal; 148 } 149 } 150 } 151 152 std::error_code BoltAddressTranslation::parse(StringRef Buf) { 153 DataExtractor DE = DataExtractor(Buf, true, 8); 154 uint64_t Offset = 0; 155 if (Buf.size() < 12) 156 return make_error_code(llvm::errc::io_error); 157 158 const uint32_t NameSz = DE.getU32(&Offset); 159 const uint32_t DescSz = DE.getU32(&Offset); 160 const uint32_t Type = DE.getU32(&Offset); 161 162 if (Type != BinarySection::NT_BOLT_BAT || 163 Buf.size() + Offset < alignTo(NameSz, 4) + DescSz) 164 return make_error_code(llvm::errc::io_error); 165 166 StringRef Name = Buf.slice(Offset, Offset + NameSz); 167 Offset = alignTo(Offset + NameSz, 4); 168 if (Name.substr(0, 4) != "BOLT") 169 return make_error_code(llvm::errc::io_error); 170 171 Error Err(Error::success()); 172 std::vector<uint64_t> HotFuncs; 173 parseMaps</*Cold=*/false>(HotFuncs, DE, Offset, Err); 174 parseMaps</*Cold=*/true>(HotFuncs, DE, Offset, Err); 175 outs() << "BOLT-INFO: Parsed " << Maps.size() << " BAT entries\n"; 176 return errorToErrorCode(std::move(Err)); 177 } 178 179 template <bool Cold> 180 void BoltAddressTranslation::parseMaps(std::vector<uint64_t> &HotFuncs, 181 DataExtractor &DE, uint64_t &Offset, 182 Error &Err) { 183 const uint32_t NumFunctions = DE.getULEB128(&Offset, &Err); 184 LLVM_DEBUG(dbgs() << "Parsing " << NumFunctions << (Cold ? " cold" : "") 185 << " functions\n"); 186 size_t HotIndex = 0; 187 uint64_t PrevAddress = 0; 188 for (uint32_t I = 0; I < NumFunctions; ++I) { 189 const uint64_t Address = PrevAddress + DE.getULEB128(&Offset, &Err); 190 PrevAddress = Address; 191 if (Cold) { 192 HotIndex += DE.getULEB128(&Offset, &Err); 193 ColdPartSource.emplace(Address, HotFuncs[HotIndex]); 194 } else { 195 HotFuncs.push_back(Address); 196 } 197 const uint32_t NumEntries = DE.getULEB128(&Offset, &Err); 198 MapTy Map; 199 200 LLVM_DEBUG(dbgs() << "Parsing " << NumEntries << " entries for 0x" 201 << Twine::utohexstr(Address) << "\n"); 202 uint64_t InputOffset = 0, OutputOffset = 0; 203 for (uint32_t J = 0; J < NumEntries; ++J) { 204 const uint64_t OutputDelta = DE.getULEB128(&Offset, &Err); 205 const int64_t InputDelta = DE.getSLEB128(&Offset, &Err); 206 OutputOffset += OutputDelta; 207 InputOffset += InputDelta; 208 Map.insert(std::pair<uint32_t, uint32_t>(OutputOffset, InputOffset)); 209 LLVM_DEBUG(dbgs() << formatv("{0:x} -> {1:x} ({2}/{3}b -> {4}/{5}b)\n", 210 OutputOffset, InputOffset, OutputDelta, 211 encodeULEB128(OutputDelta, nulls()), 212 InputDelta, 213 encodeSLEB128(InputDelta, nulls()))); 214 } 215 Maps.insert(std::pair<uint64_t, MapTy>(Address, Map)); 216 } 217 } 218 219 void BoltAddressTranslation::dump(raw_ostream &OS) { 220 const size_t NumTables = Maps.size(); 221 OS << "BAT tables for " << NumTables << " functions:\n"; 222 for (const auto &MapEntry : Maps) { 223 OS << "Function Address: 0x" << Twine::utohexstr(MapEntry.first) << "\n"; 224 OS << "BB mappings:\n"; 225 for (const auto &Entry : MapEntry.second) { 226 const bool IsBranch = Entry.second & BRANCHENTRY; 227 const uint32_t Val = Entry.second >> 1; // dropping BRANCHENTRY bit 228 OS << "0x" << Twine::utohexstr(Entry.first) << " -> " 229 << "0x" << Twine::utohexstr(Val); 230 if (IsBranch) 231 OS << " (branch)"; 232 OS << "\n"; 233 } 234 OS << "\n"; 235 } 236 const size_t NumColdParts = ColdPartSource.size(); 237 if (!NumColdParts) 238 return; 239 240 OS << NumColdParts << " cold mappings:\n"; 241 for (const auto &Entry : ColdPartSource) { 242 OS << "0x" << Twine::utohexstr(Entry.first) << " -> " 243 << Twine::utohexstr(Entry.second) << "\n"; 244 } 245 OS << "\n"; 246 } 247 248 uint64_t BoltAddressTranslation::translate(uint64_t FuncAddress, 249 uint64_t Offset, 250 bool IsBranchSrc) const { 251 auto Iter = Maps.find(FuncAddress); 252 if (Iter == Maps.end()) 253 return Offset; 254 255 const MapTy &Map = Iter->second; 256 auto KeyVal = Map.upper_bound(Offset); 257 if (KeyVal == Map.begin()) 258 return Offset; 259 260 --KeyVal; 261 262 const uint32_t Val = KeyVal->second >> 1; // dropping BRANCHENTRY bit 263 // Branch source addresses are translated to the first instruction of the 264 // source BB to avoid accounting for modifications BOLT may have made in the 265 // BB regarding deletion/addition of instructions. 266 if (IsBranchSrc) 267 return Val; 268 return Offset - KeyVal->first + Val; 269 } 270 271 std::optional<BoltAddressTranslation::FallthroughListTy> 272 BoltAddressTranslation::getFallthroughsInTrace(uint64_t FuncAddress, 273 uint64_t From, 274 uint64_t To) const { 275 SmallVector<std::pair<uint64_t, uint64_t>, 16> Res; 276 277 // Filter out trivial case 278 if (From >= To) 279 return Res; 280 281 From -= FuncAddress; 282 To -= FuncAddress; 283 284 auto Iter = Maps.find(FuncAddress); 285 if (Iter == Maps.end()) 286 return std::nullopt; 287 288 const MapTy &Map = Iter->second; 289 auto FromIter = Map.upper_bound(From); 290 if (FromIter == Map.begin()) 291 return Res; 292 // Skip instruction entries, to create fallthroughs we are only interested in 293 // BB boundaries 294 do { 295 if (FromIter == Map.begin()) 296 return Res; 297 --FromIter; 298 } while (FromIter->second & BRANCHENTRY); 299 300 auto ToIter = Map.upper_bound(To); 301 if (ToIter == Map.begin()) 302 return Res; 303 --ToIter; 304 if (FromIter->first >= ToIter->first) 305 return Res; 306 307 for (auto Iter = FromIter; Iter != ToIter;) { 308 const uint32_t Src = Iter->first; 309 if (Iter->second & BRANCHENTRY) { 310 ++Iter; 311 continue; 312 } 313 314 ++Iter; 315 while (Iter->second & BRANCHENTRY && Iter != ToIter) 316 ++Iter; 317 if (Iter->second & BRANCHENTRY) 318 break; 319 Res.emplace_back(Src, Iter->first); 320 } 321 322 return Res; 323 } 324 325 uint64_t BoltAddressTranslation::fetchParentAddress(uint64_t Address) const { 326 auto Iter = ColdPartSource.find(Address); 327 if (Iter == ColdPartSource.end()) 328 return 0; 329 return Iter->second; 330 } 331 332 bool BoltAddressTranslation::enabledFor( 333 llvm::object::ELFObjectFileBase *InputFile) const { 334 for (const SectionRef &Section : InputFile->sections()) { 335 Expected<StringRef> SectionNameOrErr = Section.getName(); 336 if (Error E = SectionNameOrErr.takeError()) 337 continue; 338 339 if (SectionNameOrErr.get() == SECTION_NAME) 340 return true; 341 } 342 return false; 343 } 344 } // namespace bolt 345 } // namespace llvm 346