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/IR/DIBuilder.h"
20 #include "llvm/IR/DebugInfo.h"
21 #include "llvm/IR/InstIterator.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/PassInstrumentation.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/JSON.h"
29 
30 #define DEBUG_TYPE "debugify"
31 
32 using namespace llvm;
33 
34 namespace {
35 
36 cl::opt<bool> Quiet("debugify-quiet",
37                     cl::desc("Suppress verbose debugify output"));
38 
39 enum class Level {
40   Locations,
41   LocationsAndVariables
42 };
43 
44 // Used for the synthetic mode only.
45 cl::opt<Level> DebugifyLevel(
46     "debugify-level", cl::desc("Kind of debug info to add"),
47     cl::values(clEnumValN(Level::Locations, "locations", "Locations only"),
48                clEnumValN(Level::LocationsAndVariables, "location+variables",
49                           "Locations and Variables")),
50     cl::init(Level::LocationsAndVariables));
51 
52 raw_ostream &dbg() { return Quiet ? nulls() : errs(); }
53 
54 uint64_t getAllocSizeInBits(Module &M, Type *Ty) {
55   return Ty->isSized() ? M.getDataLayout().getTypeAllocSizeInBits(Ty) : 0;
56 }
57 
58 bool isFunctionSkipped(Function &F) {
59   return F.isDeclaration() || !F.hasExactDefinition();
60 }
61 
62 /// Find the basic block's terminating instruction.
63 ///
64 /// Special care is needed to handle musttail and deopt calls, as these behave
65 /// like (but are in fact not) terminators.
66 Instruction *findTerminatingInstruction(BasicBlock &BB) {
67   if (auto *I = BB.getTerminatingMustTailCall())
68     return I;
69   if (auto *I = BB.getTerminatingDeoptimizeCall())
70     return I;
71   return BB.getTerminator();
72 }
73 } // end anonymous namespace
74 
75 bool llvm::applyDebugifyMetadata(
76     Module &M, iterator_range<Module::iterator> Functions, StringRef Banner,
77     std::function<bool(DIBuilder &DIB, Function &F)> ApplyToMF) {
78   // Skip modules with debug info.
79   if (M.getNamedMetadata("llvm.dbg.cu")) {
80     dbg() << Banner << "Skipping module with debug info\n";
81     return false;
82   }
83 
84   DIBuilder DIB(M);
85   LLVMContext &Ctx = M.getContext();
86   auto *Int32Ty = Type::getInt32Ty(Ctx);
87 
88   // Get a DIType which corresponds to Ty.
89   DenseMap<uint64_t, DIType *> TypeCache;
90   auto getCachedDIType = [&](Type *Ty) -> DIType * {
91     uint64_t Size = getAllocSizeInBits(M, Ty);
92     DIType *&DTy = TypeCache[Size];
93     if (!DTy) {
94       std::string Name = "ty" + utostr(Size);
95       DTy = DIB.createBasicType(Name, Size, dwarf::DW_ATE_unsigned);
96     }
97     return DTy;
98   };
99 
100   unsigned NextLine = 1;
101   unsigned NextVar = 1;
102   auto File = DIB.createFile(M.getName(), "/");
103   auto CU = DIB.createCompileUnit(dwarf::DW_LANG_C, File, "debugify",
104                                   /*isOptimized=*/true, "", 0);
105 
106   // Visit each instruction.
107   for (Function &F : Functions) {
108     if (isFunctionSkipped(F))
109       continue;
110 
111     bool InsertedDbgVal = false;
112     auto SPType = DIB.createSubroutineType(DIB.getOrCreateTypeArray(None));
113     DISubprogram::DISPFlags SPFlags =
114         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized;
115     if (F.hasPrivateLinkage() || F.hasInternalLinkage())
116       SPFlags |= DISubprogram::SPFlagLocalToUnit;
117     auto SP = DIB.createFunction(CU, F.getName(), F.getName(), File, NextLine,
118                                  SPType, NextLine, DINode::FlagZero, SPFlags);
119     F.setSubprogram(SP);
120 
121     // Helper that inserts a dbg.value before \p InsertBefore, copying the
122     // location (and possibly the type, if it's non-void) from \p TemplateInst.
123     auto insertDbgVal = [&](Instruction &TemplateInst,
124                             Instruction *InsertBefore) {
125       std::string Name = utostr(NextVar++);
126       Value *V = &TemplateInst;
127       if (TemplateInst.getType()->isVoidTy())
128         V = ConstantInt::get(Int32Ty, 0);
129       const DILocation *Loc = TemplateInst.getDebugLoc().get();
130       auto LocalVar = DIB.createAutoVariable(SP, Name, File, Loc->getLine(),
131                                              getCachedDIType(V->getType()),
132                                              /*AlwaysPreserve=*/true);
133       DIB.insertDbgValueIntrinsic(V, LocalVar, DIB.createExpression(), Loc,
134                                   InsertBefore);
135     };
136 
137     for (BasicBlock &BB : F) {
138       // Attach debug locations.
139       for (Instruction &I : BB)
140         I.setDebugLoc(DILocation::get(Ctx, NextLine++, 1, SP));
141 
142       if (DebugifyLevel < Level::LocationsAndVariables)
143         continue;
144 
145       // Inserting debug values into EH pads can break IR invariants.
146       if (BB.isEHPad())
147         continue;
148 
149       // Find the terminating instruction, after which no debug values are
150       // attached.
151       Instruction *LastInst = findTerminatingInstruction(BB);
152       assert(LastInst && "Expected basic block with a terminator");
153 
154       // Maintain an insertion point which can't be invalidated when updates
155       // are made.
156       BasicBlock::iterator InsertPt = BB.getFirstInsertionPt();
157       assert(InsertPt != BB.end() && "Expected to find an insertion point");
158       Instruction *InsertBefore = &*InsertPt;
159 
160       // Attach debug values.
161       for (Instruction *I = &*BB.begin(); I != LastInst; I = I->getNextNode()) {
162         // Skip void-valued instructions.
163         if (I->getType()->isVoidTy())
164           continue;
165 
166         // Phis and EH pads must be grouped at the beginning of the block.
167         // Only advance the insertion point when we finish visiting these.
168         if (!isa<PHINode>(I) && !I->isEHPad())
169           InsertBefore = I->getNextNode();
170 
171         insertDbgVal(*I, InsertBefore);
172         InsertedDbgVal = true;
173       }
174     }
175     // Make sure we emit at least one dbg.value, otherwise MachineDebugify may
176     // not have anything to work with as it goes about inserting DBG_VALUEs.
177     // (It's common for MIR tests to be written containing skeletal IR with
178     // empty functions -- we're still interested in debugifying the MIR within
179     // those tests, and this helps with that.)
180     if (DebugifyLevel == Level::LocationsAndVariables && !InsertedDbgVal) {
181       auto *Term = findTerminatingInstruction(F.getEntryBlock());
182       insertDbgVal(*Term, Term);
183     }
184     if (ApplyToMF)
185       ApplyToMF(DIB, F);
186     DIB.finalizeSubprogram(SP);
187   }
188   DIB.finalize();
189 
190   // Track the number of distinct lines and variables.
191   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.debugify");
192   auto addDebugifyOperand = [&](unsigned N) {
193     NMD->addOperand(MDNode::get(
194         Ctx, ValueAsMetadata::getConstant(ConstantInt::get(Int32Ty, N))));
195   };
196   addDebugifyOperand(NextLine - 1); // Original number of lines.
197   addDebugifyOperand(NextVar - 1);  // Original number of variables.
198   assert(NMD->getNumOperands() == 2 &&
199          "llvm.debugify should have exactly 2 operands!");
200 
201   // Claim that this synthetic debug info is valid.
202   StringRef DIVersionKey = "Debug Info Version";
203   if (!M.getModuleFlag(DIVersionKey))
204     M.addModuleFlag(Module::Warning, DIVersionKey, DEBUG_METADATA_VERSION);
205 
206   return true;
207 }
208 
209 static bool
210 applyDebugify(Function &F,
211               enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
212               DebugInfoPerPassMap *DIPreservationMap = nullptr,
213               StringRef NameOfWrappedPass = "") {
214   Module &M = *F.getParent();
215   auto FuncIt = F.getIterator();
216   if (Mode == DebugifyMode::SyntheticDebugInfo)
217     return applyDebugifyMetadata(M, make_range(FuncIt, std::next(FuncIt)),
218                                  "FunctionDebugify: ", /*ApplyToMF*/ nullptr);
219   assert(DIPreservationMap);
220   return collectDebugInfoMetadata(M, M.functions(), *DIPreservationMap,
221                                   "FunctionDebugify (original debuginfo)",
222                                   NameOfWrappedPass);
223 }
224 
225 static bool
226 applyDebugify(Module &M,
227               enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
228               DebugInfoPerPassMap *DIPreservationMap = nullptr,
229               StringRef NameOfWrappedPass = "") {
230   if (Mode == DebugifyMode::SyntheticDebugInfo)
231     return applyDebugifyMetadata(M, M.functions(),
232                                  "ModuleDebugify: ", /*ApplyToMF*/ nullptr);
233   return collectDebugInfoMetadata(M, M.functions(), *DIPreservationMap,
234                                   "ModuleDebugify (original debuginfo)",
235                                   NameOfWrappedPass);
236 }
237 
238 bool llvm::stripDebugifyMetadata(Module &M) {
239   bool Changed = false;
240 
241   // Remove the llvm.debugify module-level named metadata.
242   NamedMDNode *DebugifyMD = M.getNamedMetadata("llvm.debugify");
243   if (DebugifyMD) {
244     M.eraseNamedMetadata(DebugifyMD);
245     Changed = true;
246   }
247 
248   // Strip out all debug intrinsics and supporting metadata (subprograms, types,
249   // variables, etc).
250   Changed |= StripDebugInfo(M);
251 
252   // Strip out the dead dbg.value prototype.
253   Function *DbgValF = M.getFunction("llvm.dbg.value");
254   if (DbgValF) {
255     assert(DbgValF->isDeclaration() && DbgValF->use_empty() &&
256            "Not all debug info stripped?");
257     DbgValF->eraseFromParent();
258     Changed = true;
259   }
260 
261   // Strip out the module-level Debug Info Version metadata.
262   // FIXME: There must be an easier way to remove an operand from a NamedMDNode.
263   NamedMDNode *NMD = M.getModuleFlagsMetadata();
264   if (!NMD)
265     return Changed;
266   SmallVector<MDNode *, 4> Flags(NMD->operands());
267   NMD->clearOperands();
268   for (MDNode *Flag : Flags) {
269     MDString *Key = dyn_cast_or_null<MDString>(Flag->getOperand(1));
270     if (Key->getString() == "Debug Info Version") {
271       Changed = true;
272       continue;
273     }
274     NMD->addOperand(Flag);
275   }
276   // If we left it empty we might as well remove it.
277   if (NMD->getNumOperands() == 0)
278     NMD->eraseFromParent();
279 
280   return Changed;
281 }
282 
283 bool llvm::collectDebugInfoMetadata(Module &M,
284                                     iterator_range<Module::iterator> Functions,
285                                     DebugInfoPerPassMap &DIPreservationMap,
286                                     StringRef Banner,
287                                     StringRef NameOfWrappedPass) {
288   LLVM_DEBUG(dbgs() << Banner << ": (before) " << NameOfWrappedPass << '\n');
289 
290   // Clear the map with the debug info before every single pass.
291   DIPreservationMap.clear();
292 
293   if (!M.getNamedMetadata("llvm.dbg.cu")) {
294     dbg() << Banner << ": Skipping module without debug info\n";
295     return false;
296   }
297 
298   // Visit each instruction.
299   for (Function &F : Functions) {
300     if (isFunctionSkipped(F))
301       continue;
302 
303     // Collect the DISubprogram.
304     auto *SP = F.getSubprogram();
305     DIPreservationMap[NameOfWrappedPass].DIFunctions.insert({F.getName(), SP});
306     if (SP)
307       LLVM_DEBUG(dbgs() << "  Collecting subprogram: " << *SP << '\n');
308 
309     for (BasicBlock &BB : F) {
310       // Collect debug locations (!dbg).
311       // TODO: Collect dbg.values.
312       for (Instruction &I : BB) {
313         // Skip PHIs.
314         if (isa<PHINode>(I))
315           continue;
316 
317         // Skip debug instructions.
318         if (isa<DbgInfoIntrinsic>(&I))
319           continue;
320 
321         LLVM_DEBUG(dbgs() << "  Collecting info for inst: " << I << '\n');
322         DIPreservationMap[NameOfWrappedPass].InstToDelete.insert({&I, &I});
323 
324         const DILocation *Loc = I.getDebugLoc().get();
325         bool HasLoc = Loc != nullptr;
326         DIPreservationMap[NameOfWrappedPass].DILocations.insert({&I, HasLoc});
327       }
328     }
329   }
330 
331   return true;
332 }
333 
334 // This checks the preservation of original debug info attached to functions.
335 static bool checkFunctions(const DebugFnMap &DIFunctionsBefore,
336                            const DebugFnMap &DIFunctionsAfter,
337                            StringRef NameOfWrappedPass,
338                            StringRef FileNameFromCU, bool ShouldWriteIntoJSON,
339                            llvm::json::Array &Bugs) {
340   bool Preserved = true;
341   for (const auto &F : DIFunctionsAfter) {
342     if (F.second)
343       continue;
344     auto SPIt = DIFunctionsBefore.find(F.first);
345     if (SPIt == DIFunctionsBefore.end()) {
346       if (ShouldWriteIntoJSON)
347         Bugs.push_back(llvm::json::Object({{"metadata", "DISubprogram"},
348                                            {"name", F.first},
349                                            {"action", "not-generate"}}));
350       else
351         dbg() << "ERROR: " << NameOfWrappedPass
352               << " did not generate DISubprogram for " << F.first << " from "
353               << FileNameFromCU << '\n';
354       Preserved = false;
355     } else {
356       auto SP = SPIt->second;
357       if (!SP)
358         continue;
359       // If the function had the SP attached before the pass, consider it as
360       // a debug info bug.
361       if (ShouldWriteIntoJSON)
362         Bugs.push_back(llvm::json::Object({{"metadata", "DISubprogram"},
363                                            {"name", F.first},
364                                            {"action", "drop"}}));
365       else
366         dbg() << "ERROR: " << NameOfWrappedPass << " dropped DISubprogram of "
367               << F.first << " from " << FileNameFromCU << '\n';
368       Preserved = false;
369     }
370   }
371 
372   return Preserved;
373 }
374 
375 // This checks the preservation of the original debug info attached to
376 // instructions.
377 static bool checkInstructions(const DebugInstMap &DILocsBefore,
378                               const DebugInstMap &DILocsAfter,
379                               const WeakInstValueMap &InstToDelete,
380                               StringRef NameOfWrappedPass,
381                               StringRef FileNameFromCU,
382                               bool ShouldWriteIntoJSON,
383                               llvm::json::Array &Bugs) {
384   bool Preserved = true;
385   for (const auto &L : DILocsAfter) {
386     if (L.second)
387       continue;
388     auto Instr = L.first;
389 
390     // In order to avoid pointer reuse/recycling, skip the values that might
391     // have been deleted during a pass.
392     auto WeakInstrPtr = InstToDelete.find(Instr);
393     if (WeakInstrPtr != InstToDelete.end() && !WeakInstrPtr->second)
394       continue;
395 
396     auto FnName = Instr->getFunction()->getName();
397     auto BB = Instr->getParent();
398     auto BBName = BB->hasName() ? BB->getName() : "no-name";
399     auto InstName = Instruction::getOpcodeName(Instr->getOpcode());
400 
401     auto InstrIt = DILocsBefore.find(Instr);
402     if (InstrIt == DILocsBefore.end()) {
403       if (ShouldWriteIntoJSON)
404         Bugs.push_back(llvm::json::Object({{"metadata", "DILocation"},
405                                            {"fn-name", FnName.str()},
406                                            {"bb-name", BBName.str()},
407                                            {"instr", InstName},
408                                            {"action", "not-generate"}}));
409       else
410         dbg() << "WARNING: " << NameOfWrappedPass
411               << " did not generate DILocation for " << *Instr
412               << " (BB: " << BBName << ", Fn: " << FnName
413               << ", File: " << FileNameFromCU << ")\n";
414       Preserved = false;
415     } else {
416       if (!InstrIt->second)
417         continue;
418       // If the instr had the !dbg attached before the pass, consider it as
419       // a debug info issue.
420       if (ShouldWriteIntoJSON)
421         Bugs.push_back(llvm::json::Object({{"metadata", "DILocation"},
422                                            {"fn-name", FnName.str()},
423                                            {"bb-name", BBName.str()},
424                                            {"instr", InstName},
425                                            {"action", "drop"}}));
426       else
427         dbg() << "WARNING: " << NameOfWrappedPass << " dropped DILocation of "
428               << *Instr << " (BB: " << BBName << ", Fn: " << FnName
429               << ", File: " << FileNameFromCU << ")\n";
430       Preserved = false;
431     }
432   }
433 
434   return Preserved;
435 }
436 
437 // Write the json data into the specifed file.
438 static void writeJSON(StringRef OrigDIVerifyBugsReportFilePath,
439                       StringRef FileNameFromCU, StringRef NameOfWrappedPass,
440                       llvm::json::Array &Bugs) {
441   std::error_code EC;
442   raw_fd_ostream OS_FILE{OrigDIVerifyBugsReportFilePath, EC,
443                          sys::fs::OF_Append | sys::fs::OF_Text};
444   if (EC) {
445     errs() << "Could not open file: " << EC.message() << ", "
446            << OrigDIVerifyBugsReportFilePath << '\n';
447     return;
448   }
449 
450   OS_FILE << "{\"file\":\"" << FileNameFromCU << "\", ";
451 
452   StringRef PassName = NameOfWrappedPass != "" ? NameOfWrappedPass : "no-name";
453   OS_FILE << "\"pass\":\"" << PassName << "\", ";
454 
455   llvm::json::Value BugsToPrint{std::move(Bugs)};
456   OS_FILE << "\"bugs\": " << BugsToPrint;
457 
458   OS_FILE << "}\n";
459 }
460 
461 bool llvm::checkDebugInfoMetadata(Module &M,
462                                   iterator_range<Module::iterator> Functions,
463                                   DebugInfoPerPassMap &DIPreservationMap,
464                                   StringRef Banner, StringRef NameOfWrappedPass,
465                                   StringRef OrigDIVerifyBugsReportFilePath) {
466   LLVM_DEBUG(dbgs() << Banner << ": (after) " << NameOfWrappedPass << '\n');
467 
468   if (!M.getNamedMetadata("llvm.dbg.cu")) {
469     dbg() << Banner << ": Skipping module without debug info\n";
470     return false;
471   }
472 
473   // Map the debug info holding DIs after a pass.
474   DebugInfoPerPassMap DIPreservationAfter;
475 
476   // Visit each instruction.
477   for (Function &F : Functions) {
478     if (isFunctionSkipped(F))
479       continue;
480 
481     // TODO: Collect metadata other than DISubprograms.
482     // Collect the DISubprogram.
483     auto *SP = F.getSubprogram();
484     DIPreservationAfter[NameOfWrappedPass].DIFunctions.insert(
485         {F.getName(), SP});
486     if (SP)
487       LLVM_DEBUG(dbgs() << "  Collecting subprogram: " << *SP << '\n');
488 
489     for (BasicBlock &BB : F) {
490       // Collect debug locations (!dbg attachments).
491       // TODO: Collect dbg.values.
492       for (Instruction &I : BB) {
493         // Skip PHIs.
494         if (isa<PHINode>(I))
495           continue;
496 
497         // Skip debug instructions.
498         if (isa<DbgInfoIntrinsic>(&I))
499           continue;
500 
501         LLVM_DEBUG(dbgs() << "  Collecting info for inst: " << I << '\n');
502 
503         const DILocation *Loc = I.getDebugLoc().get();
504         bool HasLoc = Loc != nullptr;
505 
506         DIPreservationAfter[NameOfWrappedPass].DILocations.insert({&I, HasLoc});
507       }
508     }
509   }
510 
511   // TODO: The name of the module could be read better?
512   StringRef FileNameFromCU =
513       (cast<DICompileUnit>(M.getNamedMetadata("llvm.dbg.cu")->getOperand(0)))
514           ->getFilename();
515 
516   auto DIFunctionsBefore = DIPreservationMap[NameOfWrappedPass].DIFunctions;
517   auto DIFunctionsAfter = DIPreservationAfter[NameOfWrappedPass].DIFunctions;
518 
519   auto DILocsBefore = DIPreservationMap[NameOfWrappedPass].DILocations;
520   auto DILocsAfter = DIPreservationAfter[NameOfWrappedPass].DILocations;
521 
522   auto InstToDelete = DIPreservationAfter[NameOfWrappedPass].InstToDelete;
523 
524   bool ShouldWriteIntoJSON = !OrigDIVerifyBugsReportFilePath.empty();
525   llvm::json::Array Bugs;
526 
527   bool ResultForFunc =
528       checkFunctions(DIFunctionsBefore, DIFunctionsAfter, NameOfWrappedPass,
529                      FileNameFromCU, ShouldWriteIntoJSON, Bugs);
530   bool ResultForInsts = checkInstructions(
531       DILocsBefore, DILocsAfter, InstToDelete, NameOfWrappedPass,
532       FileNameFromCU, ShouldWriteIntoJSON, Bugs);
533   bool Result = ResultForFunc && ResultForInsts;
534 
535   StringRef ResultBanner = NameOfWrappedPass != "" ? NameOfWrappedPass : Banner;
536   if (ShouldWriteIntoJSON && !Bugs.empty())
537     writeJSON(OrigDIVerifyBugsReportFilePath, FileNameFromCU, NameOfWrappedPass,
538               Bugs);
539 
540   if (Result)
541     dbg() << ResultBanner << ": PASS\n";
542   else
543     dbg() << ResultBanner << ": FAIL\n";
544 
545   LLVM_DEBUG(dbgs() << "\n\n");
546   return Result;
547 }
548 
549 namespace {
550 /// Return true if a mis-sized diagnostic is issued for \p DVI.
551 bool diagnoseMisSizedDbgValue(Module &M, DbgValueInst *DVI) {
552   // The size of a dbg.value's value operand should match the size of the
553   // variable it corresponds to.
554   //
555   // TODO: This, along with a check for non-null value operands, should be
556   // promoted to verifier failures.
557   Value *V = DVI->getValue();
558   if (!V)
559     return false;
560 
561   // For now, don't try to interpret anything more complicated than an empty
562   // DIExpression. Eventually we should try to handle OP_deref and fragments.
563   if (DVI->getExpression()->getNumElements())
564     return false;
565 
566   Type *Ty = V->getType();
567   uint64_t ValueOperandSize = getAllocSizeInBits(M, Ty);
568   Optional<uint64_t> DbgVarSize = DVI->getFragmentSizeInBits();
569   if (!ValueOperandSize || !DbgVarSize)
570     return false;
571 
572   bool HasBadSize = false;
573   if (Ty->isIntegerTy()) {
574     auto Signedness = DVI->getVariable()->getSignedness();
575     if (Signedness && *Signedness == DIBasicType::Signedness::Signed)
576       HasBadSize = ValueOperandSize < *DbgVarSize;
577   } else {
578     HasBadSize = ValueOperandSize != *DbgVarSize;
579   }
580 
581   if (HasBadSize) {
582     dbg() << "ERROR: dbg.value operand has size " << ValueOperandSize
583           << ", but its variable has size " << *DbgVarSize << ": ";
584     DVI->print(dbg());
585     dbg() << "\n";
586   }
587   return HasBadSize;
588 }
589 
590 bool checkDebugifyMetadata(Module &M,
591                            iterator_range<Module::iterator> Functions,
592                            StringRef NameOfWrappedPass, StringRef Banner,
593                            bool Strip, DebugifyStatsMap *StatsMap) {
594   // Skip modules without debugify metadata.
595   NamedMDNode *NMD = M.getNamedMetadata("llvm.debugify");
596   if (!NMD) {
597     dbg() << Banner << ": Skipping module without debugify metadata\n";
598     return false;
599   }
600 
601   auto getDebugifyOperand = [&](unsigned Idx) -> unsigned {
602     return mdconst::extract<ConstantInt>(NMD->getOperand(Idx)->getOperand(0))
603         ->getZExtValue();
604   };
605   assert(NMD->getNumOperands() == 2 &&
606          "llvm.debugify should have exactly 2 operands!");
607   unsigned OriginalNumLines = getDebugifyOperand(0);
608   unsigned OriginalNumVars = getDebugifyOperand(1);
609   bool HasErrors = false;
610 
611   // Track debug info loss statistics if able.
612   DebugifyStatistics *Stats = nullptr;
613   if (StatsMap && !NameOfWrappedPass.empty())
614     Stats = &StatsMap->operator[](NameOfWrappedPass);
615 
616   BitVector MissingLines{OriginalNumLines, true};
617   BitVector MissingVars{OriginalNumVars, true};
618   for (Function &F : Functions) {
619     if (isFunctionSkipped(F))
620       continue;
621 
622     // Find missing lines.
623     for (Instruction &I : instructions(F)) {
624       if (isa<DbgValueInst>(&I) || isa<PHINode>(&I))
625         continue;
626 
627       auto DL = I.getDebugLoc();
628       if (DL && DL.getLine() != 0) {
629         MissingLines.reset(DL.getLine() - 1);
630         continue;
631       }
632 
633       if (!DL) {
634         dbg() << "WARNING: Instruction with empty DebugLoc in function ";
635         dbg() << F.getName() << " --";
636         I.print(dbg());
637         dbg() << "\n";
638       }
639     }
640 
641     // Find missing variables and mis-sized debug values.
642     for (Instruction &I : instructions(F)) {
643       auto *DVI = dyn_cast<DbgValueInst>(&I);
644       if (!DVI)
645         continue;
646 
647       unsigned Var = ~0U;
648       (void)to_integer(DVI->getVariable()->getName(), Var, 10);
649       assert(Var <= OriginalNumVars && "Unexpected name for DILocalVariable");
650       bool HasBadSize = diagnoseMisSizedDbgValue(M, DVI);
651       if (!HasBadSize)
652         MissingVars.reset(Var - 1);
653       HasErrors |= HasBadSize;
654     }
655   }
656 
657   // Print the results.
658   for (unsigned Idx : MissingLines.set_bits())
659     dbg() << "WARNING: Missing line " << Idx + 1 << "\n";
660 
661   for (unsigned Idx : MissingVars.set_bits())
662     dbg() << "WARNING: Missing variable " << Idx + 1 << "\n";
663 
664   // Update DI loss statistics.
665   if (Stats) {
666     Stats->NumDbgLocsExpected += OriginalNumLines;
667     Stats->NumDbgLocsMissing += MissingLines.count();
668     Stats->NumDbgValuesExpected += OriginalNumVars;
669     Stats->NumDbgValuesMissing += MissingVars.count();
670   }
671 
672   dbg() << Banner;
673   if (!NameOfWrappedPass.empty())
674     dbg() << " [" << NameOfWrappedPass << "]";
675   dbg() << ": " << (HasErrors ? "FAIL" : "PASS") << '\n';
676 
677   // Strip debugify metadata if required.
678   if (Strip)
679     return stripDebugifyMetadata(M);
680 
681   return false;
682 }
683 
684 /// ModulePass for attaching synthetic debug info to everything, used with the
685 /// legacy module pass manager.
686 struct DebugifyModulePass : public ModulePass {
687   bool runOnModule(Module &M) override {
688     return applyDebugify(M, Mode, DIPreservationMap, NameOfWrappedPass);
689   }
690 
691   DebugifyModulePass(enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
692                      StringRef NameOfWrappedPass = "",
693                      DebugInfoPerPassMap *DIPreservationMap = nullptr)
694       : ModulePass(ID), NameOfWrappedPass(NameOfWrappedPass),
695         DIPreservationMap(DIPreservationMap), Mode(Mode) {}
696 
697   void getAnalysisUsage(AnalysisUsage &AU) const override {
698     AU.setPreservesAll();
699   }
700 
701   static char ID; // Pass identification.
702 
703 private:
704   StringRef NameOfWrappedPass;
705   DebugInfoPerPassMap *DIPreservationMap;
706   enum DebugifyMode Mode;
707 };
708 
709 /// FunctionPass for attaching synthetic debug info to instructions within a
710 /// single function, used with the legacy module pass manager.
711 struct DebugifyFunctionPass : public FunctionPass {
712   bool runOnFunction(Function &F) override {
713     return applyDebugify(F, Mode, DIPreservationMap, NameOfWrappedPass);
714   }
715 
716   DebugifyFunctionPass(
717       enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
718       StringRef NameOfWrappedPass = "",
719       DebugInfoPerPassMap *DIPreservationMap = nullptr)
720       : FunctionPass(ID), NameOfWrappedPass(NameOfWrappedPass),
721         DIPreservationMap(DIPreservationMap), Mode(Mode) {}
722 
723   void getAnalysisUsage(AnalysisUsage &AU) const override {
724     AU.setPreservesAll();
725   }
726 
727   static char ID; // Pass identification.
728 
729 private:
730   StringRef NameOfWrappedPass;
731   DebugInfoPerPassMap *DIPreservationMap;
732   enum DebugifyMode Mode;
733 };
734 
735 /// ModulePass for checking debug info inserted by -debugify, used with the
736 /// legacy module pass manager.
737 struct CheckDebugifyModulePass : public ModulePass {
738   bool runOnModule(Module &M) override {
739     if (Mode == DebugifyMode::SyntheticDebugInfo)
740       return checkDebugifyMetadata(M, M.functions(), NameOfWrappedPass,
741                                    "CheckModuleDebugify", Strip, StatsMap);
742     return checkDebugInfoMetadata(
743         M, M.functions(), *DIPreservationMap,
744         "CheckModuleDebugify (original debuginfo)", NameOfWrappedPass,
745         OrigDIVerifyBugsReportFilePath);
746   }
747 
748   CheckDebugifyModulePass(
749       bool Strip = false, StringRef NameOfWrappedPass = "",
750       DebugifyStatsMap *StatsMap = nullptr,
751       enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
752       DebugInfoPerPassMap *DIPreservationMap = nullptr,
753       StringRef OrigDIVerifyBugsReportFilePath = "")
754       : ModulePass(ID), NameOfWrappedPass(NameOfWrappedPass),
755         OrigDIVerifyBugsReportFilePath(OrigDIVerifyBugsReportFilePath),
756         StatsMap(StatsMap), DIPreservationMap(DIPreservationMap), Mode(Mode),
757         Strip(Strip) {}
758 
759   void getAnalysisUsage(AnalysisUsage &AU) const override {
760     AU.setPreservesAll();
761   }
762 
763   static char ID; // Pass identification.
764 
765 private:
766   StringRef NameOfWrappedPass;
767   StringRef OrigDIVerifyBugsReportFilePath;
768   DebugifyStatsMap *StatsMap;
769   DebugInfoPerPassMap *DIPreservationMap;
770   enum DebugifyMode Mode;
771   bool Strip;
772 };
773 
774 /// FunctionPass for checking debug info inserted by -debugify-function, used
775 /// with the legacy module pass manager.
776 struct CheckDebugifyFunctionPass : public FunctionPass {
777   bool runOnFunction(Function &F) override {
778     Module &M = *F.getParent();
779     auto FuncIt = F.getIterator();
780     if (Mode == DebugifyMode::SyntheticDebugInfo)
781       return checkDebugifyMetadata(M, make_range(FuncIt, std::next(FuncIt)),
782                                    NameOfWrappedPass, "CheckFunctionDebugify",
783                                    Strip, StatsMap);
784     return checkDebugInfoMetadata(
785         M, make_range(FuncIt, std::next(FuncIt)), *DIPreservationMap,
786         "CheckFunctionDebugify (original debuginfo)", NameOfWrappedPass,
787         OrigDIVerifyBugsReportFilePath);
788   }
789 
790   CheckDebugifyFunctionPass(
791       bool Strip = false, StringRef NameOfWrappedPass = "",
792       DebugifyStatsMap *StatsMap = nullptr,
793       enum DebugifyMode Mode = DebugifyMode::SyntheticDebugInfo,
794       DebugInfoPerPassMap *DIPreservationMap = nullptr,
795       StringRef OrigDIVerifyBugsReportFilePath = "")
796       : FunctionPass(ID), NameOfWrappedPass(NameOfWrappedPass),
797         OrigDIVerifyBugsReportFilePath(OrigDIVerifyBugsReportFilePath),
798         StatsMap(StatsMap), DIPreservationMap(DIPreservationMap), Mode(Mode),
799         Strip(Strip) {}
800 
801   void getAnalysisUsage(AnalysisUsage &AU) const override {
802     AU.setPreservesAll();
803   }
804 
805   static char ID; // Pass identification.
806 
807 private:
808   StringRef NameOfWrappedPass;
809   StringRef OrigDIVerifyBugsReportFilePath;
810   DebugifyStatsMap *StatsMap;
811   DebugInfoPerPassMap *DIPreservationMap;
812   enum DebugifyMode Mode;
813   bool Strip;
814 };
815 
816 } // end anonymous namespace
817 
818 void llvm::exportDebugifyStats(StringRef Path, const DebugifyStatsMap &Map) {
819   std::error_code EC;
820   raw_fd_ostream OS{Path, EC};
821   if (EC) {
822     errs() << "Could not open file: " << EC.message() << ", " << Path << '\n';
823     return;
824   }
825 
826   OS << "Pass Name" << ',' << "# of missing debug values" << ','
827      << "# of missing locations" << ',' << "Missing/Expected value ratio" << ','
828      << "Missing/Expected location ratio" << '\n';
829   for (const auto &Entry : Map) {
830     StringRef Pass = Entry.first;
831     DebugifyStatistics Stats = Entry.second;
832 
833     OS << Pass << ',' << Stats.NumDbgValuesMissing << ','
834        << Stats.NumDbgLocsMissing << ',' << Stats.getMissingValueRatio() << ','
835        << Stats.getEmptyLocationRatio() << '\n';
836   }
837 }
838 
839 ModulePass *createDebugifyModulePass(enum DebugifyMode Mode,
840                                      llvm::StringRef NameOfWrappedPass,
841                                      DebugInfoPerPassMap *DIPreservationMap) {
842   if (Mode == DebugifyMode::SyntheticDebugInfo)
843     return new DebugifyModulePass();
844   assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
845   return new DebugifyModulePass(Mode, NameOfWrappedPass, DIPreservationMap);
846 }
847 
848 FunctionPass *
849 createDebugifyFunctionPass(enum DebugifyMode Mode,
850                            llvm::StringRef NameOfWrappedPass,
851                            DebugInfoPerPassMap *DIPreservationMap) {
852   if (Mode == DebugifyMode::SyntheticDebugInfo)
853     return new DebugifyFunctionPass();
854   assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
855   return new DebugifyFunctionPass(Mode, NameOfWrappedPass, DIPreservationMap);
856 }
857 
858 PreservedAnalyses NewPMDebugifyPass::run(Module &M, ModuleAnalysisManager &) {
859   applyDebugifyMetadata(M, M.functions(),
860                         "ModuleDebugify: ", /*ApplyToMF*/ nullptr);
861   return PreservedAnalyses::all();
862 }
863 
864 ModulePass *createCheckDebugifyModulePass(
865     bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap,
866     enum DebugifyMode Mode, DebugInfoPerPassMap *DIPreservationMap,
867     StringRef OrigDIVerifyBugsReportFilePath) {
868   if (Mode == DebugifyMode::SyntheticDebugInfo)
869     return new CheckDebugifyModulePass(Strip, NameOfWrappedPass, StatsMap);
870   assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
871   return new CheckDebugifyModulePass(false, NameOfWrappedPass, nullptr, Mode,
872                                      DIPreservationMap,
873                                      OrigDIVerifyBugsReportFilePath);
874 }
875 
876 FunctionPass *createCheckDebugifyFunctionPass(
877     bool Strip, StringRef NameOfWrappedPass, DebugifyStatsMap *StatsMap,
878     enum DebugifyMode Mode, DebugInfoPerPassMap *DIPreservationMap,
879     StringRef OrigDIVerifyBugsReportFilePath) {
880   if (Mode == DebugifyMode::SyntheticDebugInfo)
881     return new CheckDebugifyFunctionPass(Strip, NameOfWrappedPass, StatsMap);
882   assert(Mode == DebugifyMode::OriginalDebugInfo && "Must be original mode");
883   return new CheckDebugifyFunctionPass(false, NameOfWrappedPass, nullptr, Mode,
884                                        DIPreservationMap,
885                                        OrigDIVerifyBugsReportFilePath);
886 }
887 
888 PreservedAnalyses NewPMCheckDebugifyPass::run(Module &M,
889                                               ModuleAnalysisManager &) {
890   checkDebugifyMetadata(M, M.functions(), "", "CheckModuleDebugify", false,
891                         nullptr);
892   return PreservedAnalyses::all();
893 }
894 
895 static bool isIgnoredPass(StringRef PassID) {
896   return isSpecialPass(PassID, {"PassManager", "PassAdaptor",
897                                 "AnalysisManagerProxy", "PrintFunctionPass",
898                                 "PrintModulePass", "BitcodeWriterPass",
899                                 "ThinLTOBitcodeWriterPass", "VerifierPass"});
900 }
901 
902 void DebugifyEachInstrumentation::registerCallbacks(
903     PassInstrumentationCallbacks &PIC) {
904   PIC.registerBeforeNonSkippedPassCallback([](StringRef P, Any IR) {
905     if (isIgnoredPass(P))
906       return;
907     if (any_isa<const Function *>(IR))
908       applyDebugify(*const_cast<Function *>(any_cast<const Function *>(IR)));
909     else if (any_isa<const Module *>(IR))
910       applyDebugify(*const_cast<Module *>(any_cast<const Module *>(IR)));
911   });
912   PIC.registerAfterPassCallback([this](StringRef P, Any IR,
913                                        const PreservedAnalyses &PassPA) {
914     if (isIgnoredPass(P))
915       return;
916     if (any_isa<const Function *>(IR)) {
917       auto &F = *const_cast<Function *>(any_cast<const Function *>(IR));
918       Module &M = *F.getParent();
919       auto It = F.getIterator();
920       checkDebugifyMetadata(M, make_range(It, std::next(It)), P,
921                             "CheckFunctionDebugify", /*Strip=*/true, &StatsMap);
922     } else if (any_isa<const Module *>(IR)) {
923       auto &M = *const_cast<Module *>(any_cast<const Module *>(IR));
924       checkDebugifyMetadata(M, M.functions(), P, "CheckModuleDebugify",
925                             /*Strip=*/true, &StatsMap);
926     }
927   });
928 }
929 
930 char DebugifyModulePass::ID = 0;
931 static RegisterPass<DebugifyModulePass> DM("debugify",
932                                            "Attach debug info to everything");
933 
934 char CheckDebugifyModulePass::ID = 0;
935 static RegisterPass<CheckDebugifyModulePass>
936     CDM("check-debugify", "Check debug info from -debugify");
937 
938 char DebugifyFunctionPass::ID = 0;
939 static RegisterPass<DebugifyFunctionPass> DF("debugify-function",
940                                              "Attach debug info to a function");
941 
942 char CheckDebugifyFunctionPass::ID = 0;
943 static RegisterPass<CheckDebugifyFunctionPass>
944     CDF("check-debugify-function", "Check debug info from -debugify-function");
945