LLVM 20.0.0git
Debugify.cpp
Go to the documentation of this file.
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
17#include "llvm/ADT/BitVector.h"
19#include "llvm/IR/DIBuilder.h"
20#include "llvm/IR/DebugInfo.h"
24#include "llvm/IR/Module.h"
26#include "llvm/Pass.h"
29#include "llvm/Support/JSON.h"
30#include <optional>
31
32#define DEBUG_TYPE "debugify"
33
34using namespace llvm;
35
36namespace {
37
38cl::opt<bool> Quiet("debugify-quiet",
39 cl::desc("Suppress verbose debugify output"));
40
41cl::opt<uint64_t> DebugifyFunctionsLimit(
42 "debugify-func-limit",
43 cl::desc("Set max number of processed functions per pass."),
44 cl::init(UINT_MAX));
45
46enum class Level {
47 Locations,
48 LocationsAndVariables
49};
50
51cl::opt<Level> DebugifyLevel(
52 "debugify-level", cl::desc("Kind of debug info to add"),
53 cl::values(clEnumValN(Level::Locations, "locations", "Locations only"),
54 clEnumValN(Level::LocationsAndVariables, "location+variables",
55 "Locations and Variables")),
56 cl::init(Level::LocationsAndVariables));
57
58raw_ostream &dbg() { return Quiet ? nulls() : errs(); }
59
60uint64_t getAllocSizeInBits(Module &M, Type *Ty) {
61 return Ty->isSized() ? M.getDataLayout().getTypeAllocSizeInBits(Ty) : 0;
62}
63
64bool isFunctionSkipped(Function &F) {
65 return F.isDeclaration() || !F.hasExactDefinition();
66}
67
68/// Find the basic block's terminating instruction.
69///
70/// Special care is needed to handle musttail and deopt calls, as these behave
71/// like (but are in fact not) terminators.
72Instruction *findTerminatingInstruction(BasicBlock &BB) {
73 if (auto *I = BB.getTerminatingMustTailCall())
74 return I;
75 if (auto *I = BB.getTerminatingDeoptimizeCall())
76 return I;
77 return BB.getTerminator();
78}
79} // end anonymous namespace
80
83 std::function<bool(DIBuilder &DIB, Function &F)> ApplyToMF) {
84 // Skip modules with debug info.
85 if (M.getNamedMetadata("llvm.dbg.cu")) {
86 dbg() << Banner << "Skipping module with debug info\n";
87 return false;
88 }
89
90 DIBuilder DIB(M);
91 LLVMContext &Ctx = M.getContext();
92 auto *Int32Ty = Type::getInt32Ty(Ctx);
93
94 // Get a DIType which corresponds to Ty.
96 auto getCachedDIType = [&](Type *Ty) -> DIType * {
97 uint64_t Size = getAllocSizeInBits(M, Ty);
98 DIType *&DTy = TypeCache[Size];
99 if (!DTy) {
100 std::string Name = "ty" + utostr(Size);
101 DTy = DIB.createBasicType(Name, Size, dwarf::DW_ATE_unsigned);
102 }
103 return DTy;
104 };
105
106 unsigned NextLine = 1;
107 unsigned NextVar = 1;
108 auto File = DIB.createFile(M.getName(), "/");
109 auto CU = DIB.createCompileUnit(dwarf::DW_LANG_C, File, "debugify",
110 /*isOptimized=*/true, "", 0);
111
112 // Visit each instruction.
113 for (Function &F : Functions) {
114 if (isFunctionSkipped(F))
115 continue;
116
117 bool InsertedDbgVal = false;
118 auto SPType =
119 DIB.createSubroutineType(DIB.getOrCreateTypeArray(std::nullopt));
121 DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized;
122 if (F.hasPrivateLinkage() || F.hasInternalLinkage())
123 SPFlags |= DISubprogram::SPFlagLocalToUnit;
124 auto SP = DIB.createFunction(CU, F.getName(), F.getName(), File, NextLine,
125 SPType, NextLine, DINode::FlagZero, SPFlags);
126 F.setSubprogram(SP);
127
128 // Helper that inserts a dbg.value before \p InsertBefore, copying the
129 // location (and possibly the type, if it's non-void) from \p TemplateInst.
130 auto insertDbgVal = [&](Instruction &TemplateInst,
131 Instruction *InsertBefore) {
132 std::string Name = utostr(NextVar++);
133 Value *V = &TemplateInst;
134 if (TemplateInst.getType()->isVoidTy())
135 V = ConstantInt::get(Int32Ty, 0);
136 const DILocation *Loc = TemplateInst.getDebugLoc().get();
137 auto LocalVar = DIB.createAutoVariable(SP, Name, File, Loc->getLine(),
138 getCachedDIType(V->getType()),
139 /*AlwaysPreserve=*/true);
140 DIB.insertDbgValueIntrinsic(V, LocalVar, DIB.createExpression(), Loc,
141 InsertBefore);
142 };
143
144 for (BasicBlock &BB : F) {
145 // Attach debug locations.
146 for (Instruction &I : BB)
147 I.setDebugLoc(DILocation::get(Ctx, NextLine++, 1, SP));
148
149 if (DebugifyLevel < Level::LocationsAndVariables)
150 continue;
151
152 // Inserting debug values into EH pads can break IR invariants.
153 if (BB.isEHPad())
154 continue;
155
156 // Find the terminating instruction, after which no debug values are
157 // attached.
158 Instruction *LastInst = findTerminatingInstruction(BB);
159 assert(LastInst && "Expected basic block with a terminator");
160
161 // Maintain an insertion point which can't be invalidated when updates
162 // are made.
163 BasicBlock::iterator InsertPt = BB.getFirstInsertionPt();
164 assert(InsertPt != BB.end() && "Expected to find an insertion point");
165 Instruction *InsertBefore = &*InsertPt;
166
167 // Attach debug values.
168 for (Instruction *I = &*BB.begin(); I != LastInst; I = I->getNextNode()) {
169 // Skip void-valued instructions.
170 if (I->getType()->isVoidTy())
171 continue;
172
173 // Phis and EH pads must be grouped at the beginning of the block.
174 // Only advance the insertion point when we finish visiting these.
175 if (!isa<PHINode>(I) && !I->isEHPad())
176 InsertBefore = I->getNextNode();
177
178 insertDbgVal(*I, InsertBefore);
179 InsertedDbgVal = true;
180 }
181 }
182 // Make sure we emit at least one dbg.value, otherwise MachineDebugify may
183 // not have anything to work with as it goes about inserting DBG_VALUEs.
184 // (It's common for MIR tests to be written containing skeletal IR with
185 // empty functions -- we're still interested in debugifying the MIR within
186 // those tests, and this helps with that.)
187 if (DebugifyLevel == Level::LocationsAndVariables && !InsertedDbgVal) {
188 auto *Term = findTerminatingInstruction(F.getEntryBlock());
189 insertDbgVal(*Term, Term);
190 }
191 if (ApplyToMF)
192 ApplyToMF(DIB, F);
193 DIB.finalizeSubprogram(SP);
194 }
195 DIB.finalize();
196
197 // Track the number of distinct lines and variables.
198 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.debugify");
199 auto addDebugifyOperand = [&](unsigned N) {
201 Ctx, ValueAsMetadata::getConstant(ConstantInt::get(Int32Ty, N))));
202 };
203 addDebugifyOperand(NextLine - 1); // Original number of lines.
204 addDebugifyOperand(NextVar - 1); // Original number of variables.
205 assert(NMD->getNumOperands() == 2 &&
206 "llvm.debugify should have exactly 2 operands!");
207
208 // Claim that this synthetic debug info is valid.
209 StringRef DIVersionKey = "Debug Info Version";
210 if (!M.getModuleFlag(DIVersionKey))
211 M.addModuleFlag(Module::Warning, DIVersionKey, DEBUG_METADATA_VERSION);
212
213 return true;
214}
215
216static bool
219 DebugInfoPerPass *DebugInfoBeforePass = nullptr,
220 StringRef NameOfWrappedPass = "") {
221 Module &M = *F.getParent();
222 auto FuncIt = F.getIterator();
224 return applyDebugifyMetadata(M, make_range(FuncIt, std::next(FuncIt)),
225 "FunctionDebugify: ", /*ApplyToMF*/ nullptr);
226 assert(DebugInfoBeforePass);
227 return collectDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
228 "FunctionDebugify (original debuginfo)",
229 NameOfWrappedPass);
230}
231
232static bool
235 DebugInfoPerPass *DebugInfoBeforePass = nullptr,
236 StringRef NameOfWrappedPass = "") {
238 return applyDebugifyMetadata(M, M.functions(),
239 "ModuleDebugify: ", /*ApplyToMF*/ nullptr);
240 return collectDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
241 "ModuleDebugify (original debuginfo)",
242 NameOfWrappedPass);
243}
244
246 bool Changed = false;
247
248 // Remove the llvm.debugify and llvm.mir.debugify module-level named metadata.
249 NamedMDNode *DebugifyMD = M.getNamedMetadata("llvm.debugify");
250 if (DebugifyMD) {
251 M.eraseNamedMetadata(DebugifyMD);
252 Changed = true;
253 }
254
255 if (auto *MIRDebugifyMD = M.getNamedMetadata("llvm.mir.debugify")) {
256 M.eraseNamedMetadata(MIRDebugifyMD);
257 Changed = true;
258 }
259
260 // Strip out all debug intrinsics and supporting metadata (subprograms, types,
261 // variables, etc).
262 Changed |= StripDebugInfo(M);
263
264 // Strip out the dead dbg.value prototype.
265 Function *DbgValF = M.getFunction("llvm.dbg.value");
266 if (DbgValF) {
267 assert(DbgValF->isDeclaration() && DbgValF->use_empty() &&
268 "Not all debug info stripped?");
269 DbgValF->eraseFromParent();
270 Changed = true;
271 }
272
273 // Strip out the module-level Debug Info Version metadata.
274 // FIXME: There must be an easier way to remove an operand from a NamedMDNode.
275 NamedMDNode *NMD = M.getModuleFlagsMetadata();
276 if (!NMD)
277 return Changed;
279 NMD->clearOperands();
280 for (MDNode *Flag : Flags) {
281 auto *Key = cast<MDString>(Flag->getOperand(1));
282 if (Key->getString() == "Debug Info Version") {
283 Changed = true;
284 continue;
285 }
286 NMD->addOperand(Flag);
287 }
288 // If we left it empty we might as well remove it.
289 if (NMD->getNumOperands() == 0)
290 NMD->eraseFromParent();
291
292 return Changed;
293}
294
297 DebugInfoPerPass &DebugInfoBeforePass,
298 StringRef Banner,
299 StringRef NameOfWrappedPass) {
300 LLVM_DEBUG(dbgs() << Banner << ": (before) " << NameOfWrappedPass << '\n');
301
302 if (!M.getNamedMetadata("llvm.dbg.cu")) {
303 dbg() << Banner << ": Skipping module without debug info\n";
304 return false;
305 }
306
307 uint64_t FunctionsCnt = DebugInfoBeforePass.DIFunctions.size();
308 // Visit each instruction.
309 for (Function &F : Functions) {
310 // Use DI collected after previous Pass (when -debugify-each is used).
311 if (DebugInfoBeforePass.DIFunctions.count(&F))
312 continue;
313
314 if (isFunctionSkipped(F))
315 continue;
316
317 // Stop collecting DI if the Functions number reached the limit.
318 if (++FunctionsCnt >= DebugifyFunctionsLimit)
319 break;
320 // Collect the DISubprogram.
321 auto *SP = F.getSubprogram();
322 DebugInfoBeforePass.DIFunctions.insert({&F, SP});
323 if (SP) {
324 LLVM_DEBUG(dbgs() << " Collecting subprogram: " << *SP << '\n');
325 for (const DINode *DN : SP->getRetainedNodes()) {
326 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
327 DebugInfoBeforePass.DIVariables[DV] = 0;
328 }
329 }
330 }
331
332 for (BasicBlock &BB : F) {
333 // Collect debug locations (!dbg) and debug variable intrinsics.
334 for (Instruction &I : BB) {
335 // Skip PHIs.
336 if (isa<PHINode>(I))
337 continue;
338
339 // Cllect dbg.values and dbg.declare.
340 if (DebugifyLevel > Level::Locations) {
341 auto HandleDbgVariable = [&](auto *DbgVar) {
342 if (!SP)
343 return;
344 // Skip inlined variables.
345 if (DbgVar->getDebugLoc().getInlinedAt())
346 return;
347 // Skip undef values.
348 if (DbgVar->isKillLocation())
349 return;
350
351 auto *Var = DbgVar->getVariable();
352 DebugInfoBeforePass.DIVariables[Var]++;
353 };
354 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
355 HandleDbgVariable(&DVR);
356 if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
357 HandleDbgVariable(DVI);
358 }
359
360 // Skip debug instructions other than dbg.value and dbg.declare.
361 if (isa<DbgInfoIntrinsic>(&I))
362 continue;
363
364 LLVM_DEBUG(dbgs() << " Collecting info for inst: " << I << '\n');
365 DebugInfoBeforePass.InstToDelete.insert({&I, &I});
366
367 const DILocation *Loc = I.getDebugLoc().get();
368 bool HasLoc = Loc != nullptr;
369 DebugInfoBeforePass.DILocations.insert({&I, HasLoc});
370 }
371 }
372 }
373
374 return true;
375}
376
377// This checks the preservation of original debug info attached to functions.
378static bool checkFunctions(const DebugFnMap &DIFunctionsBefore,
379 const DebugFnMap &DIFunctionsAfter,
380 StringRef NameOfWrappedPass,
381 StringRef FileNameFromCU, bool ShouldWriteIntoJSON,
382 llvm::json::Array &Bugs) {
383 bool Preserved = true;
384 for (const auto &F : DIFunctionsAfter) {
385 if (F.second)
386 continue;
387 auto SPIt = DIFunctionsBefore.find(F.first);
388 if (SPIt == DIFunctionsBefore.end()) {
389 if (ShouldWriteIntoJSON)
390 Bugs.push_back(llvm::json::Object({{"metadata", "DISubprogram"},
391 {"name", F.first->getName()},
392 {"action", "not-generate"}}));
393 else
394 dbg() << "ERROR: " << NameOfWrappedPass
395 << " did not generate DISubprogram for " << F.first->getName()
396 << " from " << FileNameFromCU << '\n';
397 Preserved = false;
398 } else {
399 auto SP = SPIt->second;
400 if (!SP)
401 continue;
402 // If the function had the SP attached before the pass, consider it as
403 // a debug info bug.
404 if (ShouldWriteIntoJSON)
405 Bugs.push_back(llvm::json::Object({{"metadata", "DISubprogram"},
406 {"name", F.first->getName()},
407 {"action", "drop"}}));
408 else
409 dbg() << "ERROR: " << NameOfWrappedPass << " dropped DISubprogram of "
410 << F.first->getName() << " from " << FileNameFromCU << '\n';
411 Preserved = false;
412 }
413 }
414
415 return Preserved;
416}
417
418// This checks the preservation of the original debug info attached to
419// instructions.
420static bool checkInstructions(const DebugInstMap &DILocsBefore,
421 const DebugInstMap &DILocsAfter,
422 const WeakInstValueMap &InstToDelete,
423 StringRef NameOfWrappedPass,
424 StringRef FileNameFromCU,
425 bool ShouldWriteIntoJSON,
426 llvm::json::Array &Bugs) {
427 bool Preserved = true;
428 for (const auto &L : DILocsAfter) {
429 if (L.second)
430 continue;
431 auto Instr = L.first;
432
433 // In order to avoid pointer reuse/recycling, skip the values that might
434 // have been deleted during a pass.
435 auto WeakInstrPtr = InstToDelete.find(Instr);
436 if (WeakInstrPtr != InstToDelete.end() && !WeakInstrPtr->second)
437 continue;
438
439 auto FnName = Instr->getFunction()->getName();
440 auto BB = Instr->getParent();
441 auto BBName = BB->hasName() ? BB->getName() : "no-name";
442 auto InstName = Instruction::getOpcodeName(Instr->getOpcode());
443
444 auto InstrIt = DILocsBefore.find(Instr);
445 if (InstrIt == DILocsBefore.end()) {
446 if (ShouldWriteIntoJSON)
447 Bugs.push_back(llvm::json::Object({{"metadata", "DILocation"},
448 {"fn-name", FnName.str()},
449 {"bb-name", BBName.str()},
450 {"instr", InstName},
451 {"action", "not-generate"}}));
452 else
453 dbg() << "WARNING: " << NameOfWrappedPass
454 << " did not generate DILocation for " << *Instr
455 << " (BB: " << BBName << ", Fn: " << FnName
456 << ", File: " << FileNameFromCU << ")\n";
457 Preserved = false;
458 } else {
459 if (!InstrIt->second)
460 continue;
461 // If the instr had the !dbg attached before the pass, consider it as
462 // a debug info issue.
463 if (ShouldWriteIntoJSON)
464 Bugs.push_back(llvm::json::Object({{"metadata", "DILocation"},
465 {"fn-name", FnName.str()},
466 {"bb-name", BBName.str()},
467 {"instr", InstName},
468 {"action", "drop"}}));
469 else
470 dbg() << "WARNING: " << NameOfWrappedPass << " dropped DILocation of "
471 << *Instr << " (BB: " << BBName << ", Fn: " << FnName
472 << ", File: " << FileNameFromCU << ")\n";
473 Preserved = false;
474 }
475 }
476
477 return Preserved;
478}
479
480// This checks the preservation of original debug variable intrinsics.
481static bool checkVars(const DebugVarMap &DIVarsBefore,
482 const DebugVarMap &DIVarsAfter,
483 StringRef NameOfWrappedPass, StringRef FileNameFromCU,
484 bool ShouldWriteIntoJSON, llvm::json::Array &Bugs) {
485 bool Preserved = true;
486 for (const auto &V : DIVarsBefore) {
487 auto VarIt = DIVarsAfter.find(V.first);
488 if (VarIt == DIVarsAfter.end())
489 continue;
490
491 unsigned NumOfDbgValsAfter = VarIt->second;
492
493 if (V.second > NumOfDbgValsAfter) {
494 if (ShouldWriteIntoJSON)
496 {{"metadata", "dbg-var-intrinsic"},
497 {"name", V.first->getName()},
498 {"fn-name", V.first->getScope()->getSubprogram()->getName()},
499 {"action", "drop"}}));
500 else
501 dbg() << "WARNING: " << NameOfWrappedPass
502 << " drops dbg.value()/dbg.declare() for " << V.first->getName()
503 << " from "
504 << "function " << V.first->getScope()->getSubprogram()->getName()
505 << " (file " << FileNameFromCU << ")\n";
506 Preserved = false;
507 }
508 }
509
510 return Preserved;
511}
512
513// Write the json data into the specifed file.
514static void writeJSON(StringRef OrigDIVerifyBugsReportFilePath,
515 StringRef FileNameFromCU, StringRef NameOfWrappedPass,
516 llvm::json::Array &Bugs) {
517 std::error_code EC;
518 raw_fd_ostream OS_FILE{OrigDIVerifyBugsReportFilePath, EC,
520 if (EC) {
521 errs() << "Could not open file: " << EC.message() << ", "
522 << OrigDIVerifyBugsReportFilePath << '\n';
523 return;
524 }
525
526 if (auto L = OS_FILE.lock()) {
527 OS_FILE << "{\"file\":\"" << FileNameFromCU << "\", ";
528
530 NameOfWrappedPass != "" ? NameOfWrappedPass : "no-name";
531 OS_FILE << "\"pass\":\"" << PassName << "\", ";
532
533 llvm::json::Value BugsToPrint{std::move(Bugs)};
534 OS_FILE << "\"bugs\": " << BugsToPrint;
535
536 OS_FILE << "}\n";
537 }
538 OS_FILE.close();
539}
540
543 DebugInfoPerPass &DebugInfoBeforePass,
544 StringRef Banner, StringRef NameOfWrappedPass,
545 StringRef OrigDIVerifyBugsReportFilePath) {
546 LLVM_DEBUG(dbgs() << Banner << ": (after) " << NameOfWrappedPass << '\n');
547
548 if (!M.getNamedMetadata("llvm.dbg.cu")) {
549 dbg() << Banner << ": Skipping module without debug info\n";
550 return false;
551 }
552
553 // Map the debug info holding DIs after a pass.
554 DebugInfoPerPass DebugInfoAfterPass;
555
556 // Visit each instruction.
557 for (Function &F : Functions) {
558 if (isFunctionSkipped(F))
559 continue;
560
561 // Don't process functions without DI collected before the Pass.
562 if (!DebugInfoBeforePass.DIFunctions.count(&F))
563 continue;
564 // TODO: Collect metadata other than DISubprograms.
565 // Collect the DISubprogram.
566 auto *SP = F.getSubprogram();
567 DebugInfoAfterPass.DIFunctions.insert({&F, SP});
568
569 if (SP) {
570 LLVM_DEBUG(dbgs() << " Collecting subprogram: " << *SP << '\n');
571 for (const DINode *DN : SP->getRetainedNodes()) {
572 if (const auto *DV = dyn_cast<DILocalVariable>(DN)) {
573 DebugInfoAfterPass.DIVariables[DV] = 0;
574 }
575 }
576 }
577
578 for (BasicBlock &BB : F) {
579 // Collect debug locations (!dbg) and debug variable intrinsics.
580 for (Instruction &I : BB) {
581 // Skip PHIs.
582 if (isa<PHINode>(I))
583 continue;
584
585 // Collect dbg.values and dbg.declares.
586 if (DebugifyLevel > Level::Locations) {
587 auto HandleDbgVariable = [&](auto *DbgVar) {
588 if (!SP)
589 return;
590 // Skip inlined variables.
591 if (DbgVar->getDebugLoc().getInlinedAt())
592 return;
593 // Skip undef values.
594 if (DbgVar->isKillLocation())
595 return;
596
597 auto *Var = DbgVar->getVariable();
598 DebugInfoAfterPass.DIVariables[Var]++;
599 };
600 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
601 HandleDbgVariable(&DVR);
602 if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I))
603 HandleDbgVariable(DVI);
604 }
605
606 // Skip debug instructions other than dbg.value and dbg.declare.
607 if (isa<DbgInfoIntrinsic>(&I))
608 continue;
609
610 LLVM_DEBUG(dbgs() << " Collecting info for inst: " << I << '\n');
611
612 const DILocation *Loc = I.getDebugLoc().get();
613 bool HasLoc = Loc != nullptr;
614
615 DebugInfoAfterPass.DILocations.insert({&I, HasLoc});
616 }
617 }
618 }
619
620 // TODO: The name of the module could be read better?
621 StringRef FileNameFromCU =
622 (cast<DICompileUnit>(M.getNamedMetadata("llvm.dbg.cu")->getOperand(0)))
623 ->getFilename();
624
625 auto DIFunctionsBefore = DebugInfoBeforePass.DIFunctions;
626 auto DIFunctionsAfter = DebugInfoAfterPass.DIFunctions;
627
628 auto DILocsBefore = DebugInfoBeforePass.DILocations;
629 auto DILocsAfter = DebugInfoAfterPass.DILocations;
630
631 auto InstToDelete = DebugInfoBeforePass.InstToDelete;
632
633 auto DIVarsBefore = DebugInfoBeforePass.DIVariables;
634 auto DIVarsAfter = DebugInfoAfterPass.DIVariables;
635
636 bool ShouldWriteIntoJSON = !OrigDIVerifyBugsReportFilePath.empty();
638
639 bool ResultForFunc =
640 checkFunctions(DIFunctionsBefore, DIFunctionsAfter, NameOfWrappedPass,
641 FileNameFromCU, ShouldWriteIntoJSON, Bugs);
642 bool ResultForInsts = checkInstructions(
643 DILocsBefore, DILocsAfter, InstToDelete, NameOfWrappedPass,
644 FileNameFromCU, ShouldWriteIntoJSON, Bugs);
645
646 bool ResultForVars = checkVars(DIVarsBefore, DIVarsAfter, NameOfWrappedPass,
647 FileNameFromCU, ShouldWriteIntoJSON, Bugs);
648
649 bool Result = ResultForFunc && ResultForInsts && ResultForVars;
650
651 StringRef ResultBanner = NameOfWrappedPass != "" ? NameOfWrappedPass : Banner;
652 if (ShouldWriteIntoJSON && !Bugs.empty())
653 writeJSON(OrigDIVerifyBugsReportFilePath, FileNameFromCU, NameOfWrappedPass,
654 Bugs);
655
656 if (Result)
657 dbg() << ResultBanner << ": PASS\n";
658 else
659 dbg() << ResultBanner << ": FAIL\n";
660
661 // In the case of the `debugify-each`, no need to go over all the instructions
662 // again in the collectDebugInfoMetadata(), since as an input we can use
663 // the debugging information from the previous pass.
664 DebugInfoBeforePass = DebugInfoAfterPass;
665
666 LLVM_DEBUG(dbgs() << "\n\n");
667 return Result;
668}
669
670namespace {
671/// Return true if a mis-sized diagnostic is issued for \p DbgVal.
672template <typename DbgValTy>
673bool diagnoseMisSizedDbgValue(Module &M, DbgValTy *DbgVal) {
674 // The size of a dbg.value's value operand should match the size of the
675 // variable it corresponds to.
676 //
677 // TODO: This, along with a check for non-null value operands, should be
678 // promoted to verifier failures.
679
680 // For now, don't try to interpret anything more complicated than an empty
681 // DIExpression. Eventually we should try to handle OP_deref and fragments.
682 if (DbgVal->getExpression()->getNumElements())
683 return false;
684
685 Value *V = DbgVal->getVariableLocationOp(0);
686 if (!V)
687 return false;
688
689 Type *Ty = V->getType();
690 uint64_t ValueOperandSize = getAllocSizeInBits(M, Ty);
691 std::optional<uint64_t> DbgVarSize = DbgVal->getFragmentSizeInBits();
692 if (!ValueOperandSize || !DbgVarSize)
693 return false;
694
695 bool HasBadSize = false;
696 if (Ty->isIntegerTy()) {
697 auto Signedness = DbgVal->getVariable()->getSignedness();
698 if (Signedness && *Signedness == DIBasicType::Signedness::Signed)
699 HasBadSize = ValueOperandSize < *DbgVarSize;
700 } else {
701 HasBadSize = ValueOperandSize != *DbgVarSize;
702 }
703
704 if (HasBadSize) {
705 dbg() << "ERROR: dbg.value operand has size " << ValueOperandSize
706 << ", but its variable has size " << *DbgVarSize << ": ";
707 DbgVal->print(dbg());
708 dbg() << "\n";
709 }
710 return HasBadSize;
711}
712
713bool checkDebugifyMetadata(Module &M,
715 StringRef NameOfWrappedPass, StringRef Banner,
716 bool Strip, DebugifyStatsMap *StatsMap) {
717 // Skip modules without debugify metadata.
718 NamedMDNode *NMD = M.getNamedMetadata("llvm.debugify");
719 if (!NMD) {
720 dbg() << Banner << ": Skipping module without debugify metadata\n";
721 return false;
722 }
723
724 auto getDebugifyOperand = [&](unsigned Idx) -> unsigned {
725 return mdconst::extract<ConstantInt>(NMD->getOperand(Idx)->getOperand(0))
726 ->getZExtValue();
727 };
728 assert(NMD->getNumOperands() == 2 &&
729 "llvm.debugify should have exactly 2 operands!");
730 unsigned OriginalNumLines = getDebugifyOperand(0);
731 unsigned OriginalNumVars = getDebugifyOperand(1);
732 bool HasErrors = false;
733
734 // Track debug info loss statistics if able.
735 DebugifyStatistics *Stats = nullptr;
736 if (StatsMap && !NameOfWrappedPass.empty())
737 Stats = &StatsMap->operator[](NameOfWrappedPass);
738
739 BitVector MissingLines{OriginalNumLines, true};
740 BitVector MissingVars{OriginalNumVars, true};
741 for (Function &F : Functions) {
742 if (isFunctionSkipped(F))
743 continue;
744
745 // Find missing lines.
746 for (Instruction &I : instructions(F)) {
747 if (isa<DbgValueInst>(&I))
748 continue;
749
750 auto DL = I.getDebugLoc();
751 if (DL && DL.getLine() != 0) {
752 MissingLines.reset(DL.getLine() - 1);
753 continue;
754 }
755
756 if (!isa<PHINode>(&I) && !DL) {
757 dbg() << "WARNING: Instruction with empty DebugLoc in function ";
758 dbg() << F.getName() << " --";
759 I.print(dbg());
760 dbg() << "\n";
761 }
762 }
763
764 // Find missing variables and mis-sized debug values.
765 auto CheckForMisSized = [&](auto *DbgVal) {
766 unsigned Var = ~0U;
767 (void)to_integer(DbgVal->getVariable()->getName(), Var, 10);
768 assert(Var <= OriginalNumVars && "Unexpected name for DILocalVariable");
769 bool HasBadSize = diagnoseMisSizedDbgValue(M, DbgVal);
770 if (!HasBadSize)
771 MissingVars.reset(Var - 1);
772 HasErrors |= HasBadSize;
773 };
774 for (Instruction &I : instructions(F)) {
775 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
776 if (DVR.isDbgValue() || DVR.isDbgAssign())
777 CheckForMisSized(&DVR);
778 auto *DVI = dyn_cast<DbgValueInst>(&I);
779 if (!DVI)
780 continue;
781 CheckForMisSized(DVI);
782 }
783 }
784
785 // Print the results.
786 for (unsigned Idx : MissingLines.set_bits())
787 dbg() << "WARNING: Missing line " << Idx + 1 << "\n";
788
789 for (unsigned Idx : MissingVars.set_bits())
790 dbg() << "WARNING: Missing variable " << Idx + 1 << "\n";
791
792 // Update DI loss statistics.
793 if (Stats) {
794 Stats->NumDbgLocsExpected += OriginalNumLines;
795 Stats->NumDbgLocsMissing += MissingLines.count();
796 Stats->NumDbgValuesExpected += OriginalNumVars;
797 Stats->NumDbgValuesMissing += MissingVars.count();
798 }
799
800 dbg() << Banner;
801 if (!NameOfWrappedPass.empty())
802 dbg() << " [" << NameOfWrappedPass << "]";
803 dbg() << ": " << (HasErrors ? "FAIL" : "PASS") << '\n';
804
805 // Strip debugify metadata if required.
806 bool Ret = false;
807 if (Strip)
809
810 return Ret;
811}
812
813/// ModulePass for attaching synthetic debug info to everything, used with the
814/// legacy module pass manager.
815struct DebugifyModulePass : public ModulePass {
816 bool runOnModule(Module &M) override {
817 bool Result =
818 applyDebugify(M, Mode, DebugInfoBeforePass, NameOfWrappedPass);
819 return Result;
820 }
821
822 DebugifyModulePass(enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
823 StringRef NameOfWrappedPass = "",
824 DebugInfoPerPass *DebugInfoBeforePass = nullptr)
825 : ModulePass(ID), NameOfWrappedPass(NameOfWrappedPass),
826 DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode) {}
827
828 void getAnalysisUsage(AnalysisUsage &AU) const override {
829 AU.setPreservesAll();
830 }
831
832 static char ID; // Pass identification.
833
834private:
835 StringRef NameOfWrappedPass;
836 DebugInfoPerPass *DebugInfoBeforePass;
837 enum DebugifyMode Mode;
838};
839
840/// FunctionPass for attaching synthetic debug info to instructions within a
841/// single function, used with the legacy module pass manager.
842struct DebugifyFunctionPass : public FunctionPass {
843 bool runOnFunction(Function &F) override {
844 bool Result =
845 applyDebugify(F, Mode, DebugInfoBeforePass, NameOfWrappedPass);
846 return Result;
847 }
848
849 DebugifyFunctionPass(
850 enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
851 StringRef NameOfWrappedPass = "",
852 DebugInfoPerPass *DebugInfoBeforePass = nullptr)
853 : FunctionPass(ID), NameOfWrappedPass(NameOfWrappedPass),
854 DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode) {}
855
856 void getAnalysisUsage(AnalysisUsage &AU) const override {
857 AU.setPreservesAll();
858 }
859
860 static char ID; // Pass identification.
861
862private:
863 StringRef NameOfWrappedPass;
864 DebugInfoPerPass *DebugInfoBeforePass;
865 enum DebugifyMode Mode;
866};
867
868/// ModulePass for checking debug info inserted by -debugify, used with the
869/// legacy module pass manager.
870struct CheckDebugifyModulePass : public ModulePass {
871 bool runOnModule(Module &M) override {
872 bool Result;
873 if (Mode == DebugifyMode::SyntheticDebugInfo)
874 Result = checkDebugifyMetadata(M, M.functions(), NameOfWrappedPass,
875 "CheckModuleDebugify", Strip, StatsMap);
876 else
878 M, M.functions(), *DebugInfoBeforePass,
879 "CheckModuleDebugify (original debuginfo)", NameOfWrappedPass,
880 OrigDIVerifyBugsReportFilePath);
881
882 return Result;
883 }
884
885 CheckDebugifyModulePass(
886 bool Strip = false, StringRef NameOfWrappedPass = "",
887 DebugifyStatsMap *StatsMap = nullptr,
888 enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
889 DebugInfoPerPass *DebugInfoBeforePass = nullptr,
890 StringRef OrigDIVerifyBugsReportFilePath = "")
891 : ModulePass(ID), NameOfWrappedPass(NameOfWrappedPass),
892 OrigDIVerifyBugsReportFilePath(OrigDIVerifyBugsReportFilePath),
893 StatsMap(StatsMap), DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode),
894 Strip(Strip) {}
895
896 void getAnalysisUsage(AnalysisUsage &AU) const override {
897 AU.setPreservesAll();
898 }
899
900 static char ID; // Pass identification.
901
902private:
903 StringRef NameOfWrappedPass;
904 StringRef OrigDIVerifyBugsReportFilePath;
905 DebugifyStatsMap *StatsMap;
906 DebugInfoPerPass *DebugInfoBeforePass;
907 enum DebugifyMode Mode;
908 bool Strip;
909};
910
911/// FunctionPass for checking debug info inserted by -debugify-function, used
912/// with the legacy module pass manager.
913struct CheckDebugifyFunctionPass : public FunctionPass {
914 bool runOnFunction(Function &F) override {
915 Module &M = *F.getParent();
916 auto FuncIt = F.getIterator();
917 bool Result;
918 if (Mode == DebugifyMode::SyntheticDebugInfo)
919 Result = checkDebugifyMetadata(M, make_range(FuncIt, std::next(FuncIt)),
920 NameOfWrappedPass, "CheckFunctionDebugify",
921 Strip, StatsMap);
922 else
924 M, make_range(FuncIt, std::next(FuncIt)), *DebugInfoBeforePass,
925 "CheckFunctionDebugify (original debuginfo)", NameOfWrappedPass,
926 OrigDIVerifyBugsReportFilePath);
927
928 return Result;
929 }
930
931 CheckDebugifyFunctionPass(
932 bool Strip = false, StringRef NameOfWrappedPass = "",
933 DebugifyStatsMap *StatsMap = nullptr,
934 enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
935 DebugInfoPerPass *DebugInfoBeforePass = nullptr,
936 StringRef OrigDIVerifyBugsReportFilePath = "")
937 : FunctionPass(ID), NameOfWrappedPass(NameOfWrappedPass),
938 OrigDIVerifyBugsReportFilePath(OrigDIVerifyBugsReportFilePath),
939 StatsMap(StatsMap), DebugInfoBeforePass(DebugInfoBeforePass), Mode(Mode),
940 Strip(Strip) {}
941
942 void getAnalysisUsage(AnalysisUsage &AU) const override {
943 AU.setPreservesAll();
944 }
945
946 static char ID; // Pass identification.
947
948private:
949 StringRef NameOfWrappedPass;
950 StringRef OrigDIVerifyBugsReportFilePath;
951 DebugifyStatsMap *StatsMap;
952 DebugInfoPerPass *DebugInfoBeforePass;
953 enum DebugifyMode Mode;
954 bool Strip;
955};
956
957} // end anonymous namespace
958
960 std::error_code EC;
961 raw_fd_ostream OS{Path, EC};
962 if (EC) {
963 errs() << "Could not open file: " << EC.message() << ", " << Path << '\n';
964 return;
965 }
966
967 OS << "Pass Name" << ',' << "# of missing debug values" << ','
968 << "# of missing locations" << ',' << "Missing/Expected value ratio" << ','
969 << "Missing/Expected location ratio" << '\n';
970 for (const auto &Entry : Map) {
971 StringRef Pass = Entry.first;
972 DebugifyStatistics Stats = Entry.second;
973
974 OS << Pass << ',' << Stats.NumDbgValuesMissing << ','
975 << Stats.NumDbgLocsMissing << ',' << Stats.getMissingValueRatio() << ','
976 << Stats.getEmptyLocationRatio() << '\n';
977 }
978}
979
981 llvm::StringRef NameOfWrappedPass,
982 DebugInfoPerPass *DebugInfoBeforePass) {
984 return new DebugifyModulePass();
985 assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
986 return new DebugifyModulePass(Mode, NameOfWrappedPass, DebugInfoBeforePass);
987}
988
991 llvm::StringRef NameOfWrappedPass,
992 DebugInfoPerPass *DebugInfoBeforePass) {
994 return new DebugifyFunctionPass();
995 assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
996 return new DebugifyFunctionPass(Mode, NameOfWrappedPass, DebugInfoBeforePass);
997}
998
1000 if (Mode == DebugifyMode::SyntheticDebugInfo)
1001 applyDebugifyMetadata(M, M.functions(),
1002 "ModuleDebugify: ", /*ApplyToMF*/ nullptr);
1003 else
1004 collectDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
1005 "ModuleDebugify (original debuginfo)",
1006 NameOfWrappedPass);
1007
1010 return PA;
1011}
1012
1014 bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap,
1015 enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass,
1016 StringRef OrigDIVerifyBugsReportFilePath) {
1018 return new CheckDebugifyModulePass(Strip, NameOfWrappedPass, StatsMap);
1019 assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
1020 return new CheckDebugifyModulePass(false, NameOfWrappedPass, nullptr, Mode,
1021 DebugInfoBeforePass,
1022 OrigDIVerifyBugsReportFilePath);
1023}
1024
1026 bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap,
1027 enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass,
1028 StringRef OrigDIVerifyBugsReportFilePath) {
1030 return new CheckDebugifyFunctionPass(Strip, NameOfWrappedPass, StatsMap);
1031 assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
1032 return new CheckDebugifyFunctionPass(false, NameOfWrappedPass, nullptr, Mode,
1033 DebugInfoBeforePass,
1034 OrigDIVerifyBugsReportFilePath);
1035}
1036
1039 if (Mode == DebugifyMode::SyntheticDebugInfo)
1040 checkDebugifyMetadata(M, M.functions(), NameOfWrappedPass,
1041 "CheckModuleDebugify", Strip, StatsMap);
1042 else
1044 M, M.functions(), *DebugInfoBeforePass,
1045 "CheckModuleDebugify (original debuginfo)", NameOfWrappedPass,
1046 OrigDIVerifyBugsReportFilePath);
1047
1048 return PreservedAnalyses::all();
1049}
1050
1051static bool isIgnoredPass(StringRef PassID) {
1052 return isSpecialPass(PassID, {"PassManager", "PassAdaptor",
1053 "AnalysisManagerProxy", "PrintFunctionPass",
1054 "PrintModulePass", "BitcodeWriterPass",
1055 "ThinLTOBitcodeWriterPass", "VerifierPass"});
1056}
1057
1061 if (isIgnoredPass(P))
1062 return;
1065 if (const auto **CF = llvm::any_cast<const Function *>(&IR)) {
1066 Function &F = *const_cast<Function *>(*CF);
1067 applyDebugify(F, Mode, DebugInfoBeforePass, P);
1069 .getManager()
1070 .invalidate(F, PA);
1071 } else if (const auto **CM = llvm::any_cast<const Module *>(&IR)) {
1072 Module &M = *const_cast<Module *>(*CM);
1073 applyDebugify(M, Mode, DebugInfoBeforePass, P);
1074 MAM.invalidate(M, PA);
1075 }
1076 });
1078 [this, &MAM](StringRef P, Any IR, const PreservedAnalyses &PassPA) {
1079 if (isIgnoredPass(P))
1080 return;
1083 if (const auto **CF = llvm::any_cast<const Function *>(&IR)) {
1084 auto &F = *const_cast<Function *>(*CF);
1085 Module &M = *F.getParent();
1086 auto It = F.getIterator();
1087 if (Mode == DebugifyMode::SyntheticDebugInfo)
1088 checkDebugifyMetadata(M, make_range(It, std::next(It)), P,
1089 "CheckFunctionDebugify", /*Strip=*/true,
1090 DIStatsMap);
1091 else
1092 checkDebugInfoMetadata(M, make_range(It, std::next(It)),
1093 *DebugInfoBeforePass,
1094 "CheckModuleDebugify (original debuginfo)",
1095 P, OrigDIVerifyBugsReportFilePath);
1097 .getManager()
1098 .invalidate(F, PA);
1099 } else if (const auto **CM = llvm::any_cast<const Module *>(&IR)) {
1100 Module &M = *const_cast<Module *>(*CM);
1101 if (Mode == DebugifyMode::SyntheticDebugInfo)
1102 checkDebugifyMetadata(M, M.functions(), P, "CheckModuleDebugify",
1103 /*Strip=*/true, DIStatsMap);
1104 else
1105 checkDebugInfoMetadata(M, M.functions(), *DebugInfoBeforePass,
1106 "CheckModuleDebugify (original debuginfo)",
1107 P, OrigDIVerifyBugsReportFilePath);
1108 MAM.invalidate(M, PA);
1109 }
1110 });
1111}
1112
1113char DebugifyModulePass::ID = 0;
1115 "Attach debug info to everything");
1116
1117char CheckDebugifyModulePass::ID = 0;
1119 CDM("check-debugify", "Check debug info from -debugify");
1120
1121char DebugifyFunctionPass::ID = 0;
1122static RegisterPass<DebugifyFunctionPass> DF("debugify-function",
1123 "Attach debug info to a function");
1124
1125char CheckDebugifyFunctionPass::ID = 0;
1127 CDF("check-debugify-function", "Check debug info from -debugify-function");
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
This file implements the BitVector class.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:686
static DISubprogram * getSubprogram(bool IsDistinct, Ts &&...Args)
Definition: DIBuilder.cpp:849
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
static RegisterPass< CheckDebugifyModulePass > CDM("check-debugify", "Check debug info from -debugify")
ModulePass * createDebugifyModulePass(enum DebugifyMode Mode, llvm::StringRef NameOfWrappedPass, DebugInfoPerPass *DebugInfoBeforePass)
Definition: Debugify.cpp:980
FunctionPass * createDebugifyFunctionPass(enum DebugifyMode Mode, llvm::StringRef NameOfWrappedPass, DebugInfoPerPass *DebugInfoBeforePass)
Definition: Debugify.cpp:990
static bool isIgnoredPass(StringRef PassID)
Definition: Debugify.cpp:1051
static bool applyDebugify(Function &F, enum DebugifyMode Mode=DebugifyMode::SyntheticDebugInfo, DebugInfoPerPass *DebugInfoBeforePass=nullptr, StringRef NameOfWrappedPass="")
Definition: Debugify.cpp:217
ModulePass * createCheckDebugifyModulePass(bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap, enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass, StringRef OrigDIVerifyBugsReportFilePath)
Definition: Debugify.cpp:1013
static void writeJSON(StringRef OrigDIVerifyBugsReportFilePath, StringRef FileNameFromCU, StringRef NameOfWrappedPass, llvm::json::Array &Bugs)
Definition: Debugify.cpp:514
static RegisterPass< DebugifyFunctionPass > DF("debugify-function", "Attach debug info to a function")
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
static bool checkFunctions(const DebugFnMap &DIFunctionsBefore, const DebugFnMap &DIFunctionsAfter, StringRef NameOfWrappedPass, StringRef FileNameFromCU, bool ShouldWriteIntoJSON, llvm::json::Array &Bugs)
Definition: Debugify.cpp:378
static RegisterPass< CheckDebugifyFunctionPass > CDF("check-debugify-function", "Check debug info from -debugify-function")
FunctionPass * createCheckDebugifyFunctionPass(bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap, enum DebugifyMode Mode, DebugInfoPerPass *DebugInfoBeforePass, StringRef OrigDIVerifyBugsReportFilePath)
Definition: Debugify.cpp:1025
static bool checkVars(const DebugVarMap &DIVarsBefore, const DebugVarMap &DIVarsAfter, StringRef NameOfWrappedPass, StringRef FileNameFromCU, bool ShouldWriteIntoJSON, llvm::json::Array &Bugs)
Definition: Debugify.cpp:481
static bool checkInstructions(const DebugInstMap &DILocsBefore, const DebugInstMap &DILocsAfter, const WeakInstValueMap &InstToDelete, StringRef NameOfWrappedPass, StringRef FileNameFromCU, bool ShouldWriteIntoJSON, llvm::json::Array &Bugs)
Definition: Debugify.cpp:420
DebugifyMode
Used to check whether we track synthetic or original debug info.
Definition: Debugify.h:95
std::string Name
uint64_t Size
static SmallString< 128 > getFilename(const DISubprogram *SP)
Extract a filename for a DISubprogram.
This file supports working with JSON data.
Legalize the Machine IR a function s Machine IR
Definition: Legalizer.cpp:81
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
block placement Basic Block Placement Stats
Module.h This file contains the declarations for the Module class.
#define P(N)
ModuleAnalysisManager MAM
PassInstrumentationCallbacks PIC
This file defines the Pass Instrumentation classes that provide instrumentation points into the pass ...
static StringRef getName(Value *V)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file contains some functions that are useful when dealing with strings.
static const char PassName[]
llvm::PreservedAnalyses run(llvm::Module &M, llvm::ModuleAnalysisManager &AM)
Definition: Debugify.cpp:1037
llvm::PreservedAnalyses run(llvm::Module &M, llvm::ModuleAnalysisManager &AM)
Definition: Debugify.cpp:999
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
void invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Invalidate cached analyses for an IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Definition: Any.h:28
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
Definition: BasicBlock.cpp:331
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:177
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:239
const CallInst * getTerminatingMustTailCall() const
Returns the call instruction marked 'musttail' prior to the terminating return instruction of this ba...
Definition: BasicBlock.cpp:300
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:72
void finalize()
Construct any deferred debug info descriptors.
Definition: DIBuilder.cpp:64
DISubroutineType * createSubroutineType(DITypeRefArray ParameterTypes, DINode::DIFlags Flags=DINode::FlagZero, unsigned CC=0)
Create subroutine type.
Definition: DIBuilder.cpp:559
void finalizeSubprogram(DISubprogram *SP)
Finalize a specific subprogram - no new variables may be added to this subprogram afterwards.
Definition: DIBuilder.cpp:56
DICompileUnit * createCompileUnit(unsigned Lang, DIFile *File, StringRef Producer, bool isOptimized, StringRef Flags, unsigned RV, StringRef SplitName=StringRef(), DICompileUnit::DebugEmissionKind Kind=DICompileUnit::DebugEmissionKind::FullDebug, uint64_t DWOId=0, bool SplitDebugInlining=true, bool DebugInfoForProfiling=false, DICompileUnit::DebugNameTableKind NameTableKind=DICompileUnit::DebugNameTableKind::Default, bool RangesBaseAddress=false, StringRef SysRoot={}, StringRef SDK={})
A CompileUnit provides an anchor for all debugging information generated during this instance of comp...
Definition: DIBuilder.cpp:135
DISubprogram * createFunction(DIScope *Scope, StringRef Name, StringRef LinkageName, DIFile *File, unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine, DINode::DIFlags Flags=DINode::FlagZero, DISubprogram::DISPFlags SPFlags=DISubprogram::SPFlagZero, DITemplateParameterArray TParams=nullptr, DISubprogram *Decl=nullptr, DITypeArray ThrownTypes=nullptr, DINodeArray Annotations=nullptr, StringRef TargetFuncName="")
Create a new descriptor for the specified subprogram.
Definition: DIBuilder.cpp:855
DIExpression * createExpression(ArrayRef< uint64_t > Addr=std::nullopt)
Create a new descriptor for the specified variable which has a complex address expression for its add...
Definition: DIBuilder.cpp:844
DIBasicType * createBasicType(StringRef Name, uint64_t SizeInBits, unsigned Encoding, DINode::DIFlags Flags=DINode::FlagZero)
Create debugging information entry for a basic type.
Definition: DIBuilder.cpp:267
DITypeRefArray getOrCreateTypeArray(ArrayRef< Metadata * > Elements)
Get a DITypeRefArray, create one if required.
Definition: DIBuilder.cpp:702
DILocalVariable * createAutoVariable(DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo, DIType *Ty, bool AlwaysPreserve=false, DINode::DIFlags Flags=DINode::FlagZero, uint32_t AlignInBits=0)
Create a new descriptor for an auto variable.
Definition: DIBuilder.cpp:806
DIFile * createFile(StringRef Filename, StringRef Directory, std::optional< DIFile::ChecksumInfo< StringRef > > Checksum=std::nullopt, std::optional< StringRef > Source=std::nullopt)
Create a file descriptor to hold debugging information for a file.
Definition: DIBuilder.cpp:215
Debug location.
Tagged DWARF-like metadata node.
DISPFlags
Debug info subprogram flags.
Base class for types.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:20
void registerCallbacks(PassInstrumentationCallbacks &PIC, ModuleAnalysisManager &MAM)
Definition: Debugify.cpp:1058
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Function.cpp:469
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:290
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:563
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:466
const char * getOpcodeName() const
Definition: Instruction.h:276
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
Metadata node.
Definition: Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1430
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1542
size_type count(const KeyT &Key) const
Definition: MapVector.h:165
iterator end()
Definition: MapVector.h:71
iterator find(const KeyT &Key)
Definition: MapVector.h:167
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: MapVector.h:141
size_type size() const
Definition: MapVector.h:60
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:251
virtual bool runOnModule(Module &M)=0
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
@ Warning
Emits a warning if two values disagree.
Definition: Module.h:122
A tuple of MDNodes.
Definition: Metadata.h:1730
void eraseFromParent()
Drop all references and remove the node from parent module.
Definition: Metadata.cpp:1401
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1388
unsigned getNumOperands() const
Definition: Metadata.cpp:1384
void clearOperands()
Drop all references to this node's operands.
Definition: Metadata.cpp:1403
iterator_range< op_iterator > operands()
Definition: Metadata.h:1826
void addOperand(MDNode *M)
Definition: Metadata.cpp:1394
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
void registerBeforeNonSkippedPassCallback(CallableT C)
void registerAfterPassCallback(CallableT C, bool ToFront=false)
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:94
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:146
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1210
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:298
static IntegerType * getInt32Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:224
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:139
static ConstantAsMetadata * getConstant(Value *C)
Definition: Metadata.h:472
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
bool use_empty() const
Definition: Value.h:344
A range adaptor for a pair of iterators.
An Array is a JSON array, which contains heterogeneous JSON values.
Definition: JSON.h:164
bool empty() const
Definition: JSON.h:547
void push_back(const Value &E)
Definition: JSON.h:552
An Object is a JSON object, which maps strings to heterogenous JSON values.
Definition: JSON.h:98
A Value is an JSON value of unknown type.
Definition: JSON.h:288
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:460
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:711
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition: FileSystem.h:767
@ OF_Append
The file should be opened in append mode.
Definition: FileSystem.h:770
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool applyDebugifyMetadata(Module &M, iterator_range< Module::iterator > Functions, StringRef Banner, std::function< bool(DIBuilder &, Function &)> ApplyToMF)
Add synthesized debug information to a module.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool stripDebugifyMetadata(Module &M)
Strip out all of the metadata and debug info inserted by debugify.
Definition: Debugify.cpp:245
void exportDebugifyStats(StringRef Path, const DebugifyStatsMap &Map)
Definition: Debugify.cpp:959
bool collectDebugInfoMetadata(Module &M, iterator_range< Module::iterator > Functions, DebugInfoPerPass &DebugInfoBeforePass, StringRef Banner, StringRef NameOfWrappedPass)
Collect original debug information before a pass.
Definition: Debugify.cpp:295
bool checkDebugInfoMetadata(Module &M, iterator_range< Module::iterator > Functions, DebugInfoPerPass &DebugInfoBeforePass, StringRef Banner, StringRef NameOfWrappedPass, StringRef OrigDIVerifyBugsReportFilePath)
Check original debug information after a pass.
Definition: Debugify.cpp:541
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool isSpecialPass(StringRef PassID, const std::vector< StringRef > &Specials)
raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
Definition: DebugInfo.cpp:591
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
@ DEBUG_METADATA_VERSION
Definition: Metadata.h:52
#define N
Used to track the Debug Info Metadata information.
Definition: Debugify.h:36
DebugInstMap DILocations
Definition: Debugify.h:40
DebugFnMap DIFunctions
Definition: Debugify.h:38
DebugVarMap DIVariables
Definition: Debugify.h:45
WeakInstValueMap InstToDelete
Definition: Debugify.h:43
Track how much debugify information (in the synthetic mode only) has been lost.
Definition: Debugify.h:123
RegisterPass<t> template - This template class is used to notify the system that a Pass is available ...
Definition: PassSupport.h:107