| 1 | //===-- SourcePrinter.cpp - source interleaving utilities ----------------===// |
| 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 | // This file implements the LiveElementPrinter and SourcePrinter classes to |
| 10 | // keep track of DWARF info as the current address is updated, and print out the |
| 11 | // source file line and variable or inlined function liveness as needed. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #include "SourcePrinter.h" |
| 16 | #include "llvm-objdump.h" |
| 17 | #include "llvm/ADT/SmallString.h" |
| 18 | #include "llvm/DebugInfo/DWARF/DWARFExpressionPrinter.h" |
| 19 | #include "llvm/DebugInfo/DWARF/LowLevel/DWARFExpression.h" |
| 20 | #include "llvm/Demangle/Demangle.h" |
| 21 | #include "llvm/Support/FileSystem.h" |
| 22 | #include "llvm/Support/FormatVariadic.h" |
| 23 | #include "llvm/Support/Path.h" |
| 24 | |
| 25 | #define DEBUG_TYPE "objdump" |
| 26 | |
| 27 | namespace llvm { |
| 28 | namespace objdump { |
| 29 | |
| 30 | static bool sourceFileExists(StringRef Path) { |
| 31 | if (sys::fs::exists(Path) && !sys::fs::is_directory(Path)) |
| 32 | return true; |
| 33 | |
| 34 | return false; |
| 35 | } |
| 36 | |
| 37 | static void normalizeSourcePath(SmallVectorImpl<char> &Path) { |
| 38 | sys::path::native(path&: Path); |
| 39 | sys::path::remove_dots(path&: Path, /*remove_dot_dot=*/true); |
| 40 | } |
| 41 | |
| 42 | static std::optional<std::string> trySourcePath(StringRef Path) { |
| 43 | SmallString<256> Normalized(Path); |
| 44 | normalizeSourcePath(Path&: Normalized); |
| 45 | if (sourceFileExists(Path: Normalized)) |
| 46 | return std::string(Normalized); |
| 47 | return std::nullopt; |
| 48 | } |
| 49 | |
| 50 | static std::optional<std::string> |
| 51 | searchSourceWithDirs(StringRef FileName, ArrayRef<StringRef> SearchDirs, |
| 52 | bool TryLiteralFirst) { |
| 53 | if (TryLiteralFirst) |
| 54 | if (auto Path = trySourcePath(Path: FileName)) |
| 55 | return Path; |
| 56 | |
| 57 | StringRef PathSuffix = sys::path::relative_path(path: FileName); |
| 58 | StringRef BaseName = sys::path::filename(path: FileName); |
| 59 | for (StringRef Dir : SearchDirs) { |
| 60 | SmallString<256> Candidate(Dir); |
| 61 | sys::path::append(path&: Candidate, a: PathSuffix); |
| 62 | if (auto Path = trySourcePath(Path: Candidate)) |
| 63 | return Path; |
| 64 | } |
| 65 | for (StringRef Dir : SearchDirs) { |
| 66 | SmallString<256> Candidate(Dir); |
| 67 | sys::path::append(path&: Candidate, a: BaseName); |
| 68 | if (auto Path = trySourcePath(Path: Candidate)) |
| 69 | return Path; |
| 70 | } |
| 71 | return std::nullopt; |
| 72 | } |
| 73 | |
| 74 | static std::optional<std::string> |
| 75 | findSourceFilePath(StringRef FileName, ArrayRef<StringRef> SearchDirs) { |
| 76 | if (FileName.empty() || FileName == DILineInfo::BadString) |
| 77 | return std::nullopt; |
| 78 | |
| 79 | if (sys::path::is_absolute_gnu(path: FileName)) |
| 80 | return searchSourceWithDirs(FileName, SearchDirs, /*TryLiteralFirst=*/true); |
| 81 | return searchSourceWithDirs(FileName, SearchDirs, /*TryLiteralFirst=*/false); |
| 82 | } |
| 83 | |
| 84 | static std::string applySubstitutePaths(StringRef FileName) { |
| 85 | if (SubstitutePaths.empty()) |
| 86 | return FileName.str(); |
| 87 | |
| 88 | StringRef BaseName = sys::path::filename(path: FileName); |
| 89 | SmallString<256> Directory(sys::path::parent_path(path: FileName)); |
| 90 | normalizeSourcePath(Path&: Directory); |
| 91 | |
| 92 | for (const auto &[From, To] : SubstitutePaths) { |
| 93 | SmallString<256> FromPath(From); |
| 94 | normalizeSourcePath(Path&: FromPath); |
| 95 | StringRef Dir = Directory; |
| 96 | if (!Dir.starts_with(Prefix: FromPath)) |
| 97 | continue; |
| 98 | if (Dir.size() > FromPath.size() && |
| 99 | !sys::path::is_separator(value: Dir[FromPath.size()])) |
| 100 | continue; |
| 101 | |
| 102 | SmallString<256> NewDir(To); |
| 103 | StringRef Suffix = Dir.substr(Start: FromPath.size()); |
| 104 | while (!Suffix.empty() && sys::path::is_separator(value: Suffix.front())) |
| 105 | Suffix = Suffix.drop_front(); |
| 106 | if (!Suffix.empty()) |
| 107 | sys::path::append(path&: NewDir, a: Suffix); |
| 108 | normalizeSourcePath(Path&: NewDir); |
| 109 | |
| 110 | if (NewDir.empty()) |
| 111 | return BaseName.str(); |
| 112 | SmallString<256> Result(NewDir); |
| 113 | sys::path::append(path&: Result, a: BaseName); |
| 114 | normalizeSourcePath(Path&: Result); |
| 115 | return std::string(Result); |
| 116 | } |
| 117 | |
| 118 | return FileName.str(); |
| 119 | } |
| 120 | |
| 121 | bool InlinedFunction::liveAtAddress(object::SectionedAddress Addr) const { |
| 122 | if (!Range.valid()) |
| 123 | return false; |
| 124 | |
| 125 | return Range.LowPC <= Addr.Address && Range.HighPC > Addr.Address; |
| 126 | } |
| 127 | |
| 128 | void InlinedFunction::print(raw_ostream &OS, const MCRegisterInfo &MRI) const { |
| 129 | const char *MangledCallerName = FuncDie.getName(Kind: DINameKind::LinkageName); |
| 130 | if (!MangledCallerName) |
| 131 | return; |
| 132 | |
| 133 | if (Demangle) |
| 134 | OS << "inlined into " << demangle(MangledName: MangledCallerName); |
| 135 | else |
| 136 | OS << "inlined into " << MangledCallerName; |
| 137 | } |
| 138 | |
| 139 | void InlinedFunction::dump(raw_ostream &OS) const { |
| 140 | OS << Name << " @ " << Range << ": " ; |
| 141 | } |
| 142 | |
| 143 | void InlinedFunction::printElementLine(raw_ostream &OS, |
| 144 | object::SectionedAddress Addr, |
| 145 | bool IsEnd) const { |
| 146 | uint32_t CallFile, CallLine, CallColumn, CallDiscriminator; |
| 147 | InlinedFuncDie.getCallerFrame(CallFile, CallLine, CallColumn, |
| 148 | CallDiscriminator); |
| 149 | const DWARFDebugLine::LineTable *LineTable = |
| 150 | Unit->getContext().getLineTableForUnit(U: Unit); |
| 151 | std::string FileName; |
| 152 | if (!LineTable->hasFileAtIndex(FileIndex: CallFile)) |
| 153 | return; |
| 154 | if (!LineTable->getFileNameByIndex( |
| 155 | FileIndex: CallFile, CompDir: Unit->getCompilationDir(), |
| 156 | Kind: DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, Result&: FileName)) |
| 157 | return; |
| 158 | |
| 159 | if (FileName.empty()) |
| 160 | return; |
| 161 | |
| 162 | const char *MangledCallerName = FuncDie.getName(Kind: DINameKind::LinkageName); |
| 163 | if (!MangledCallerName) |
| 164 | return; |
| 165 | |
| 166 | std::string CallerName = MangledCallerName; |
| 167 | std::string CalleeName = Name; |
| 168 | if (Demangle) { |
| 169 | CallerName = demangle(MangledName: MangledCallerName); |
| 170 | CalleeName = demangle(MangledName: Name); |
| 171 | } |
| 172 | |
| 173 | OS << "; " << FileName << ":" << CallLine << ":" << CallColumn << ": " ; |
| 174 | if (IsEnd) |
| 175 | OS << "end of " ; |
| 176 | OS << CalleeName << " inlined into " << CallerName << "\n" ; |
| 177 | } |
| 178 | |
| 179 | bool LiveVariable::liveAtAddress(object::SectionedAddress Addr) const { |
| 180 | if (LocExpr.Range == std::nullopt) |
| 181 | return false; |
| 182 | return LocExpr.Range->SectionIndex == Addr.SectionIndex && |
| 183 | LocExpr.Range->LowPC <= Addr.Address && |
| 184 | LocExpr.Range->HighPC > Addr.Address; |
| 185 | } |
| 186 | |
| 187 | void LiveVariable::print(raw_ostream &OS, const MCRegisterInfo &MRI) const { |
| 188 | DataExtractor Data(LocExpr.Expr, Unit->getContext().isLittleEndian()); |
| 189 | DWARFExpression Expression(Data, Unit->getAddressByteSize()); |
| 190 | |
| 191 | auto GetRegName = [&MRI, &OS](uint64_t DwarfRegNum, bool IsEH) -> StringRef { |
| 192 | if (std::optional<MCRegister> LLVMRegNum = |
| 193 | MRI.getLLVMRegNum(RegNum: DwarfRegNum, isEH: IsEH)) |
| 194 | if (const char *RegName = MRI.getName(RegNo: *LLVMRegNum)) |
| 195 | return StringRef(RegName); |
| 196 | OS << "<unknown register " << DwarfRegNum << ">" ; |
| 197 | return {}; |
| 198 | }; |
| 199 | |
| 200 | printDwarfExpressionCompact(E: &Expression, OS, GetNameForDWARFReg: GetRegName); |
| 201 | } |
| 202 | |
| 203 | void LiveVariable::dump(raw_ostream &OS) const { |
| 204 | OS << Name << " @ " << LocExpr.Range << ": " ; |
| 205 | } |
| 206 | |
| 207 | void LiveElementPrinter::addInlinedFunction(DWARFDie FuncDie, |
| 208 | DWARFDie InlinedFuncDie) { |
| 209 | uint64_t FuncLowPC, FuncHighPC, SectionIndex; |
| 210 | if (!InlinedFuncDie.getLowAndHighPC(LowPC&: FuncLowPC, HighPC&: FuncHighPC, SectionIndex)) |
| 211 | return; |
| 212 | |
| 213 | DWARFUnit *U = InlinedFuncDie.getDwarfUnit(); |
| 214 | const char *InlinedFuncName = InlinedFuncDie.getName(Kind: DINameKind::LinkageName); |
| 215 | DWARFAddressRange Range{FuncLowPC, FuncHighPC, SectionIndex}; |
| 216 | // Add the new element to the main vector. |
| 217 | LiveElements.emplace_back(args: std::make_unique<InlinedFunction>( |
| 218 | args&: InlinedFuncName, args&: U, args&: FuncDie, args&: InlinedFuncDie, args&: Range)); |
| 219 | |
| 220 | LiveElement *LE = LiveElements.back().get(); |
| 221 | // Map the element's low address (LowPC) to its pointer for fast range start |
| 222 | // lookup. |
| 223 | LiveElementsByAddress[FuncLowPC].push_back(x: LE); |
| 224 | // Map the element's high address (HighPC) to its pointer for fast range end |
| 225 | // lookup. |
| 226 | LiveElementsByEndAddress[FuncHighPC].push_back(x: LE); |
| 227 | // Map the pointer to its DWARF discovery index for deterministic |
| 228 | // ordering. |
| 229 | ElementPtrToIndex[LE] = LiveElements.size() - 1; |
| 230 | } |
| 231 | |
| 232 | /// Registers the most recently added LiveVariable into all data structures. |
| 233 | void LiveElementPrinter::registerNewVariable() { |
| 234 | assert( |
| 235 | !LiveElements.empty() && |
| 236 | "registerNewVariable called before element was added to LiveElements." ); |
| 237 | LiveVariable *CurrentVar = |
| 238 | static_cast<LiveVariable *>(LiveElements.back().get()); |
| 239 | assert(ElementPtrToIndex.count(CurrentVar) == 0 && |
| 240 | "Element already registered!" ); |
| 241 | |
| 242 | // Map from a LiveElement pointer to its index in the LiveElements. |
| 243 | ElementPtrToIndex[CurrentVar] = LiveElements.size() - 1; |
| 244 | |
| 245 | if (const std::optional<DWARFAddressRange> &Range = |
| 246 | CurrentVar->getLocExpr().Range) { |
| 247 | // Add the variable to address-based maps. |
| 248 | LiveElementsByAddress[Range->LowPC].push_back(x: CurrentVar); |
| 249 | LiveElementsByEndAddress[Range->HighPC].push_back(x: CurrentVar); |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | void LiveElementPrinter::addVariable(DWARFDie FuncDie, DWARFDie VarDie) { |
| 254 | uint64_t FuncLowPC, FuncHighPC, SectionIndex; |
| 255 | FuncDie.getLowAndHighPC(LowPC&: FuncLowPC, HighPC&: FuncHighPC, SectionIndex); |
| 256 | const char *VarName = VarDie.getName(Kind: DINameKind::ShortName); |
| 257 | DWARFUnit *U = VarDie.getDwarfUnit(); |
| 258 | |
| 259 | Expected<DWARFLocationExpressionsVector> Locs = |
| 260 | VarDie.getLocations(Attr: dwarf::DW_AT_location); |
| 261 | if (!Locs) { |
| 262 | // If the variable doesn't have any locations, just ignore it. We don't |
| 263 | // report an error or warning here as that could be noisy on optimised |
| 264 | // code. |
| 265 | consumeError(Err: Locs.takeError()); |
| 266 | return; |
| 267 | } |
| 268 | |
| 269 | for (const DWARFLocationExpression &LocExpr : *Locs) { |
| 270 | if (LocExpr.Range) { |
| 271 | LiveElements.emplace_back( |
| 272 | args: std::make_unique<LiveVariable>(args: LocExpr, args&: VarName, args&: U, args&: FuncDie)); |
| 273 | } else { |
| 274 | // If the LocExpr does not have an associated range, it is valid for |
| 275 | // the whole of the function. |
| 276 | // TODO: technically it is not valid for any range covered by another |
| 277 | // LocExpr, does that happen in reality? |
| 278 | DWARFLocationExpression WholeFuncExpr{ |
| 279 | .Range: DWARFAddressRange(FuncLowPC, FuncHighPC, SectionIndex), .Expr: LocExpr.Expr}; |
| 280 | LiveElements.emplace_back( |
| 281 | args: std::make_unique<LiveVariable>(args&: WholeFuncExpr, args&: VarName, args&: U, args&: FuncDie)); |
| 282 | } |
| 283 | |
| 284 | // Register the new variable with all data structures. |
| 285 | registerNewVariable(); |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | void LiveElementPrinter::addFunction(DWARFDie D) { |
| 290 | for (const DWARFDie &Child : D.children()) { |
| 291 | if (DbgVariables != DFDisabled && |
| 292 | (Child.getTag() == dwarf::DW_TAG_variable || |
| 293 | Child.getTag() == dwarf::DW_TAG_formal_parameter)) { |
| 294 | addVariable(FuncDie: D, VarDie: Child); |
| 295 | } else if (DbgInlinedFunctions != DFDisabled && |
| 296 | Child.getTag() == dwarf::DW_TAG_inlined_subroutine) { |
| 297 | addInlinedFunction(FuncDie: D, InlinedFuncDie: Child); |
| 298 | addFunction(D: Child); |
| 299 | } else |
| 300 | addFunction(D: Child); |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | // Get the column number (in characters) at which the first live element |
| 305 | // line should be printed. |
| 306 | unsigned LiveElementPrinter::getIndentLevel() const { |
| 307 | return DbgIndent + getInstStartColumn(STI); |
| 308 | } |
| 309 | |
| 310 | // Indent to the first live-range column to the right of the currently |
| 311 | // printed line, and return the index of that column. |
| 312 | // TODO: formatted_raw_ostream uses "column" to mean a number of characters |
| 313 | // since the last \n, and we use it to mean the number of slots in which we |
| 314 | // put live element lines. Pick a less overloaded word. |
| 315 | unsigned LiveElementPrinter::moveToFirstVarColumn(formatted_raw_ostream &OS) { |
| 316 | // Logical column number: column zero is the first column we print in, each |
| 317 | // logical column is 2 physical columns wide. |
| 318 | unsigned FirstUnprintedLogicalColumn = |
| 319 | std::max(a: (int)(OS.getColumn() - getIndentLevel() + 1) / 2, b: 0); |
| 320 | // Physical column number: the actual column number in characters, with |
| 321 | // zero being the left-most side of the screen. |
| 322 | unsigned FirstUnprintedPhysicalColumn = |
| 323 | getIndentLevel() + FirstUnprintedLogicalColumn * 2; |
| 324 | |
| 325 | if (FirstUnprintedPhysicalColumn > OS.getColumn()) |
| 326 | OS.PadToColumn(NewCol: FirstUnprintedPhysicalColumn); |
| 327 | |
| 328 | return FirstUnprintedLogicalColumn; |
| 329 | } |
| 330 | |
| 331 | unsigned LiveElementPrinter::getOrCreateColumn(unsigned ElementIdx) { |
| 332 | // Check if the element already has an assigned column. |
| 333 | auto it = ElementToColumn.find(Val: ElementIdx); |
| 334 | if (it != ElementToColumn.end()) |
| 335 | return it->second; |
| 336 | |
| 337 | unsigned ColIdx; |
| 338 | if (!FreeCols.empty()) { |
| 339 | // Get the smallest available index from the set. |
| 340 | ColIdx = *FreeCols.begin(); |
| 341 | // Remove the index from the set. |
| 342 | FreeCols.erase(position: FreeCols.begin()); |
| 343 | } else { |
| 344 | // No free columns, so create a new one. |
| 345 | ColIdx = ActiveCols.size(); |
| 346 | ActiveCols.emplace_back(); |
| 347 | } |
| 348 | |
| 349 | // Assign the element to the column and update the map. |
| 350 | ElementToColumn[ElementIdx] = ColIdx; |
| 351 | ActiveCols[ColIdx].ElementIdx = ElementIdx; |
| 352 | return ColIdx; |
| 353 | } |
| 354 | |
| 355 | void LiveElementPrinter::freeColumn(unsigned ColIdx) { |
| 356 | unsigned ElementIdx = ActiveCols[ColIdx].ElementIdx; |
| 357 | |
| 358 | // Clear the column's data. |
| 359 | ActiveCols[ColIdx].clear(); |
| 360 | |
| 361 | // Remove the element's entry from the map and add the column to the free |
| 362 | // list. |
| 363 | ElementToColumn.erase(Val: ElementIdx); |
| 364 | FreeCols.insert(x: ColIdx); |
| 365 | } |
| 366 | |
| 367 | std::vector<unsigned> |
| 368 | LiveElementPrinter::getSortedActiveElementIndices() const { |
| 369 | // Get all element indices that currently have an assigned column. |
| 370 | std::vector<unsigned> Indices; |
| 371 | for (const auto &Pair : ElementToColumn) |
| 372 | Indices.push_back(x: Pair.first); |
| 373 | |
| 374 | // Sort by the DWARF discovery order. |
| 375 | llvm::stable_sort(Range&: Indices); |
| 376 | return Indices; |
| 377 | } |
| 378 | |
| 379 | void LiveElementPrinter::dump() const { |
| 380 | for (const std::unique_ptr<LiveElement> &LE : LiveElements) { |
| 381 | LE->dump(OS&: dbgs()); |
| 382 | LE->print(OS&: dbgs(), MRI); |
| 383 | dbgs() << "\n" ; |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | void LiveElementPrinter::addCompileUnit(DWARFDie D) { |
| 388 | if (D.getTag() == dwarf::DW_TAG_subprogram) |
| 389 | addFunction(D); |
| 390 | else |
| 391 | for (const DWARFDie &Child : D.children()) |
| 392 | addFunction(D: Child); |
| 393 | } |
| 394 | |
| 395 | /// Update to match the state of the instruction between ThisAddr and |
| 396 | /// NextAddr. In the common case, any live range active at ThisAddr is |
| 397 | /// live-in to the instruction, and any live range active at NextAddr is |
| 398 | /// live-out of the instruction. If IncludeDefinedVars is false, then live |
| 399 | /// ranges starting at NextAddr will be ignored. |
| 400 | void LiveElementPrinter::update(object::SectionedAddress ThisAddr, |
| 401 | object::SectionedAddress NextAddr, |
| 402 | bool IncludeDefinedVars) { |
| 403 | // Exit early if only printing function limits. |
| 404 | if (DbgInlinedFunctions == DFLimitsOnly) |
| 405 | return; |
| 406 | |
| 407 | // Free columns identified in the previous cycle. |
| 408 | for (unsigned ColIdx : ColumnsToFreeNextCycle) |
| 409 | freeColumn(ColIdx); |
| 410 | ColumnsToFreeNextCycle.clear(); |
| 411 | |
| 412 | // Update status of active columns and collect those to free next cycle. |
| 413 | for (unsigned ColIdx = 0, End = ActiveCols.size(); ColIdx < End; ++ColIdx) { |
| 414 | if (!ActiveCols[ColIdx].isActive()) |
| 415 | continue; |
| 416 | |
| 417 | const std::unique_ptr<LiveElement> &LE = |
| 418 | LiveElements[ActiveCols[ColIdx].ElementIdx]; |
| 419 | ActiveCols[ColIdx].LiveIn = LE->liveAtAddress(Addr: ThisAddr); |
| 420 | ActiveCols[ColIdx].LiveOut = LE->liveAtAddress(Addr: NextAddr); |
| 421 | |
| 422 | LLVM_DEBUG({ |
| 423 | std::string Name = Demangle ? demangle(LE->getName()) : LE->getName(); |
| 424 | dbgs() << "pass 1, " << ThisAddr.Address << "-" << NextAddr.Address |
| 425 | << ", " << Name << ", Col " << ColIdx |
| 426 | << ": LiveIn=" << ActiveCols[ColIdx].LiveIn |
| 427 | << ", LiveOut=" << ActiveCols[ColIdx].LiveOut << "\n" ; |
| 428 | }); |
| 429 | |
| 430 | // If element is fully dead, deactivate column immediately. |
| 431 | if (!ActiveCols[ColIdx].LiveIn && !ActiveCols[ColIdx].LiveOut) { |
| 432 | ActiveCols[ColIdx].ElementIdx = Column::NullElementIdx; |
| 433 | continue; |
| 434 | } |
| 435 | |
| 436 | // Mark for cleanup in the next cycle if range ends here. |
| 437 | if (ActiveCols[ColIdx].LiveIn && !ActiveCols[ColIdx].LiveOut) |
| 438 | ColumnsToFreeNextCycle.push_back(x: ColIdx); |
| 439 | } |
| 440 | |
| 441 | // Next, look for variables which don't already have a column, but which |
| 442 | // are now live (those starting at ThisAddr or NextAddr). |
| 443 | if (IncludeDefinedVars) { |
| 444 | // Collect all elements starting at ThisAddr and NextAddr. |
| 445 | std::vector<std::pair<unsigned, LiveElement *>> NewLiveElements; |
| 446 | auto CollectNewElements = [&](const auto &It) { |
| 447 | if (It == LiveElementsByAddress.end()) |
| 448 | return; |
| 449 | |
| 450 | const std::vector<LiveElement *> &ElementList = It->second; |
| 451 | for (LiveElement *LE : ElementList) { |
| 452 | auto IndexIt = ElementPtrToIndex.find(Val: LE); |
| 453 | assert(IndexIt != ElementPtrToIndex.end() && |
| 454 | "LiveElement in address map but missing from index map!" ); |
| 455 | |
| 456 | // Get the element index for sorting and column management. |
| 457 | unsigned ElementIdx = IndexIt->second; |
| 458 | // Skip elements that already have a column. |
| 459 | if (ElementToColumn.count(Val: ElementIdx)) |
| 460 | continue; |
| 461 | |
| 462 | bool LiveIn = LE->liveAtAddress(Addr: ThisAddr); |
| 463 | bool LiveOut = LE->liveAtAddress(Addr: NextAddr); |
| 464 | if (!LiveIn && !LiveOut) |
| 465 | continue; |
| 466 | |
| 467 | NewLiveElements.emplace_back(args&: ElementIdx, args&: LE); |
| 468 | } |
| 469 | }; |
| 470 | |
| 471 | // Collect elements starting at ThisAddr. |
| 472 | CollectNewElements(LiveElementsByAddress.find(Key: ThisAddr.Address)); |
| 473 | // Collect elements starting at NextAddr (the address immediately |
| 474 | // following the instruction). |
| 475 | CollectNewElements(LiveElementsByAddress.find(Key: NextAddr.Address)); |
| 476 | // Sort elements by DWARF discovery order for deterministic column |
| 477 | // assignment. |
| 478 | llvm::stable_sort(Range&: NewLiveElements, C: [](const auto &A, const auto &B) { |
| 479 | return A.first < B.first; |
| 480 | }); |
| 481 | |
| 482 | // Assign columns in deterministic order. |
| 483 | for (const auto &ElementPair : NewLiveElements) { |
| 484 | unsigned ElementIdx = ElementPair.first; |
| 485 | // Skip if element was already added from the first range. |
| 486 | if (ElementToColumn.count(Val: ElementIdx)) |
| 487 | continue; |
| 488 | |
| 489 | LiveElement *LE = ElementPair.second; |
| 490 | bool LiveIn = LE->liveAtAddress(Addr: ThisAddr); |
| 491 | bool LiveOut = LE->liveAtAddress(Addr: NextAddr); |
| 492 | |
| 493 | // Assign or create a column. |
| 494 | unsigned ColIdx = getOrCreateColumn(ElementIdx); |
| 495 | LLVM_DEBUG({ |
| 496 | std::string Name = Demangle ? demangle(LE->getName()) : LE->getName(); |
| 497 | dbgs() << "pass 2, " << ThisAddr.Address << "-" << NextAddr.Address |
| 498 | << ", " << Name << ", Col " << ColIdx << ": LiveIn=" << LiveIn |
| 499 | << ", LiveOut=" << LiveOut << "\n" ; |
| 500 | }); |
| 501 | |
| 502 | ActiveCols[ColIdx].LiveIn = LiveIn; |
| 503 | ActiveCols[ColIdx].LiveOut = LiveOut; |
| 504 | ActiveCols[ColIdx].MustDrawLabel = true; |
| 505 | |
| 506 | // Mark for cleanup next cycle if range ends here. |
| 507 | if (ActiveCols[ColIdx].LiveIn && !ActiveCols[ColIdx].LiveOut) |
| 508 | ColumnsToFreeNextCycle.push_back(x: ColIdx); |
| 509 | } |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | enum class LineChar { |
| 514 | RangeStart, |
| 515 | RangeMid, |
| 516 | RangeEnd, |
| 517 | LabelVert, |
| 518 | LabelCornerNew, |
| 519 | LabelCornerActive, |
| 520 | LabelHoriz, |
| 521 | }; |
| 522 | const char *LiveElementPrinter::getLineChar(LineChar C) const { |
| 523 | bool IsASCII = DbgVariables == DFASCII || DbgInlinedFunctions == DFASCII; |
| 524 | switch (C) { |
| 525 | case LineChar::RangeStart: |
| 526 | return IsASCII ? "^" : (const char *)u8"\u2548" ; |
| 527 | case LineChar::RangeMid: |
| 528 | return IsASCII ? "|" : (const char *)u8"\u2503" ; |
| 529 | case LineChar::RangeEnd: |
| 530 | return IsASCII ? "v" : (const char *)u8"\u253b" ; |
| 531 | case LineChar::LabelVert: |
| 532 | return IsASCII ? "|" : (const char *)u8"\u2502" ; |
| 533 | case LineChar::LabelCornerNew: |
| 534 | return IsASCII ? "/" : (const char *)u8"\u250c" ; |
| 535 | case LineChar::LabelCornerActive: |
| 536 | return IsASCII ? "|" : (const char *)u8"\u2520" ; |
| 537 | case LineChar::LabelHoriz: |
| 538 | return IsASCII ? "-" : (const char *)u8"\u2500" ; |
| 539 | } |
| 540 | llvm_unreachable("Unhandled LineChar enum" ); |
| 541 | } |
| 542 | |
| 543 | /// Print live ranges to the right of an existing line. This assumes the |
| 544 | /// line is not an instruction, so doesn't start or end any live ranges, so |
| 545 | /// we only need to print active ranges or empty columns. If AfterInst is |
| 546 | /// true, this is being printed after the last instruction fed to update(), |
| 547 | /// otherwise this is being printed before it. |
| 548 | void LiveElementPrinter::printAfterOtherLine(formatted_raw_ostream &OS, |
| 549 | bool AfterInst) { |
| 550 | if (ActiveCols.size()) { |
| 551 | unsigned FirstUnprintedColumn = moveToFirstVarColumn(OS); |
| 552 | for (size_t ColIdx = FirstUnprintedColumn, End = ActiveCols.size(); |
| 553 | ColIdx < End; ++ColIdx) { |
| 554 | if (ActiveCols[ColIdx].isActive()) { |
| 555 | if ((AfterInst && ActiveCols[ColIdx].LiveOut) || |
| 556 | (!AfterInst && ActiveCols[ColIdx].LiveIn)) |
| 557 | OS << getLineChar(C: LineChar::RangeMid); |
| 558 | else if (!AfterInst && ActiveCols[ColIdx].LiveOut) |
| 559 | OS << getLineChar(C: LineChar::LabelVert); |
| 560 | else |
| 561 | OS << " " ; |
| 562 | } |
| 563 | OS << " " ; |
| 564 | } |
| 565 | } |
| 566 | OS << "\n" ; |
| 567 | } |
| 568 | |
| 569 | /// Print any live element range info needed to the right of a |
| 570 | /// non-instruction line of disassembly. This is where we print the element |
| 571 | /// names and expressions, with thin line-drawing characters connecting them |
| 572 | /// to the live range which starts at the next instruction. If MustPrint is |
| 573 | /// true, we have to print at least one line (with the continuation of any |
| 574 | /// already-active live ranges) because something has already been printed |
| 575 | /// earlier on this line. |
| 576 | void LiveElementPrinter::printBetweenInsts(formatted_raw_ostream &OS, |
| 577 | bool MustPrint) { |
| 578 | bool PrintedSomething = false; |
| 579 | // Get all active elements, sorted by discovery order. |
| 580 | std::vector<unsigned> SortedElementIndices = getSortedActiveElementIndices(); |
| 581 | // The outer loop iterates over the deterministic DWARF discovery order. |
| 582 | for (unsigned ElementIdx : SortedElementIndices) { |
| 583 | // Look up the physical column index (ColIdx) assigned to this |
| 584 | // element. We use .at() because we are certain the element is active. |
| 585 | unsigned ColIdx = ElementToColumn.at(Val: ElementIdx); |
| 586 | if (ActiveCols[ColIdx].isActive() && ActiveCols[ColIdx].MustDrawLabel) { |
| 587 | // First we need to print the live range markers for any active |
| 588 | // columns to the left of this one. |
| 589 | OS.PadToColumn(NewCol: getIndentLevel()); |
| 590 | for (unsigned ColIdx2 = 0; ColIdx2 < ColIdx; ++ColIdx2) { |
| 591 | if (ActiveCols[ColIdx2].isActive()) { |
| 592 | if (ActiveCols[ColIdx2].MustDrawLabel && !ActiveCols[ColIdx2].LiveIn) |
| 593 | OS << getLineChar(C: LineChar::LabelVert) << " " ; |
| 594 | else |
| 595 | OS << getLineChar(C: LineChar::RangeMid) << " " ; |
| 596 | } else |
| 597 | OS << " " ; |
| 598 | } |
| 599 | |
| 600 | const std::unique_ptr<LiveElement> &LE = LiveElements[ElementIdx]; |
| 601 | // Then print the variable name and location of the new live range, |
| 602 | // with box drawing characters joining it to the live range line. |
| 603 | OS << getLineChar(C: ActiveCols[ColIdx].LiveIn ? LineChar::LabelCornerActive |
| 604 | : LineChar::LabelCornerNew) |
| 605 | << getLineChar(C: LineChar::LabelHoriz) << " " ; |
| 606 | |
| 607 | std::string Name = Demangle ? demangle(MangledName: LE->getName()) : LE->getName(); |
| 608 | WithColor(OS, raw_ostream::GREEN) << Name; |
| 609 | OS << " = " ; |
| 610 | { |
| 611 | WithColor ExprColor(OS, raw_ostream::CYAN); |
| 612 | LE->print(OS, MRI); |
| 613 | } |
| 614 | |
| 615 | // If there are any columns to the right of the expression we just |
| 616 | // printed, then continue their live range lines. |
| 617 | unsigned FirstUnprintedColumn = moveToFirstVarColumn(OS); |
| 618 | for (unsigned ColIdx2 = FirstUnprintedColumn, End = ActiveCols.size(); |
| 619 | ColIdx2 < End; ++ColIdx2) { |
| 620 | if (ActiveCols[ColIdx2].isActive() && ActiveCols[ColIdx2].LiveIn) |
| 621 | OS << getLineChar(C: LineChar::RangeMid) << " " ; |
| 622 | else |
| 623 | OS << " " ; |
| 624 | } |
| 625 | |
| 626 | OS << "\n" ; |
| 627 | PrintedSomething = true; |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | for (unsigned ColIdx = 0, End = ActiveCols.size(); ColIdx < End; ++ColIdx) |
| 632 | if (ActiveCols[ColIdx].isActive()) |
| 633 | ActiveCols[ColIdx].MustDrawLabel = false; |
| 634 | |
| 635 | // If we must print something (because we printed a line/column number), |
| 636 | // but don't have any new variables to print, then print a line which |
| 637 | // just continues any existing live ranges. |
| 638 | if (MustPrint && !PrintedSomething) |
| 639 | printAfterOtherLine(OS, AfterInst: false); |
| 640 | } |
| 641 | |
| 642 | /// Print the live element ranges to the right of a disassembled instruction. |
| 643 | void LiveElementPrinter::printAfterInst(formatted_raw_ostream &OS) { |
| 644 | if (!ActiveCols.size()) |
| 645 | return; |
| 646 | unsigned FirstUnprintedColumn = moveToFirstVarColumn(OS); |
| 647 | for (unsigned ColIdx = FirstUnprintedColumn, End = ActiveCols.size(); |
| 648 | ColIdx < End; ++ColIdx) { |
| 649 | if (!ActiveCols[ColIdx].isActive()) |
| 650 | OS << " " ; |
| 651 | else if (ActiveCols[ColIdx].LiveIn && ActiveCols[ColIdx].LiveOut) |
| 652 | OS << getLineChar(C: LineChar::RangeMid) << " " ; |
| 653 | else if (ActiveCols[ColIdx].LiveOut) |
| 654 | OS << getLineChar(C: LineChar::RangeStart) << " " ; |
| 655 | else if (ActiveCols[ColIdx].LiveIn) |
| 656 | OS << getLineChar(C: LineChar::RangeEnd) << " " ; |
| 657 | else |
| 658 | llvm_unreachable("var must be live in or out!" ); |
| 659 | } |
| 660 | } |
| 661 | |
| 662 | void LiveElementPrinter::printBoundaryLine(formatted_raw_ostream &OS, |
| 663 | object::SectionedAddress Addr, |
| 664 | bool IsEnd) { |
| 665 | // Only print the start/end line for inlined functions if DFLimitsOnly is |
| 666 | // enabled. |
| 667 | if (DbgInlinedFunctions != DFLimitsOnly) |
| 668 | return; |
| 669 | |
| 670 | // Select the appropriate map based on whether we are checking the start |
| 671 | // (LowPC) or end (HighPC) address. |
| 672 | const auto &AddressMap = |
| 673 | IsEnd ? LiveElementsByEndAddress : LiveElementsByAddress; |
| 674 | |
| 675 | // Use the map to find all elements that start/end at the given address. |
| 676 | std::vector<unsigned> ElementIndices; |
| 677 | auto It = AddressMap.find(Key: Addr.Address); |
| 678 | if (It != AddressMap.end()) { |
| 679 | for (LiveElement *LE : It->second) { |
| 680 | // Look up the element index from the pointer. |
| 681 | auto IndexIt = ElementPtrToIndex.find(Val: LE); |
| 682 | assert(IndexIt != ElementPtrToIndex.end() && |
| 683 | "LiveElement found in address map but missing index!" ); |
| 684 | ElementIndices.push_back(x: IndexIt->second); |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | // Sort the indices to ensure deterministic output order (by DWARF discovery |
| 689 | // order). |
| 690 | llvm::stable_sort(Range&: ElementIndices); |
| 691 | |
| 692 | for (unsigned ElementIdx : ElementIndices) { |
| 693 | LiveElement *LE = LiveElements[ElementIdx].get(); |
| 694 | LE->printElementLine(OS, Address: Addr, IsEnd); |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) { |
| 699 | std::unique_ptr<MemoryBuffer> Buffer; |
| 700 | if (LineInfo.Source) { |
| 701 | Buffer = MemoryBuffer::getMemBuffer(InputData: *LineInfo.Source); |
| 702 | } else { |
| 703 | std::string PathToOpen = LineInfo.FileName; |
| 704 | if (!SourceDirs.empty()) { |
| 705 | SmallVector<StringRef, 8> SearchDirs; |
| 706 | for (const std::string &Dir : SourceDirs) |
| 707 | SearchDirs.push_back(Elt: Dir); |
| 708 | if (std::optional<std::string> Resolved = |
| 709 | findSourceFilePath(FileName: LineInfo.FileName, SearchDirs)) |
| 710 | PathToOpen = std::move(*Resolved); |
| 711 | } |
| 712 | |
| 713 | auto BufferOrError = MemoryBuffer::getFile(Filename: PathToOpen, /*IsText=*/true); |
| 714 | if (!BufferOrError) { |
| 715 | if (MissingSources.insert(key: LineInfo.FileName).second) |
| 716 | reportWarning(Message: "failed to find source " + LineInfo.FileName, |
| 717 | File: Obj->getFileName()); |
| 718 | return false; |
| 719 | } |
| 720 | Buffer = std::move(*BufferOrError); |
| 721 | } |
| 722 | // Chomp the file to get lines |
| 723 | const char *BufferStart = Buffer->getBufferStart(), |
| 724 | *BufferEnd = Buffer->getBufferEnd(); |
| 725 | std::vector<StringRef> &Lines = LineCache[LineInfo.FileName]; |
| 726 | const char *Start = BufferStart; |
| 727 | for (const char *I = BufferStart; I != BufferEnd; ++I) |
| 728 | if (*I == '\n') { |
| 729 | Lines.emplace_back(args&: Start, args: I - Start - (BufferStart < I && I[-1] == '\r')); |
| 730 | Start = I + 1; |
| 731 | } |
| 732 | if (Start < BufferEnd) |
| 733 | Lines.emplace_back(args&: Start, args: BufferEnd - Start); |
| 734 | SourceCache[LineInfo.FileName] = std::move(Buffer); |
| 735 | return true; |
| 736 | } |
| 737 | |
| 738 | void SourcePrinter::printSourceLine(formatted_raw_ostream &OS, |
| 739 | object::SectionedAddress Address, |
| 740 | StringRef ObjectFilename, |
| 741 | LiveElementPrinter &LEP, |
| 742 | StringRef Delimiter) { |
| 743 | if (!Symbolizer) |
| 744 | return; |
| 745 | |
| 746 | DILineInfo LineInfo = DILineInfo(); |
| 747 | Expected<DILineInfo> ExpectedLineInfo = |
| 748 | Symbolizer->symbolizeCode(Obj: *Obj, ModuleOffset: Address); |
| 749 | if (ExpectedLineInfo) { |
| 750 | LineInfo = *ExpectedLineInfo; |
| 751 | } else if (!WarnedInvalidDebugInfo) { |
| 752 | WarnedInvalidDebugInfo = true; |
| 753 | // TODO Untested. |
| 754 | reportWarning(Message: "failed to parse debug information: " + |
| 755 | toString(E: ExpectedLineInfo.takeError()), |
| 756 | File: ObjectFilename); |
| 757 | } |
| 758 | if (!objdump::SubstitutePaths.empty()) |
| 759 | LineInfo.FileName = applySubstitutePaths(FileName: LineInfo.FileName); |
| 760 | |
| 761 | if (!objdump::Prefix.empty() && |
| 762 | sys::path::is_absolute_gnu(path: LineInfo.FileName)) { |
| 763 | // FileName has at least one character since is_absolute_gnu is false for |
| 764 | // an empty string. |
| 765 | assert(!LineInfo.FileName.empty()); |
| 766 | if (PrefixStrip > 0) { |
| 767 | uint32_t Level = 0; |
| 768 | auto StrippedNameStart = LineInfo.FileName.begin(); |
| 769 | |
| 770 | // Path.h iterator skips extra separators. Therefore it cannot be used |
| 771 | // here to keep compatibility with GNU Objdump. |
| 772 | for (auto Pos = StrippedNameStart + 1, End = LineInfo.FileName.end(); |
| 773 | Pos != End && Level < PrefixStrip; ++Pos) { |
| 774 | if (sys::path::is_separator(value: *Pos)) { |
| 775 | StrippedNameStart = Pos; |
| 776 | ++Level; |
| 777 | } |
| 778 | } |
| 779 | |
| 780 | LineInfo.FileName = |
| 781 | std::string(StrippedNameStart, LineInfo.FileName.end()); |
| 782 | } |
| 783 | |
| 784 | SmallString<128> FilePath; |
| 785 | sys::path::append(path&: FilePath, a: Prefix, b: LineInfo.FileName); |
| 786 | |
| 787 | LineInfo.FileName = std::string(FilePath); |
| 788 | } |
| 789 | |
| 790 | if (PrintLines) |
| 791 | printLines(OS, Address, LineInfo, Delimiter, LEP); |
| 792 | if (PrintSource) |
| 793 | printSources(OS, LineInfo, ObjectFilename, Delimiter, LEP); |
| 794 | OldLineInfo = std::move(LineInfo); |
| 795 | } |
| 796 | |
| 797 | void SourcePrinter::printLines(formatted_raw_ostream &OS, |
| 798 | object::SectionedAddress Address, |
| 799 | const DILineInfo &LineInfo, StringRef Delimiter, |
| 800 | LiveElementPrinter &LEP) { |
| 801 | bool PrintFunctionName = LineInfo.FunctionName != DILineInfo::BadString && |
| 802 | LineInfo.FunctionName != OldLineInfo.FunctionName; |
| 803 | if (PrintFunctionName) { |
| 804 | OS << Delimiter << LineInfo.FunctionName; |
| 805 | // If demangling is successful, FunctionName will end with "()". Print it |
| 806 | // only if demangling did not run or was unsuccessful. |
| 807 | if (!StringRef(LineInfo.FunctionName).ends_with(Suffix: "()" )) |
| 808 | OS << "()" ; |
| 809 | OS << ":\n" ; |
| 810 | } |
| 811 | if (LineInfo.FileName != DILineInfo::BadString && LineInfo.Line != 0 && |
| 812 | (OldLineInfo.Line != LineInfo.Line || |
| 813 | OldLineInfo.FileName != LineInfo.FileName || PrintFunctionName)) { |
| 814 | OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line; |
| 815 | LEP.printBetweenInsts(OS, MustPrint: true); |
| 816 | } |
| 817 | } |
| 818 | |
| 819 | // Get the source line text for LineInfo: |
| 820 | // - use LineInfo::LineSource if available; |
| 821 | // - use LineCache if LineInfo::Source otherwise. |
| 822 | StringRef SourcePrinter::getLine(const DILineInfo &LineInfo, |
| 823 | StringRef ObjectFilename) { |
| 824 | if (LineInfo.LineSource) |
| 825 | return LineInfo.LineSource.value(); |
| 826 | |
| 827 | if (SourceCache.find(Key: LineInfo.FileName) == SourceCache.end()) |
| 828 | if (!cacheSource(LineInfo)) |
| 829 | return {}; |
| 830 | |
| 831 | auto LineBuffer = LineCache.find(Key: LineInfo.FileName); |
| 832 | if (LineBuffer == LineCache.end()) |
| 833 | return {}; |
| 834 | |
| 835 | if (LineInfo.Line > LineBuffer->second.size()) { |
| 836 | reportWarning( |
| 837 | Message: formatv(Fmt: "debug info line number {0} exceeds the number of lines in {1}" , |
| 838 | Vals: LineInfo.Line, Vals: LineInfo.FileName), |
| 839 | File: ObjectFilename); |
| 840 | return {}; |
| 841 | } |
| 842 | |
| 843 | // Vector begins at 0, line numbers are non-zero |
| 844 | return LineBuffer->second[LineInfo.Line - 1]; |
| 845 | } |
| 846 | |
| 847 | void SourcePrinter::printSources(formatted_raw_ostream &OS, |
| 848 | const DILineInfo &LineInfo, |
| 849 | StringRef ObjectFilename, StringRef Delimiter, |
| 850 | LiveElementPrinter &LEP) { |
| 851 | if (LineInfo.FileName == DILineInfo::BadString || LineInfo.Line == 0 || |
| 852 | (OldLineInfo.Line == LineInfo.Line && |
| 853 | OldLineInfo.FileName == LineInfo.FileName)) |
| 854 | return; |
| 855 | |
| 856 | StringRef Line = getLine(LineInfo, ObjectFilename); |
| 857 | if (!Line.empty()) { |
| 858 | OS << Delimiter << Line; |
| 859 | LEP.printBetweenInsts(OS, MustPrint: true); |
| 860 | } |
| 861 | } |
| 862 | |
| 863 | SourcePrinter::SourcePrinter(const object::ObjectFile *Obj, |
| 864 | StringRef DefaultArch) |
| 865 | : Obj(Obj) { |
| 866 | symbolize::LLVMSymbolizer::Options SymbolizerOpts; |
| 867 | SymbolizerOpts.PrintFunctions = |
| 868 | DILineInfoSpecifier::FunctionNameKind::LinkageName; |
| 869 | SymbolizerOpts.Demangle = Demangle; |
| 870 | SymbolizerOpts.DefaultArch = std::string(DefaultArch); |
| 871 | Symbolizer.reset(p: new symbolize::LLVMSymbolizer(SymbolizerOpts)); |
| 872 | } |
| 873 | |
| 874 | } // namespace objdump |
| 875 | } // namespace llvm |
| 876 | |