| 1 | //===- Debugify.cpp - Check debug info preservation in optimizations ------===// |
| 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 | /// \file In the `synthetic` mode, the `-debugify` attaches synthetic debug info |
| 10 | /// to everything. It can be used to create targeted tests for debug info |
| 11 | /// preservation. In addition, when using the `original` mode, it can check |
| 12 | /// original debug info preservation. The `synthetic` mode is default one. |
| 13 | /// |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
| 16 | #include "llvm/Transforms/Utils/Debugify.h" |
| 17 | #include "llvm/ADT/BitVector.h" |
| 18 | #include "llvm/ADT/StringExtras.h" |
| 19 | #include "llvm/Config/llvm-config.h" |
| 20 | #include "llvm/IR/DIBuilder.h" |
| 21 | #include "llvm/IR/DebugInfo.h" |
| 22 | #include "llvm/IR/DebugInfoMetadata.h" |
| 23 | #include "llvm/IR/DebugLoc.h" |
| 24 | #include "llvm/IR/InstIterator.h" |
| 25 | #include "llvm/IR/Instructions.h" |
| 26 | #include "llvm/IR/Module.h" |
| 27 | #include "llvm/IR/PassInstrumentation.h" |
| 28 | #include "llvm/Pass.h" |
| 29 | #include "llvm/Support/CommandLine.h" |
| 30 | #include "llvm/Support/FileSystem.h" |
| 31 | #include "llvm/Support/JSON.h" |
| 32 | #include <optional> |
| 33 | #if LLVM_ENABLE_DEBUGLOC_TRACKING_ORIGIN |
| 34 | // We need the Signals header to operate on stacktraces if we're using DebugLoc |
| 35 | // origin-tracking. |
| 36 | #include "llvm/Support/Signals.h" |
| 37 | #else |
| 38 | #include "llvm/Support/WithColor.h" |
| 39 | #endif |
| 40 | |
| 41 | #define DEBUG_TYPE "debugify" |
| 42 | |
| 43 | using namespace llvm; |
| 44 | |
| 45 | namespace { |
| 46 | |
| 47 | cl::opt<bool> ApplyAtomGroups("debugify-atoms" , cl::init(Val: false)); |
| 48 | |
| 49 | cl::opt<bool> Quiet("debugify-quiet" , |
| 50 | cl::desc("Suppress verbose debugify output" )); |
| 51 | |
| 52 | cl::opt<uint64_t> DebugifyFunctionsLimit( |
| 53 | "debugify-func-limit" , |
| 54 | cl::desc("Set max number of processed functions per pass." ), |
| 55 | cl::init(UINT_MAX)); |
| 56 | |
| 57 | enum class Level { |
| 58 | Locations, |
| 59 | LocationsAndVariables |
| 60 | }; |
| 61 | |
| 62 | cl::opt<Level> DebugifyLevel( |
| 63 | "debugify-level" , cl::desc("Kind of debug info to add" ), |
| 64 | cl::values(clEnumValN(Level::Locations, "locations" , "Locations only" ), |
| 65 | clEnumValN(Level::LocationsAndVariables, "location+variables" , |
| 66 | "Locations and Variables" )), |
| 67 | cl::init(Val: Level::LocationsAndVariables)); |
| 68 | |
| 69 | raw_ostream &dbg() { return Quiet ? nulls() : errs(); } |
| 70 | |
| 71 | #if LLVM_ENABLE_DEBUGLOC_TRACKING_ORIGIN |
| 72 | cl::list<std::string> EnableOriginStacktraces( |
| 73 | "enable-origin-stacktraces" , |
| 74 | cl::desc("Collect DebugLoc origin stacktraces; a comma-separated list of " |
| 75 | "passes may be given, in which case stacktraces will be collected " |
| 76 | "in those passes only" ), |
| 77 | cl::value_desc("Pass1,Pass2,Pass3,..." ), cl::CommaSeparated, |
| 78 | cl::ValueOptional); |
| 79 | |
| 80 | // For a given pass, sets whether the collection of DebugLoc origin stacktraces |
| 81 | // is enabled or not. |
| 82 | static void setDebugLocOriginCollectionForPass(StringRef PassName) { |
| 83 | if (!EnableOriginStacktraces.getNumOccurrences()) { |
| 84 | llvm::DebugLocOriginCollectionEnabled = false; |
| 85 | return; |
| 86 | } |
| 87 | if (EnableOriginStacktraces.size() == 1 && |
| 88 | EnableOriginStacktraces[0].empty()) { |
| 89 | llvm::DebugLocOriginCollectionEnabled = true; |
| 90 | return; |
| 91 | } |
| 92 | llvm::DebugLocOriginCollectionEnabled = |
| 93 | llvm::is_contained(EnableOriginStacktraces, PassName); |
| 94 | } |
| 95 | static void unsetDebugLocOriginCollection() { |
| 96 | llvm::DebugLocOriginCollectionEnabled = false; |
| 97 | } |
| 98 | |
| 99 | // These maps refer to addresses in the current LLVM process, so we can reuse |
| 100 | // them everywhere - therefore, we store them at file scope. |
| 101 | static SymbolizedAddressMap SymbolizedAddrs; |
| 102 | static AddressSet UnsymbolizedAddrs; |
| 103 | |
| 104 | std::string symbolizeStackTrace(const Instruction *I) { |
| 105 | // We flush the set of unsymbolized addresses at the latest possible moment, |
| 106 | // i.e. now. |
| 107 | if (!UnsymbolizedAddrs.empty()) { |
| 108 | sys::symbolizeAddresses(UnsymbolizedAddrs, SymbolizedAddrs); |
| 109 | UnsymbolizedAddrs.clear(); |
| 110 | } |
| 111 | const DbgLocOrigin::StackTracesTy &OriginStackTraces = |
| 112 | I->getDebugLoc().getOriginStackTraces(); |
| 113 | std::string Result; |
| 114 | raw_string_ostream OS(Result); |
| 115 | for (size_t TraceIdx = 0; TraceIdx < OriginStackTraces.size(); ++TraceIdx) { |
| 116 | if (TraceIdx != 0) |
| 117 | OS << "========================================\n" ; |
| 118 | auto &[Depth, StackTrace] = OriginStackTraces[TraceIdx]; |
| 119 | unsigned VirtualFrameNo = 0; |
| 120 | for (int Frame = 0; Frame < Depth; ++Frame) { |
| 121 | assert(SymbolizedAddrs.contains(StackTrace[Frame]) && |
| 122 | "Expected each address to have been symbolized." ); |
| 123 | for (std::string &SymbolizedFrame : SymbolizedAddrs[StackTrace[Frame]]) { |
| 124 | OS << right_justify(formatv("#{0}" , VirtualFrameNo++).str(), |
| 125 | std::log10(Depth) + 2) |
| 126 | << ' ' << SymbolizedFrame << '\n'; |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | return Result; |
| 131 | } |
| 132 | void collectStackAddresses(Instruction &I) { |
| 133 | auto &OriginStackTraces = I.getDebugLoc().getOriginStackTraces(); |
| 134 | for (auto &[Depth, StackTrace] : OriginStackTraces) { |
| 135 | for (int Frame = 0; Frame < Depth; ++Frame) { |
| 136 | void *Addr = StackTrace[Frame]; |
| 137 | if (!SymbolizedAddrs.contains(Addr)) |
| 138 | UnsymbolizedAddrs.insert(Addr); |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | #else |
| 143 | // These functions are only used in origin-tracking builds; they are no-ops in |
| 144 | // normal builds. |
| 145 | static void setDebugLocOriginCollectionForPass(StringRef PassName) {} |
| 146 | static void unsetDebugLocOriginCollection() {} |
| 147 | |
| 148 | cl::list<std::string> EnableOriginStacktraces( |
| 149 | "enable-origin-stacktraces" , |
| 150 | cl::desc("Collect DebugLoc origin stacktraces; requires " |
| 151 | "LLVM_ENABLE_DEBUGLOC_COVERAGE_TRACKING=COVERAGE_AND_ORIGIN" ), |
| 152 | cl::CommaSeparated, cl::ValueOptional, cl::Hidden, |
| 153 | cl::cb<void, std::string>([](std::string Pass) { |
| 154 | WithColor::warning() << "--enable-origin-stacktraces has no effect " |
| 155 | "without LLVM_ENABLE_DEBUGLOC_COVERAGE_TRACKING=" |
| 156 | "COVERAGE_AND_ORIGIN\n" ; |
| 157 | })); |
| 158 | |
| 159 | void collectStackAddresses(Instruction &I) {} |
| 160 | #endif // LLVM_ENABLE_DEBUGLOC_TRACKING_ORIGIN |
| 161 | |
| 162 | uint64_t getAllocSizeInBits(Module &M, Type *Ty) { |
| 163 | return Ty->isSized() ? M.getDataLayout().getTypeAllocSizeInBits(Ty) : 0; |
| 164 | } |
| 165 | |
| 166 | bool isFunctionSkipped(Function &F) { |
| 167 | return F.isDeclaration() || !F.hasExactDefinition(); |
| 168 | } |
| 169 | |
| 170 | /// Find the basic block's terminating instruction. |
| 171 | /// |
| 172 | /// Special care is needed to handle musttail and deopt calls, as these behave |
| 173 | /// like (but are in fact not) terminators. |
| 174 | Instruction *findTerminatingInstruction(BasicBlock &BB) { |
| 175 | if (auto *I = BB.getTerminatingMustTailCall()) |
| 176 | return I; |
| 177 | if (auto *I = BB.getTerminatingDeoptimizeCall()) |
| 178 | return I; |
| 179 | return BB.getTerminator(); |
| 180 | } |
| 181 | } // end anonymous namespace |
| 182 | |
| 183 | bool llvm::applyDebugifyMetadata( |
| 184 | Module &M, iterator_range<Module::iterator> Functions, StringRef Banner, |
| 185 | std::function<bool(DIBuilder &DIB, Function &F)> ApplyToMF) { |
| 186 | // Skip modules with debug info. |
| 187 | if (M.getNamedMetadata(Name: "llvm.dbg.cu" )) { |
| 188 | dbg() << Banner << "Skipping module with debug info\n" ; |
| 189 | return false; |
| 190 | } |
| 191 | |
| 192 | DIBuilder DIB(M); |
| 193 | LLVMContext &Ctx = M.getContext(); |
| 194 | auto *Int32Ty = Type::getInt32Ty(C&: Ctx); |
| 195 | |
| 196 | // Get a DIType which corresponds to Ty. |
| 197 | DenseMap<uint64_t, DIType *> TypeCache; |
| 198 | auto getCachedDIType = [&](Type *Ty) -> DIType * { |
| 199 | uint64_t Size = getAllocSizeInBits(M, Ty); |
| 200 | DIType *&DTy = TypeCache[Size]; |
| 201 | if (!DTy) { |
| 202 | std::string Name = "ty" + utostr(X: Size); |
| 203 | DTy = DIB.createBasicType(Name, SizeInBits: Size, Encoding: dwarf::DW_ATE_unsigned); |
| 204 | } |
| 205 | return DTy; |
| 206 | }; |
| 207 | |
| 208 | unsigned NextLine = 1; |
| 209 | unsigned NextVar = 1; |
| 210 | auto File = DIB.createFile(Filename: M.getName(), Directory: "/" ); |
| 211 | auto CU = DIB.createCompileUnit(Lang: DISourceLanguageName(dwarf::DW_LANG_C), File, |
| 212 | Producer: "debugify" , /*isOptimized=*/true, Flags: "" , RV: 0); |
| 213 | |
| 214 | // Visit each instruction. |
| 215 | for (Function &F : Functions) { |
| 216 | if (isFunctionSkipped(F)) |
| 217 | continue; |
| 218 | |
| 219 | bool InsertedDbgVal = false; |
| 220 | auto SPType = DIB.createSubroutineType(ParameterTypes: DIB.getOrCreateTypeArray(Elements: {})); |
| 221 | DISubprogram::DISPFlags SPFlags = |
| 222 | DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized; |
| 223 | if (F.hasPrivateLinkage() || F.hasInternalLinkage()) |
| 224 | SPFlags |= DISubprogram::SPFlagLocalToUnit; |
| 225 | auto SP = DIB.createFunction(Scope: CU, Name: F.getName(), LinkageName: F.getName(), File, LineNo: NextLine, |
| 226 | Ty: SPType, ScopeLine: NextLine, Flags: DINode::FlagZero, SPFlags, |
| 227 | TParams: nullptr, Decl: nullptr, ThrownTypes: nullptr, Annotations: nullptr, TargetFuncName: "" , |
| 228 | /*UseKeyInstructions*/ ApplyAtomGroups); |
| 229 | F.setSubprogram(SP); |
| 230 | |
| 231 | // Helper that inserts a dbg.value before \p InsertBefore, copying the |
| 232 | // location (and possibly the type, if it's non-void) from \p TemplateInst. |
| 233 | auto insertDbgVal = [&](Instruction &TemplateInst, |
| 234 | BasicBlock::iterator InsertPt) { |
| 235 | std::string Name = utostr(X: NextVar++); |
| 236 | Value *V = &TemplateInst; |
| 237 | if (TemplateInst.getType()->isVoidTy()) |
| 238 | V = ConstantInt::get(Ty: Int32Ty, V: 0); |
| 239 | const DILocation *Loc = TemplateInst.getDebugLoc().get(); |
| 240 | auto LocalVar = DIB.createAutoVariable(Scope: SP, Name, File, LineNo: Loc->getLine(), |
| 241 | Ty: getCachedDIType(V->getType()), |
| 242 | /*AlwaysPreserve=*/true); |
| 243 | DIB.insertDbgValueIntrinsic(Val: V, VarInfo: LocalVar, Expr: DIB.createExpression(), DL: Loc, |
| 244 | InsertPt); |
| 245 | }; |
| 246 | |
| 247 | for (BasicBlock &BB : F) { |
| 248 | // Attach debug locations. |
| 249 | for (Instruction &I : BB) { |
| 250 | uint64_t AtomGroup = ApplyAtomGroups ? NextLine : 0; |
| 251 | uint8_t AtomRank = ApplyAtomGroups ? 1 : 0; |
| 252 | uint64_t Line = NextLine++; |
| 253 | I.setDebugLoc(DILocation::get(Context&: Ctx, Line, Column: 1, Scope: SP, InlinedAt: nullptr, ImplicitCode: false, |
| 254 | AtomGroup, AtomRank)); |
| 255 | } |
| 256 | |
| 257 | if (DebugifyLevel < Level::LocationsAndVariables) |
| 258 | continue; |
| 259 | |
| 260 | // Inserting debug values into EH pads can break IR invariants. |
| 261 | if (BB.isEHPad()) |
| 262 | continue; |
| 263 | |
| 264 | // Find the terminating instruction, after which no debug values are |
| 265 | // attached. |
| 266 | Instruction *LastInst = findTerminatingInstruction(BB); |
| 267 | assert(LastInst && "Expected basic block with a terminator" ); |
| 268 | |
| 269 | // Maintain an insertion point which can't be invalidated when updates |
| 270 | // are made. |
| 271 | BasicBlock::iterator InsertPt = BB.getFirstInsertionPt(); |
| 272 | assert(InsertPt != BB.end() && "Expected to find an insertion point" ); |
| 273 | |
| 274 | // Insert after existing debug values to preserve order. |
| 275 | InsertPt.setHeadBit(false); |
| 276 | |
| 277 | // Attach debug values. |
| 278 | for (Instruction *I = &*BB.begin(); I != LastInst; I = I->getNextNode()) { |
| 279 | // Skip void-valued instructions. |
| 280 | if (I->getType()->isVoidTy()) |
| 281 | continue; |
| 282 | |
| 283 | // Phis and EH pads must be grouped at the beginning of the block. |
| 284 | // Only advance the insertion point when we finish visiting these. |
| 285 | if (!isa<PHINode>(Val: I) && !I->isEHPad()) |
| 286 | InsertPt = std::next(x: I->getIterator()); |
| 287 | |
| 288 | insertDbgVal(*I, InsertPt); |
| 289 | InsertedDbgVal = true; |
| 290 | } |
| 291 | } |
| 292 | // Make sure we emit at least one dbg.value, otherwise MachineDebugify may |
| 293 | // not have anything to work with as it goes about inserting DBG_VALUEs. |
| 294 | // (It's common for MIR tests to be written containing skeletal IR with |
| 295 | // empty functions -- we're still interested in debugifying the MIR within |
| 296 | // those tests, and this helps with that.) |
| 297 | if (DebugifyLevel == Level::LocationsAndVariables && !InsertedDbgVal) { |
| 298 | auto *Term = findTerminatingInstruction(BB&: F.getEntryBlock()); |
| 299 | insertDbgVal(*Term, Term->getIterator()); |
| 300 | } |
| 301 | if (ApplyToMF) |
| 302 | ApplyToMF(DIB, F); |
| 303 | } |
| 304 | DIB.finalize(); |
| 305 | |
| 306 | // Track the number of distinct lines and variables. |
| 307 | NamedMDNode *NMD = M.getOrInsertNamedMetadata(Name: "llvm.debugify" ); |
| 308 | auto addDebugifyOperand = [&](unsigned N) { |
| 309 | NMD->addOperand(M: MDNode::get( |
| 310 | Context&: Ctx, MDs: ValueAsMetadata::getConstant(C: ConstantInt::get(Ty: Int32Ty, V: N)))); |
| 311 | }; |
| 312 | addDebugifyOperand(NextLine - 1); // Original number of lines. |
| 313 | addDebugifyOperand(NextVar - 1); // Original number of variables. |
| 314 | assert(NMD->getNumOperands() == 2 && |
| 315 | "llvm.debugify should have exactly 2 operands!" ); |
| 316 | |
| 317 | // Claim that this synthetic debug info is valid. |
| 318 | StringRef DIVersionKey = "Debug Info Version" ; |
| 319 | if (!M.getModuleFlag(Key: DIVersionKey)) |
| 320 | M.addModuleFlag(Behavior: Module::Warning, Key: DIVersionKey, Val: DEBUG_METADATA_VERSION); |
| 321 | |
| 322 | return true; |
| 323 | } |
| 324 | |
| 325 | static bool applyDebugify(Function &F, enum DebugifyMode Mode, |
| 326 | DebugInfoPerPass *DebugInfoBeforePass, |
| 327 | StringRef NameOfWrappedPass = "" ) { |
| 328 | setDebugLocOriginCollectionForPass(NameOfWrappedPass); |
| 329 | Module &M = *F.getParent(); |
| 330 | auto FuncIt = F.getIterator(); |
| 331 | if (Mode == DebugifyMode::SyntheticDebugInfo) |
| 332 | return applyDebugifyMetadata(M, Functions: make_range(x: FuncIt, y: std::next(x: FuncIt)), |
| 333 | Banner: "FunctionDebugify: " , /*ApplyToMF*/ nullptr); |
| 334 | assert(DebugInfoBeforePass && "Missing debug info metadata" ); |
| 335 | return collectDebugInfoMetadata(M, Functions: M.functions(), DebugInfoBeforePass&: *DebugInfoBeforePass, |
| 336 | Banner: "FunctionDebugify (original debuginfo)" , |
| 337 | NameOfWrappedPass); |
| 338 | } |
| 339 | |
| 340 | static bool applyDebugify(Module &M, enum DebugifyMode Mode, |
| 341 | DebugInfoPerPass *DebugInfoBeforePass, |
| 342 | StringRef NameOfWrappedPass = "" ) { |
| 343 | setDebugLocOriginCollectionForPass(NameOfWrappedPass); |
| 344 | if (Mode == DebugifyMode::SyntheticDebugInfo) |
| 345 | return applyDebugifyMetadata(M, Functions: M.functions(), |
| 346 | Banner: "ModuleDebugify: " , /*ApplyToMF*/ nullptr); |
| 347 | assert(DebugInfoBeforePass && "Missing debug info metadata" ); |
| 348 | return collectDebugInfoMetadata(M, Functions: M.functions(), DebugInfoBeforePass&: *DebugInfoBeforePass, |
| 349 | Banner: "ModuleDebugify (original debuginfo)" , |
| 350 | NameOfWrappedPass); |
| 351 | } |
| 352 | |
| 353 | bool llvm::stripDebugifyMetadata(Module &M) { |
| 354 | bool Changed = false; |
| 355 | |
| 356 | // Remove the llvm.debugify and llvm.mir.debugify module-level named metadata. |
| 357 | NamedMDNode *DebugifyMD = M.getNamedMetadata(Name: "llvm.debugify" ); |
| 358 | if (DebugifyMD) { |
| 359 | M.eraseNamedMetadata(NMD: DebugifyMD); |
| 360 | Changed = true; |
| 361 | } |
| 362 | |
| 363 | if (auto *MIRDebugifyMD = M.getNamedMetadata(Name: "llvm.mir.debugify" )) { |
| 364 | M.eraseNamedMetadata(NMD: MIRDebugifyMD); |
| 365 | Changed = true; |
| 366 | } |
| 367 | |
| 368 | // Strip out all debug intrinsics and supporting metadata (subprograms, types, |
| 369 | // variables, etc). |
| 370 | Changed |= StripDebugInfo(M); |
| 371 | |
| 372 | // Strip out the dead dbg.value prototype. |
| 373 | Function *DbgValF = M.getFunction(Name: "llvm.dbg.value" ); |
| 374 | if (DbgValF) { |
| 375 | assert(DbgValF->isDeclaration() && DbgValF->use_empty() && |
| 376 | "Not all debug info stripped?" ); |
| 377 | DbgValF->eraseFromParent(); |
| 378 | Changed = true; |
| 379 | } |
| 380 | |
| 381 | // Strip out the module-level Debug Info Version metadata. |
| 382 | // FIXME: There must be an easier way to remove an operand from a NamedMDNode. |
| 383 | NamedMDNode *NMD = M.getModuleFlagsMetadata(); |
| 384 | if (!NMD) |
| 385 | return Changed; |
| 386 | SmallVector<MDNode *, 4> Flags(NMD->operands()); |
| 387 | NMD->clearOperands(); |
| 388 | for (MDNode *Flag : Flags) { |
| 389 | auto *Key = cast<MDString>(Val: Flag->getOperand(I: 1)); |
| 390 | if (Key->getString() == "Debug Info Version" ) { |
| 391 | Changed = true; |
| 392 | continue; |
| 393 | } |
| 394 | NMD->addOperand(M: Flag); |
| 395 | } |
| 396 | // If we left it empty we might as well remove it. |
| 397 | if (NMD->getNumOperands() == 0) |
| 398 | NMD->eraseFromParent(); |
| 399 | |
| 400 | return Changed; |
| 401 | } |
| 402 | |
| 403 | bool hasLoc(const Instruction &I) { |
| 404 | const DILocation *Loc = I.getDebugLoc().get(); |
| 405 | #if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE |
| 406 | DebugLocKind Kind = I.getDebugLoc().getKind(); |
| 407 | return Loc || Kind != DebugLocKind::Normal; |
| 408 | #else |
| 409 | return Loc; |
| 410 | #endif |
| 411 | } |
| 412 | |
| 413 | bool llvm::collectDebugInfoMetadata(Module &M, |
| 414 | iterator_range<Module::iterator> Functions, |
| 415 | DebugInfoPerPass &DebugInfoBeforePass, |
| 416 | StringRef Banner, |
| 417 | StringRef NameOfWrappedPass) { |
| 418 | LLVM_DEBUG(dbgs() << Banner << ": (before) " << NameOfWrappedPass << '\n'); |
| 419 | |
| 420 | if (!M.getNamedMetadata(Name: "llvm.dbg.cu" )) { |
| 421 | dbg() << Banner << ": Skipping module without debug info\n" ; |
| 422 | return false; |
| 423 | } |
| 424 | |
| 425 | uint64_t FunctionsCnt = DebugInfoBeforePass.DIFunctions.size(); |
| 426 | // Visit each instruction. |
| 427 | for (Function &F : Functions) { |
| 428 | // Use DI collected after previous Pass (when -debugify-each is used). |
| 429 | if (DebugInfoBeforePass.DIFunctions.count(Key: &F)) |
| 430 | continue; |
| 431 | |
| 432 | if (isFunctionSkipped(F)) |
| 433 | continue; |
| 434 | |
| 435 | // Stop collecting DI if the Functions number reached the limit. |
| 436 | if (++FunctionsCnt >= DebugifyFunctionsLimit) |
| 437 | break; |
| 438 | // Collect the DISubprogram. |
| 439 | auto *SP = F.getSubprogram(); |
| 440 | DebugInfoBeforePass.DIFunctions.insert(KV: {&F, SP}); |
| 441 | if (SP) { |
| 442 | LLVM_DEBUG(dbgs() << " Collecting subprogram: " << *SP << '\n'); |
| 443 | for (const DINode *DN : SP->getRetainedNodes()) { |
| 444 | if (const auto *DV = dyn_cast<DILocalVariable>(Val: DN)) { |
| 445 | DebugInfoBeforePass.DIVariables[DV] = 0; |
| 446 | } |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | for (BasicBlock &BB : F) { |
| 451 | // Collect debug locations (!dbg) and debug variable intrinsics. |
| 452 | for (Instruction &I : BB) { |
| 453 | // Skip PHIs. |
| 454 | if (isa<PHINode>(Val: I)) |
| 455 | continue; |
| 456 | |
| 457 | // Cllect dbg.values and dbg.declare. |
| 458 | if (DebugifyLevel > Level::Locations) { |
| 459 | auto HandleDbgVariable = [&](DbgVariableRecord *DbgVar) { |
| 460 | if (!SP) |
| 461 | return; |
| 462 | // Skip inlined variables. |
| 463 | if (DbgVar->getDebugLoc().getInlinedAt()) |
| 464 | return; |
| 465 | // Skip undef values. |
| 466 | if (DbgVar->isKillLocation()) |
| 467 | return; |
| 468 | |
| 469 | auto *Var = DbgVar->getVariable(); |
| 470 | DebugInfoBeforePass.DIVariables[Var]++; |
| 471 | }; |
| 472 | for (DbgVariableRecord &DVR : filterDbgVars(R: I.getDbgRecordRange())) |
| 473 | HandleDbgVariable(&DVR); |
| 474 | } |
| 475 | |
| 476 | LLVM_DEBUG(dbgs() << " Collecting info for inst: " << I << '\n'); |
| 477 | DebugInfoBeforePass.InstToDelete.insert(KV: {&I, &I}); |
| 478 | |
| 479 | // Track the addresses to symbolize, if the feature is enabled. |
| 480 | collectStackAddresses(I); |
| 481 | DebugInfoBeforePass.DILocations.insert(KV: {&I, hasLoc(I)}); |
| 482 | } |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | return true; |
| 487 | } |
| 488 | |
| 489 | // This checks the preservation of original debug info attached to functions. |
| 490 | static bool checkFunctions(const DebugFnMap &DIFunctionsBefore, |
| 491 | const DebugFnMap &DIFunctionsAfter, |
| 492 | StringRef NameOfWrappedPass, |
| 493 | StringRef FileNameFromCU, bool ShouldWriteIntoJSON, |
| 494 | llvm::json::Array &Bugs) { |
| 495 | bool Preserved = true; |
| 496 | for (const auto &F : DIFunctionsAfter) { |
| 497 | if (F.second) |
| 498 | continue; |
| 499 | auto SPIt = DIFunctionsBefore.find(Key: F.first); |
| 500 | if (SPIt == DIFunctionsBefore.end()) { |
| 501 | if (ShouldWriteIntoJSON) |
| 502 | Bugs.push_back(E: llvm::json::Object({{.K: "metadata" , .V: "DISubprogram" }, |
| 503 | {.K: "name" , .V: F.first->getName()}, |
| 504 | {.K: "action" , .V: "not-generate" }})); |
| 505 | else |
| 506 | dbg() << "ERROR: " << NameOfWrappedPass |
| 507 | << " did not generate DISubprogram for " << F.first->getName() |
| 508 | << " from " << FileNameFromCU << '\n'; |
| 509 | Preserved = false; |
| 510 | } else { |
| 511 | auto SP = SPIt->second; |
| 512 | if (!SP) |
| 513 | continue; |
| 514 | // If the function had the SP attached before the pass, consider it as |
| 515 | // a debug info bug. |
| 516 | if (ShouldWriteIntoJSON) |
| 517 | Bugs.push_back(E: llvm::json::Object({{.K: "metadata" , .V: "DISubprogram" }, |
| 518 | {.K: "name" , .V: F.first->getName()}, |
| 519 | {.K: "action" , .V: "drop" }})); |
| 520 | else |
| 521 | dbg() << "ERROR: " << NameOfWrappedPass << " dropped DISubprogram of " |
| 522 | << F.first->getName() << " from " << FileNameFromCU << '\n'; |
| 523 | Preserved = false; |
| 524 | } |
| 525 | } |
| 526 | |
| 527 | return Preserved; |
| 528 | } |
| 529 | |
| 530 | // This checks the preservation of the original debug info attached to |
| 531 | // instructions. |
| 532 | static bool checkInstructions(const DebugInstMap &DILocsBefore, |
| 533 | const DebugInstMap &DILocsAfter, |
| 534 | const WeakInstValueMap &InstToDelete, |
| 535 | StringRef NameOfWrappedPass, |
| 536 | StringRef FileNameFromCU, |
| 537 | bool ShouldWriteIntoJSON, |
| 538 | llvm::json::Array &Bugs) { |
| 539 | bool Preserved = true; |
| 540 | for (const auto &L : DILocsAfter) { |
| 541 | if (L.second) |
| 542 | continue; |
| 543 | auto Instr = L.first; |
| 544 | |
| 545 | // In order to avoid pointer reuse/recycling, skip the values that might |
| 546 | // have been deleted during a pass. |
| 547 | auto WeakInstrPtr = InstToDelete.find(Key: Instr); |
| 548 | if (WeakInstrPtr != InstToDelete.end() && !WeakInstrPtr->second) |
| 549 | continue; |
| 550 | |
| 551 | auto FnName = Instr->getFunction()->getName(); |
| 552 | auto BB = Instr->getParent(); |
| 553 | auto BBName = BB->hasName() ? BB->getName() : "no-name" ; |
| 554 | auto InstName = Instruction::getOpcodeName(Opcode: Instr->getOpcode()); |
| 555 | |
| 556 | auto CreateJSONBugEntry = [&](const char *Action) { |
| 557 | auto BugEntry = llvm::json::Object({ |
| 558 | {.K: "metadata" , .V: "DILocation" }, |
| 559 | {.K: "fn-name" , .V: FnName.str()}, |
| 560 | {.K: "bb-name" , .V: BBName.str()}, |
| 561 | {.K: "instr" , .V: InstName}, |
| 562 | {.K: "action" , .V: Action}, |
| 563 | }); |
| 564 | #if LLVM_ENABLE_DEBUGLOC_TRACKING_ORIGIN |
| 565 | if (!Instr->getDebugLoc().getOriginStackTraces().empty()) |
| 566 | BugEntry.insert({"origin" , symbolizeStackTrace(Instr)}); |
| 567 | #endif |
| 568 | Bugs.push_back(E: std::move(BugEntry)); |
| 569 | }; |
| 570 | |
| 571 | auto InstrIt = DILocsBefore.find(Key: Instr); |
| 572 | if (InstrIt == DILocsBefore.end()) { |
| 573 | if (ShouldWriteIntoJSON) |
| 574 | CreateJSONBugEntry("not-generate" ); |
| 575 | else |
| 576 | dbg() << "WARNING: " << NameOfWrappedPass |
| 577 | << " did not generate DILocation for " << *Instr |
| 578 | << " (BB: " << BBName << ", Fn: " << FnName |
| 579 | << ", File: " << FileNameFromCU << ")\n" ; |
| 580 | Preserved = false; |
| 581 | } else { |
| 582 | if (!InstrIt->second) |
| 583 | continue; |
| 584 | // If the instr had the !dbg attached before the pass, consider it as |
| 585 | // a debug info issue. |
| 586 | if (ShouldWriteIntoJSON) |
| 587 | CreateJSONBugEntry("drop" ); |
| 588 | else |
| 589 | dbg() << "WARNING: " << NameOfWrappedPass << " dropped DILocation of " |
| 590 | << *Instr << " (BB: " << BBName << ", Fn: " << FnName |
| 591 | << ", File: " << FileNameFromCU << ")\n" ; |
| 592 | Preserved = false; |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | return Preserved; |
| 597 | } |
| 598 | |
| 599 | // This checks the preservation of original debug variable intrinsics. |
| 600 | static bool checkVars(const DebugVarMap &DIVarsBefore, |
| 601 | const DebugVarMap &DIVarsAfter, |
| 602 | StringRef NameOfWrappedPass, StringRef FileNameFromCU, |
| 603 | bool ShouldWriteIntoJSON, llvm::json::Array &Bugs) { |
| 604 | bool Preserved = true; |
| 605 | for (const auto &V : DIVarsBefore) { |
| 606 | auto VarIt = DIVarsAfter.find(Key: V.first); |
| 607 | if (VarIt == DIVarsAfter.end()) |
| 608 | continue; |
| 609 | |
| 610 | unsigned NumOfDbgValsAfter = VarIt->second; |
| 611 | |
| 612 | if (V.second > NumOfDbgValsAfter) { |
| 613 | if (ShouldWriteIntoJSON) |
| 614 | Bugs.push_back(E: llvm::json::Object( |
| 615 | {{.K: "metadata" , .V: "dbg-var-intrinsic" }, |
| 616 | {.K: "name" , .V: V.first->getName()}, |
| 617 | {.K: "fn-name" , .V: V.first->getScope()->getSubprogram()->getName()}, |
| 618 | {.K: "action" , .V: "drop" }})); |
| 619 | else |
| 620 | dbg() << "WARNING: " << NameOfWrappedPass |
| 621 | << " drops dbg.value()/dbg.declare() for " << V.first->getName() |
| 622 | << " from " |
| 623 | << "function " << V.first->getScope()->getSubprogram()->getName() |
| 624 | << " (file " << FileNameFromCU << ")\n" ; |
| 625 | Preserved = false; |
| 626 | } |
| 627 | } |
| 628 | |
| 629 | return Preserved; |
| 630 | } |
| 631 | |
| 632 | // Write the json data into the specifed file. |
| 633 | static void writeJSON(StringRef OrigDIVerifyBugsReportFilePath, |
| 634 | StringRef FileNameFromCU, StringRef NameOfWrappedPass, |
| 635 | llvm::json::Array &Bugs) { |
| 636 | std::error_code EC; |
| 637 | raw_fd_ostream OS_FILE{OrigDIVerifyBugsReportFilePath, EC, |
| 638 | sys::fs::OF_Append | sys::fs::OF_TextWithCRLF}; |
| 639 | if (EC) { |
| 640 | errs() << "Could not open file: " << EC.message() << ", " |
| 641 | << OrigDIVerifyBugsReportFilePath << '\n'; |
| 642 | return; |
| 643 | } |
| 644 | |
| 645 | if (auto L = OS_FILE.lock()) { |
| 646 | OS_FILE << "{\"file\":\"" << FileNameFromCU << "\", " ; |
| 647 | |
| 648 | StringRef PassName = |
| 649 | NameOfWrappedPass != "" ? NameOfWrappedPass : "no-name" ; |
| 650 | OS_FILE << "\"pass\":\"" << PassName << "\", " ; |
| 651 | |
| 652 | llvm::json::Value BugsToPrint{std::move(Bugs)}; |
| 653 | OS_FILE << "\"bugs\": " << BugsToPrint; |
| 654 | |
| 655 | OS_FILE << "}\n" ; |
| 656 | } |
| 657 | OS_FILE.close(); |
| 658 | } |
| 659 | |
| 660 | bool llvm::checkDebugInfoMetadata(Module &M, |
| 661 | iterator_range<Module::iterator> Functions, |
| 662 | DebugInfoPerPass &DebugInfoBeforePass, |
| 663 | StringRef Banner, StringRef NameOfWrappedPass, |
| 664 | StringRef OrigDIVerifyBugsReportFilePath) { |
| 665 | LLVM_DEBUG(dbgs() << Banner << ": (after) " << NameOfWrappedPass << '\n'); |
| 666 | unsetDebugLocOriginCollection(); |
| 667 | |
| 668 | if (!M.getNamedMetadata(Name: "llvm.dbg.cu" )) { |
| 669 | dbg() << Banner << ": Skipping module without debug info\n" ; |
| 670 | return false; |
| 671 | } |
| 672 | |
| 673 | // Map the debug info holding DIs after a pass. |
| 674 | DebugInfoPerPass DebugInfoAfterPass; |
| 675 | |
| 676 | // Visit each instruction. |
| 677 | for (Function &F : Functions) { |
| 678 | if (isFunctionSkipped(F)) |
| 679 | continue; |
| 680 | |
| 681 | // Don't process functions without DI collected before the Pass. |
| 682 | if (!DebugInfoBeforePass.DIFunctions.count(Key: &F)) |
| 683 | continue; |
| 684 | // TODO: Collect metadata other than DISubprograms. |
| 685 | // Collect the DISubprogram. |
| 686 | auto *SP = F.getSubprogram(); |
| 687 | DebugInfoAfterPass.DIFunctions.insert(KV: {&F, SP}); |
| 688 | |
| 689 | if (SP) { |
| 690 | LLVM_DEBUG(dbgs() << " Collecting subprogram: " << *SP << '\n'); |
| 691 | for (const DINode *DN : SP->getRetainedNodes()) { |
| 692 | if (const auto *DV = dyn_cast<DILocalVariable>(Val: DN)) { |
| 693 | DebugInfoAfterPass.DIVariables[DV] = 0; |
| 694 | } |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | for (BasicBlock &BB : F) { |
| 699 | // Collect debug locations (!dbg) and debug variable intrinsics. |
| 700 | for (Instruction &I : BB) { |
| 701 | // Skip PHIs. |
| 702 | if (isa<PHINode>(Val: I)) |
| 703 | continue; |
| 704 | |
| 705 | // Collect dbg.values and dbg.declares. |
| 706 | if (DebugifyLevel > Level::Locations) { |
| 707 | auto HandleDbgVariable = [&](DbgVariableRecord *DbgVar) { |
| 708 | if (!SP) |
| 709 | return; |
| 710 | // Skip inlined variables. |
| 711 | if (DbgVar->getDebugLoc().getInlinedAt()) |
| 712 | return; |
| 713 | // Skip undef values. |
| 714 | if (DbgVar->isKillLocation()) |
| 715 | return; |
| 716 | |
| 717 | auto *Var = DbgVar->getVariable(); |
| 718 | DebugInfoAfterPass.DIVariables[Var]++; |
| 719 | }; |
| 720 | for (DbgVariableRecord &DVR : filterDbgVars(R: I.getDbgRecordRange())) |
| 721 | HandleDbgVariable(&DVR); |
| 722 | } |
| 723 | |
| 724 | LLVM_DEBUG(dbgs() << " Collecting info for inst: " << I << '\n'); |
| 725 | |
| 726 | // Track the addresses to symbolize, if the feature is enabled. |
| 727 | collectStackAddresses(I); |
| 728 | DebugInfoAfterPass.DILocations.insert(KV: {&I, hasLoc(I)}); |
| 729 | } |
| 730 | } |
| 731 | } |
| 732 | |
| 733 | // TODO: The name of the module could be read better? |
| 734 | StringRef FileNameFromCU = |
| 735 | (cast<DICompileUnit>(Val: M.getNamedMetadata(Name: "llvm.dbg.cu" )->getOperand(i: 0))) |
| 736 | ->getFilename(); |
| 737 | |
| 738 | auto DIFunctionsBefore = DebugInfoBeforePass.DIFunctions; |
| 739 | auto DIFunctionsAfter = DebugInfoAfterPass.DIFunctions; |
| 740 | |
| 741 | auto DILocsBefore = DebugInfoBeforePass.DILocations; |
| 742 | auto DILocsAfter = DebugInfoAfterPass.DILocations; |
| 743 | |
| 744 | auto InstToDelete = DebugInfoBeforePass.InstToDelete; |
| 745 | |
| 746 | auto DIVarsBefore = DebugInfoBeforePass.DIVariables; |
| 747 | auto DIVarsAfter = DebugInfoAfterPass.DIVariables; |
| 748 | |
| 749 | bool ShouldWriteIntoJSON = !OrigDIVerifyBugsReportFilePath.empty(); |
| 750 | llvm::json::Array Bugs; |
| 751 | |
| 752 | bool ResultForFunc = |
| 753 | checkFunctions(DIFunctionsBefore, DIFunctionsAfter, NameOfWrappedPass, |
| 754 | FileNameFromCU, ShouldWriteIntoJSON, Bugs); |
| 755 | bool ResultForInsts = checkInstructions( |
| 756 | DILocsBefore, DILocsAfter, InstToDelete, NameOfWrappedPass, |
| 757 | FileNameFromCU, ShouldWriteIntoJSON, Bugs); |
| 758 | |
| 759 | #if LLVM_ENABLE_DEBUGLOC_TRACKING_COVERAGE |
| 760 | // If we are tracking DebugLoc coverage, replace each empty DebugLoc with an |
| 761 | // annotated location now so that it does not show up in future passes even if |
| 762 | // it is propagated to other instructions. |
| 763 | for (auto &L : DILocsAfter) |
| 764 | if (!L.second) |
| 765 | const_cast<Instruction *>(L.first)->setDebugLoc(DebugLoc::getUnknown()); |
| 766 | #endif |
| 767 | |
| 768 | bool ResultForVars = checkVars(DIVarsBefore, DIVarsAfter, NameOfWrappedPass, |
| 769 | FileNameFromCU, ShouldWriteIntoJSON, Bugs); |
| 770 | |
| 771 | bool Result = ResultForFunc && ResultForInsts && ResultForVars; |
| 772 | |
| 773 | StringRef ResultBanner = NameOfWrappedPass != "" ? NameOfWrappedPass : Banner; |
| 774 | if (ShouldWriteIntoJSON && !Bugs.empty()) |
| 775 | writeJSON(OrigDIVerifyBugsReportFilePath, FileNameFromCU, NameOfWrappedPass, |
| 776 | Bugs); |
| 777 | |
| 778 | if (Result) |
| 779 | dbg() << ResultBanner << ": PASS\n" ; |
| 780 | else |
| 781 | dbg() << ResultBanner << ": FAIL\n" ; |
| 782 | |
| 783 | // In the case of the `debugify-each`, no need to go over all the instructions |
| 784 | // again in the collectDebugInfoMetadata(), since as an input we can use |
| 785 | // the debugging information from the previous pass. |
| 786 | DebugInfoBeforePass = DebugInfoAfterPass; |
| 787 | |
| 788 | LLVM_DEBUG(dbgs() << "\n\n" ); |
| 789 | return Result; |
| 790 | } |
| 791 | |
| 792 | namespace { |
| 793 | /// Return true if a mis-sized diagnostic is issued for \p DbgVal. |
| 794 | template <typename DbgValTy> |
| 795 | bool diagnoseMisSizedDbgValue(Module &M, DbgValTy *DbgVal) { |
| 796 | // The size of a dbg.value's value operand should match the size of the |
| 797 | // variable it corresponds to. |
| 798 | // |
| 799 | // TODO: This, along with a check for non-null value operands, should be |
| 800 | // promoted to verifier failures. |
| 801 | |
| 802 | // For now, don't try to interpret anything more complicated than an empty |
| 803 | // DIExpression. Eventually we should try to handle OP_deref and fragments. |
| 804 | if (DbgVal->getExpression()->getNumElements()) |
| 805 | return false; |
| 806 | |
| 807 | Value *V = DbgVal->getVariableLocationOp(0); |
| 808 | if (!V) |
| 809 | return false; |
| 810 | |
| 811 | Type *Ty = V->getType(); |
| 812 | uint64_t ValueOperandSize = getAllocSizeInBits(M, Ty); |
| 813 | std::optional<uint64_t> DbgVarSize = DbgVal->getFragmentSizeInBits(); |
| 814 | if (!ValueOperandSize || !DbgVarSize) |
| 815 | return false; |
| 816 | |
| 817 | bool HasBadSize = false; |
| 818 | if (Ty->isIntegerTy()) { |
| 819 | auto Signedness = DbgVal->getVariable()->getSignedness(); |
| 820 | if (Signedness == DIBasicType::Signedness::Signed) |
| 821 | HasBadSize = ValueOperandSize < *DbgVarSize; |
| 822 | } else { |
| 823 | HasBadSize = ValueOperandSize != *DbgVarSize; |
| 824 | } |
| 825 | |
| 826 | if (HasBadSize) { |
| 827 | dbg() << "ERROR: dbg.value operand has size " << ValueOperandSize |
| 828 | << ", but its variable has size " << *DbgVarSize << ": " ; |
| 829 | DbgVal->print(dbg()); |
| 830 | dbg() << "\n" ; |
| 831 | } |
| 832 | return HasBadSize; |
| 833 | } |
| 834 | |
| 835 | bool checkDebugifyMetadata(Module &M, |
| 836 | iterator_range<Module::iterator> Functions, |
| 837 | StringRef NameOfWrappedPass, StringRef Banner, |
| 838 | bool Strip, DebugifyStatsMap *StatsMap) { |
| 839 | // Skip modules without debugify metadata. |
| 840 | NamedMDNode *NMD = M.getNamedMetadata(Name: "llvm.debugify" ); |
| 841 | unsetDebugLocOriginCollection(); |
| 842 | if (!NMD) { |
| 843 | dbg() << Banner << ": Skipping module without debugify metadata\n" ; |
| 844 | return false; |
| 845 | } |
| 846 | |
| 847 | auto getDebugifyOperand = [&](unsigned Idx) -> unsigned { |
| 848 | return mdconst::extract<ConstantInt>(MD: NMD->getOperand(i: Idx)->getOperand(I: 0)) |
| 849 | ->getZExtValue(); |
| 850 | }; |
| 851 | assert(NMD->getNumOperands() == 2 && |
| 852 | "llvm.debugify should have exactly 2 operands!" ); |
| 853 | unsigned OriginalNumLines = getDebugifyOperand(0); |
| 854 | unsigned OriginalNumVars = getDebugifyOperand(1); |
| 855 | bool HasErrors = false; |
| 856 | |
| 857 | // Track debug info loss statistics if able. |
| 858 | DebugifyStatistics *Stats = nullptr; |
| 859 | if (StatsMap && !NameOfWrappedPass.empty()) |
| 860 | Stats = &StatsMap->operator[](Key: NameOfWrappedPass); |
| 861 | |
| 862 | BitVector MissingLines{OriginalNumLines, true}; |
| 863 | BitVector MissingVars{OriginalNumVars, true}; |
| 864 | for (Function &F : Functions) { |
| 865 | if (isFunctionSkipped(F)) |
| 866 | continue; |
| 867 | |
| 868 | // Find missing lines. |
| 869 | for (Instruction &I : instructions(F)) { |
| 870 | auto DL = I.getDebugLoc(); |
| 871 | if (DL && DL.getLine() != 0) { |
| 872 | MissingLines.reset(Idx: DL.getLine() - 1); |
| 873 | continue; |
| 874 | } |
| 875 | |
| 876 | if (!isa<PHINode>(Val: &I) && !DL) { |
| 877 | dbg() << "WARNING: Instruction with empty DebugLoc in function " ; |
| 878 | dbg() << F.getName() << " --" ; |
| 879 | I.print(O&: dbg()); |
| 880 | dbg() << "\n" ; |
| 881 | } |
| 882 | } |
| 883 | |
| 884 | // Find missing variables and mis-sized debug values. |
| 885 | auto CheckForMisSized = [&](auto *DbgVal) { |
| 886 | unsigned Var = ~0U; |
| 887 | (void)to_integer(DbgVal->getVariable()->getName(), Var, 10); |
| 888 | assert(Var <= OriginalNumVars && "Unexpected name for DILocalVariable" ); |
| 889 | bool HasBadSize = diagnoseMisSizedDbgValue(M, DbgVal); |
| 890 | if (!HasBadSize) |
| 891 | MissingVars.reset(Idx: Var - 1); |
| 892 | HasErrors |= HasBadSize; |
| 893 | }; |
| 894 | for (Instruction &I : instructions(F)) { |
| 895 | for (DbgVariableRecord &DVR : filterDbgVars(R: I.getDbgRecordRange())) |
| 896 | if (DVR.isDbgValue() || DVR.isDbgAssign()) |
| 897 | CheckForMisSized(&DVR); |
| 898 | } |
| 899 | } |
| 900 | |
| 901 | // Print the results. |
| 902 | for (unsigned Idx : MissingLines.set_bits()) |
| 903 | dbg() << "WARNING: Missing line " << Idx + 1 << "\n" ; |
| 904 | |
| 905 | for (unsigned Idx : MissingVars.set_bits()) |
| 906 | dbg() << "WARNING: Missing variable " << Idx + 1 << "\n" ; |
| 907 | |
| 908 | // Update DI loss statistics. |
| 909 | if (Stats) { |
| 910 | Stats->NumDbgLocsExpected += OriginalNumLines; |
| 911 | Stats->NumDbgLocsMissing += MissingLines.count(); |
| 912 | Stats->NumDbgValuesExpected += OriginalNumVars; |
| 913 | Stats->NumDbgValuesMissing += MissingVars.count(); |
| 914 | } |
| 915 | |
| 916 | dbg() << Banner; |
| 917 | if (!NameOfWrappedPass.empty()) |
| 918 | dbg() << " [" << NameOfWrappedPass << "]" ; |
| 919 | dbg() << ": " << (HasErrors ? "FAIL" : "PASS" ) << '\n'; |
| 920 | |
| 921 | // Strip debugify metadata if required. |
| 922 | bool Ret = false; |
| 923 | if (Strip) |
| 924 | Ret = stripDebugifyMetadata(M); |
| 925 | |
| 926 | return Ret; |
| 927 | } |
| 928 | |
| 929 | /// ModulePass for attaching synthetic debug info to everything, used with the |
| 930 | /// legacy module pass manager. |
| 931 | struct DebugifyModulePass : public ModulePass { |
| 932 | bool runOnModule(Module &M) override { |
| 933 | bool Result = |
| 934 | applyDebugify(M, Mode, DebugInfoBeforePass, NameOfWrappedPass); |
| 935 | return Result; |
| 936 | } |
| 937 | |
| 938 | DebugifyModulePass(enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo, |
| 939 | StringRef NameOfWrappedPass = "" , |
| 940 | DebugInfoPerPass *DebugInfoBeforePass = nullptr) |
| 941 | : ModulePass(ID), NameOfWrappedPass(NameOfWrappedPass), |
| 942 | DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode) {} |
| 943 | |
| 944 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 945 | AU.setPreservesAll(); |
| 946 | } |
| 947 | |
| 948 | static char ID; // Pass identification. |
| 949 | |
| 950 | private: |
| 951 | StringRef NameOfWrappedPass; |
| 952 | DebugInfoPerPass *DebugInfoBeforePass; |
| 953 | enum DebugifyMode Mode; |
| 954 | }; |
| 955 | |
| 956 | /// FunctionPass for attaching synthetic debug info to instructions within a |
| 957 | /// single function, used with the legacy module pass manager. |
| 958 | struct DebugifyFunctionPass : public FunctionPass { |
| 959 | bool runOnFunction(Function &F) override { |
| 960 | bool Result = |
| 961 | applyDebugify(F, Mode, DebugInfoBeforePass, NameOfWrappedPass); |
| 962 | return Result; |
| 963 | } |
| 964 | |
| 965 | DebugifyFunctionPass( |
| 966 | enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo, |
| 967 | StringRef NameOfWrappedPass = "" , |
| 968 | DebugInfoPerPass *DebugInfoBeforePass = nullptr) |
| 969 | : FunctionPass(ID), NameOfWrappedPass(NameOfWrappedPass), |
| 970 | DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode) {} |
| 971 | |
| 972 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 973 | AU.setPreservesAll(); |
| 974 | } |
| 975 | |
| 976 | static char ID; // Pass identification. |
| 977 | |
| 978 | private: |
| 979 | StringRef NameOfWrappedPass; |
| 980 | DebugInfoPerPass *DebugInfoBeforePass; |
| 981 | enum DebugifyMode Mode; |
| 982 | }; |
| 983 | |
| 984 | /// ModulePass for checking debug info inserted by -debugify, used with the |
| 985 | /// legacy module pass manager. |
| 986 | struct CheckDebugifyModulePass : public ModulePass { |
| 987 | bool runOnModule(Module &M) override { |
| 988 | bool Result; |
| 989 | if (Mode == DebugifyMode::SyntheticDebugInfo) |
| 990 | Result = checkDebugifyMetadata(M, Functions: M.functions(), NameOfWrappedPass, |
| 991 | Banner: "CheckModuleDebugify" , Strip, StatsMap); |
| 992 | else |
| 993 | Result = checkDebugInfoMetadata( |
| 994 | M, Functions: M.functions(), DebugInfoBeforePass&: *DebugInfoBeforePass, |
| 995 | Banner: "CheckModuleDebugify (original debuginfo)" , NameOfWrappedPass, |
| 996 | OrigDIVerifyBugsReportFilePath); |
| 997 | |
| 998 | return Result; |
| 999 | } |
| 1000 | |
| 1001 | CheckDebugifyModulePass( |
| 1002 | bool Strip = false, StringRef NameOfWrappedPass = "" , |
| 1003 | DebugifyStatsMap *StatsMap = nullptr, |
| 1004 | enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo, |
| 1005 | DebugInfoPerPass *DebugInfoBeforePass = nullptr, |
| 1006 | StringRef OrigDIVerifyBugsReportFilePath = "" ) |
| 1007 | : ModulePass(ID), NameOfWrappedPass(NameOfWrappedPass), |
| 1008 | OrigDIVerifyBugsReportFilePath(OrigDIVerifyBugsReportFilePath), |
| 1009 | StatsMap(StatsMap), DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode), |
| 1010 | Strip(Strip) {} |
| 1011 | |
| 1012 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 1013 | AU.setPreservesAll(); |
| 1014 | } |
| 1015 | |
| 1016 | static char ID; // Pass identification. |
| 1017 | |
| 1018 | private: |
| 1019 | StringRef NameOfWrappedPass; |
| 1020 | StringRef OrigDIVerifyBugsReportFilePath; |
| 1021 | DebugifyStatsMap *StatsMap; |
| 1022 | DebugInfoPerPass *DebugInfoBeforePass; |
| 1023 | enum DebugifyMode Mode; |
| 1024 | bool Strip; |
| 1025 | }; |
| 1026 | |
| 1027 | /// FunctionPass for checking debug info inserted by -debugify-function, used |
| 1028 | /// with the legacy module pass manager. |
| 1029 | struct CheckDebugifyFunctionPass : public FunctionPass { |
| 1030 | bool runOnFunction(Function &F) override { |
| 1031 | Module &M = *F.getParent(); |
| 1032 | auto FuncIt = F.getIterator(); |
| 1033 | bool Result; |
| 1034 | if (Mode == DebugifyMode::SyntheticDebugInfo) |
| 1035 | Result = checkDebugifyMetadata(M, Functions: make_range(x: FuncIt, y: std::next(x: FuncIt)), |
| 1036 | NameOfWrappedPass, Banner: "CheckFunctionDebugify" , |
| 1037 | Strip, StatsMap); |
| 1038 | else |
| 1039 | Result = checkDebugInfoMetadata( |
| 1040 | M, Functions: make_range(x: FuncIt, y: std::next(x: FuncIt)), DebugInfoBeforePass&: *DebugInfoBeforePass, |
| 1041 | Banner: "CheckFunctionDebugify (original debuginfo)" , NameOfWrappedPass, |
| 1042 | OrigDIVerifyBugsReportFilePath); |
| 1043 | |
| 1044 | return Result; |
| 1045 | } |
| 1046 | |
| 1047 | CheckDebugifyFunctionPass( |
| 1048 | bool Strip = false, StringRef NameOfWrappedPass = "" , |
| 1049 | DebugifyStatsMap *StatsMap = nullptr, |
| 1050 | enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo, |
| 1051 | DebugInfoPerPass *DebugInfoBeforePass = nullptr, |
| 1052 | StringRef OrigDIVerifyBugsReportFilePath = "" ) |
| 1053 | : FunctionPass(ID), NameOfWrappedPass(NameOfWrappedPass), |
| 1054 | OrigDIVerifyBugsReportFilePath(OrigDIVerifyBugsReportFilePath), |
| 1055 | StatsMap(StatsMap), DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode), |
| 1056 | Strip(Strip) {} |
| 1057 | |
| 1058 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 1059 | AU.setPreservesAll(); |
| 1060 | } |
| 1061 | |
| 1062 | static char ID; // Pass identification. |
| 1063 | |
| 1064 | private: |
| 1065 | StringRef NameOfWrappedPass; |
| 1066 | StringRef OrigDIVerifyBugsReportFilePath; |
| 1067 | DebugifyStatsMap *StatsMap; |
| 1068 | DebugInfoPerPass *DebugInfoBeforePass; |
| 1069 | enum DebugifyMode Mode; |
| 1070 | bool Strip; |
| 1071 | }; |
| 1072 | |
| 1073 | } // end anonymous namespace |
| 1074 | |
| 1075 | void llvm::exportDebugifyStats(StringRef Path, const DebugifyStatsMap &Map) { |
| 1076 | std::error_code EC; |
| 1077 | raw_fd_ostream OS{Path, EC}; |
| 1078 | if (EC) { |
| 1079 | errs() << "Could not open file: " << EC.message() << ", " << Path << '\n'; |
| 1080 | return; |
| 1081 | } |
| 1082 | |
| 1083 | OS << "Pass Name" << ',' << "# of missing debug values" << ',' |
| 1084 | << "# of missing locations" << ',' << "Missing/Expected value ratio" << ',' |
| 1085 | << "Missing/Expected location ratio" << '\n'; |
| 1086 | for (const auto &Entry : Map) { |
| 1087 | StringRef Pass = Entry.first; |
| 1088 | DebugifyStatistics Stats = Entry.second; |
| 1089 | |
| 1090 | OS << Pass << ',' << Stats.NumDbgValuesMissing << ',' |
| 1091 | << Stats.NumDbgLocsMissing << ',' << Stats.getMissingValueRatio() << ',' |
| 1092 | << Stats.getEmptyLocationRatio() << '\n'; |
| 1093 | } |
| 1094 | } |
| 1095 | |
| 1096 | ModulePass *createDebugifyModulePass(enum DebugifyMode Mode, |
| 1097 | llvm::StringRef NameOfWrappedPass, |
| 1098 | DebugInfoPerPass *DebugInfoBeforePass) { |
| 1099 | if (Mode == DebugifyMode::SyntheticDebugInfo) |
| 1100 | return new DebugifyModulePass(); |
| 1101 | assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode" ); |
| 1102 | return new DebugifyModulePass(Mode, NameOfWrappedPass, DebugInfoBeforePass); |
| 1103 | } |
| 1104 | |
| 1105 | FunctionPass * |
| 1106 | createDebugifyFunctionPass(enum DebugifyMode Mode, |
| 1107 | llvm::StringRef NameOfWrappedPass, |
| 1108 | DebugInfoPerPass *DebugInfoBeforePass) { |
| 1109 | if (Mode == DebugifyMode::SyntheticDebugInfo) |
| 1110 | return new DebugifyFunctionPass(); |
| 1111 | assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode" ); |
| 1112 | return new DebugifyFunctionPass(Mode, NameOfWrappedPass, DebugInfoBeforePass); |
| 1113 | } |
| 1114 | |
| 1115 | PreservedAnalyses NewPMDebugifyPass::run(Module &M, ModuleAnalysisManager &AM) { |
| 1116 | if (Mode == DebugifyMode::SyntheticDebugInfo) { |
| 1117 | if (ApplyToMF) { |
| 1118 | auto ApplyToMFWrapper = [&](DIBuilder &DIB, Function &F) -> bool { |
| 1119 | return ApplyToMF(DIB, F, AM); |
| 1120 | }; |
| 1121 | applyDebugifyMetadata(M, Functions: M.functions(), |
| 1122 | Banner: "ModuleDebugify: " , ApplyToMF: ApplyToMFWrapper); |
| 1123 | } else { |
| 1124 | applyDebugifyMetadata(M, Functions: M.functions(), Banner: "ModuleDebugify: " , ApplyToMF: nullptr); |
| 1125 | } |
| 1126 | } else { |
| 1127 | collectDebugInfoMetadata(M, Functions: M.functions(), DebugInfoBeforePass&: *DebugInfoBeforePass, |
| 1128 | Banner: "ModuleDebugify (original debuginfo)" , |
| 1129 | NameOfWrappedPass); |
| 1130 | } |
| 1131 | |
| 1132 | PreservedAnalyses PA; |
| 1133 | if (ApplyToMF) |
| 1134 | PA.preserve<FunctionAnalysisManagerModuleProxy>(); |
| 1135 | PA.preserveSet<CFGAnalyses>(); |
| 1136 | return PA; |
| 1137 | } |
| 1138 | |
| 1139 | ModulePass *createCheckDebugifyModulePass( |
| 1140 | bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap, |
| 1141 | enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass, |
| 1142 | StringRef OrigDIVerifyBugsReportFilePath) { |
| 1143 | if (Mode == DebugifyMode::SyntheticDebugInfo) |
| 1144 | return new CheckDebugifyModulePass(Strip, NameOfWrappedPass, StatsMap); |
| 1145 | assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode" ); |
| 1146 | return new CheckDebugifyModulePass(false, NameOfWrappedPass, nullptr, Mode, |
| 1147 | DebugInfoBeforePass, |
| 1148 | OrigDIVerifyBugsReportFilePath); |
| 1149 | } |
| 1150 | |
| 1151 | FunctionPass *createCheckDebugifyFunctionPass( |
| 1152 | bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap, |
| 1153 | enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass, |
| 1154 | StringRef OrigDIVerifyBugsReportFilePath) { |
| 1155 | if (Mode == DebugifyMode::SyntheticDebugInfo) |
| 1156 | return new CheckDebugifyFunctionPass(Strip, NameOfWrappedPass, StatsMap); |
| 1157 | assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode" ); |
| 1158 | return new CheckDebugifyFunctionPass(false, NameOfWrappedPass, nullptr, Mode, |
| 1159 | DebugInfoBeforePass, |
| 1160 | OrigDIVerifyBugsReportFilePath); |
| 1161 | } |
| 1162 | |
| 1163 | PreservedAnalyses NewPMCheckDebugifyPass::run(Module &M, |
| 1164 | ModuleAnalysisManager &) { |
| 1165 | if (Mode == DebugifyMode::SyntheticDebugInfo) |
| 1166 | checkDebugifyMetadata(M, Functions: M.functions(), NameOfWrappedPass, |
| 1167 | Banner: "CheckModuleDebugify" , Strip, StatsMap); |
| 1168 | else |
| 1169 | checkDebugInfoMetadata( |
| 1170 | M, Functions: M.functions(), DebugInfoBeforePass&: *DebugInfoBeforePass, |
| 1171 | Banner: "CheckModuleDebugify (original debuginfo)" , NameOfWrappedPass, |
| 1172 | OrigDIVerifyBugsReportFilePath); |
| 1173 | |
| 1174 | return PreservedAnalyses::all(); |
| 1175 | } |
| 1176 | |
| 1177 | static bool isIgnoredPass(StringRef PassID) { |
| 1178 | return isSpecialPass(PassID, Specials: {"PassManager" , "PassAdaptor" , |
| 1179 | "AnalysisManagerProxy" , "PrintFunctionPass" , |
| 1180 | "PrintModulePass" , "BitcodeWriterPass" , |
| 1181 | "ThinLTOBitcodeWriterPass" , "VerifierPass" }); |
| 1182 | } |
| 1183 | |
| 1184 | void DebugifyEachInstrumentation::registerCallbacks( |
| 1185 | PassInstrumentationCallbacks &PIC, ModuleAnalysisManager &MAM) { |
| 1186 | PIC.registerBeforeNonSkippedPassCallback(C: [this, &MAM](StringRef P, Any IR) { |
| 1187 | if (isIgnoredPass(PassID: P)) |
| 1188 | return; |
| 1189 | PreservedAnalyses PA; |
| 1190 | PA.preserveSet<CFGAnalyses>(); |
| 1191 | if (const auto **CF = llvm::any_cast<const Function *>(Value: &IR)) { |
| 1192 | Function &F = *const_cast<Function *>(*CF); |
| 1193 | applyDebugify(F, Mode, DebugInfoBeforePass, NameOfWrappedPass: P); |
| 1194 | MAM.getResult<FunctionAnalysisManagerModuleProxy>(IR&: *F.getParent()) |
| 1195 | .getManager() |
| 1196 | .invalidate(IR&: F, PA); |
| 1197 | } else if (const auto **CM = llvm::any_cast<const Module *>(Value: &IR)) { |
| 1198 | Module &M = *const_cast<Module *>(*CM); |
| 1199 | applyDebugify(M, Mode, DebugInfoBeforePass, NameOfWrappedPass: P); |
| 1200 | MAM.invalidate(IR&: M, PA); |
| 1201 | } |
| 1202 | }); |
| 1203 | PIC.registerAfterPassCallback( |
| 1204 | C: [this, &MAM](StringRef P, Any IR, const PreservedAnalyses &PassPA) { |
| 1205 | if (isIgnoredPass(PassID: P)) |
| 1206 | return; |
| 1207 | PreservedAnalyses PA; |
| 1208 | PA.preserveSet<CFGAnalyses>(); |
| 1209 | if (const auto **CF = llvm::any_cast<const Function *>(Value: &IR)) { |
| 1210 | auto &F = *const_cast<Function *>(*CF); |
| 1211 | Module &M = *F.getParent(); |
| 1212 | auto It = F.getIterator(); |
| 1213 | if (Mode == DebugifyMode::SyntheticDebugInfo) |
| 1214 | checkDebugifyMetadata(M, Functions: make_range(x: It, y: std::next(x: It)), NameOfWrappedPass: P, |
| 1215 | Banner: "CheckFunctionDebugify" , /*Strip=*/true, |
| 1216 | StatsMap: DIStatsMap); |
| 1217 | else |
| 1218 | checkDebugInfoMetadata(M, Functions: make_range(x: It, y: std::next(x: It)), |
| 1219 | DebugInfoBeforePass&: *DebugInfoBeforePass, |
| 1220 | Banner: "CheckModuleDebugify (original debuginfo)" , |
| 1221 | NameOfWrappedPass: P, OrigDIVerifyBugsReportFilePath); |
| 1222 | MAM.getResult<FunctionAnalysisManagerModuleProxy>(IR&: *F.getParent()) |
| 1223 | .getManager() |
| 1224 | .invalidate(IR&: F, PA); |
| 1225 | } else if (const auto **CM = llvm::any_cast<const Module *>(Value: &IR)) { |
| 1226 | Module &M = *const_cast<Module *>(*CM); |
| 1227 | if (Mode == DebugifyMode::SyntheticDebugInfo) |
| 1228 | checkDebugifyMetadata(M, Functions: M.functions(), NameOfWrappedPass: P, Banner: "CheckModuleDebugify" , |
| 1229 | /*Strip=*/true, StatsMap: DIStatsMap); |
| 1230 | else |
| 1231 | checkDebugInfoMetadata(M, Functions: M.functions(), DebugInfoBeforePass&: *DebugInfoBeforePass, |
| 1232 | Banner: "CheckModuleDebugify (original debuginfo)" , |
| 1233 | NameOfWrappedPass: P, OrigDIVerifyBugsReportFilePath); |
| 1234 | MAM.invalidate(IR&: M, PA); |
| 1235 | } |
| 1236 | }); |
| 1237 | } |
| 1238 | |
| 1239 | char DebugifyModulePass::ID = 0; |
| 1240 | static RegisterPass<DebugifyModulePass> DM("debugify" , |
| 1241 | "Attach debug info to everything" ); |
| 1242 | |
| 1243 | char CheckDebugifyModulePass::ID = 0; |
| 1244 | static RegisterPass<CheckDebugifyModulePass> |
| 1245 | CDM("check-debugify" , "Check debug info from -debugify" ); |
| 1246 | |
| 1247 | char DebugifyFunctionPass::ID = 0; |
| 1248 | static RegisterPass<DebugifyFunctionPass> DF("debugify-function" , |
| 1249 | "Attach debug info to a function" ); |
| 1250 | |
| 1251 | char CheckDebugifyFunctionPass::ID = 0; |
| 1252 | static RegisterPass<CheckDebugifyFunctionPass> |
| 1253 | CDF("check-debugify-function" , "Check debug info from -debugify-function" ); |
| 1254 | |