125ee8613SDaniel Sanders //===- Debugify.cpp - Attach synthetic debug info to everything -----------===//
225ee8613SDaniel Sanders //
325ee8613SDaniel Sanders // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
425ee8613SDaniel Sanders // See https://llvm.org/LICENSE.txt for license information.
525ee8613SDaniel Sanders // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
625ee8613SDaniel Sanders //
725ee8613SDaniel Sanders //===----------------------------------------------------------------------===//
825ee8613SDaniel Sanders ///
925ee8613SDaniel Sanders /// \file This pass attaches synthetic debug info to everything. It can be used
1025ee8613SDaniel Sanders /// to create targeted tests for debug info preservation.
1125ee8613SDaniel Sanders ///
1225ee8613SDaniel Sanders //===----------------------------------------------------------------------===//
1325ee8613SDaniel Sanders 
144c1a1d3cSReid Kleckner #include "llvm/Transforms/Utils/Debugify.h"
1525ee8613SDaniel Sanders #include "llvm/ADT/BitVector.h"
1625ee8613SDaniel Sanders #include "llvm/ADT/StringExtras.h"
1725ee8613SDaniel Sanders #include "llvm/IR/DIBuilder.h"
1825ee8613SDaniel Sanders #include "llvm/IR/DebugInfo.h"
1925ee8613SDaniel Sanders #include "llvm/IR/InstIterator.h"
2025ee8613SDaniel Sanders #include "llvm/IR/Instructions.h"
2125ee8613SDaniel Sanders #include "llvm/IR/IntrinsicInst.h"
2225ee8613SDaniel Sanders #include "llvm/IR/Module.h"
2325ee8613SDaniel Sanders #include "llvm/Pass.h"
244c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h"
2525ee8613SDaniel Sanders 
2625ee8613SDaniel Sanders using namespace llvm;
2725ee8613SDaniel Sanders 
2825ee8613SDaniel Sanders namespace {
2925ee8613SDaniel Sanders 
3025ee8613SDaniel Sanders cl::opt<bool> Quiet("debugify-quiet",
3125ee8613SDaniel Sanders                     cl::desc("Suppress verbose debugify output"));
3225ee8613SDaniel Sanders 
3315f7bc78SDaniel Sanders enum class Level {
3415f7bc78SDaniel Sanders   Locations,
3515f7bc78SDaniel Sanders   LocationsAndVariables
3615f7bc78SDaniel Sanders };
3715f7bc78SDaniel Sanders cl::opt<Level> DebugifyLevel(
3815f7bc78SDaniel Sanders     "debugify-level", cl::desc("Kind of debug info to add"),
3915f7bc78SDaniel Sanders     cl::values(clEnumValN(Level::Locations, "locations", "Locations only"),
4015f7bc78SDaniel Sanders                clEnumValN(Level::LocationsAndVariables, "location+variables",
4115f7bc78SDaniel Sanders                           "Locations and Variables")),
4215f7bc78SDaniel Sanders     cl::init(Level::LocationsAndVariables));
4315f7bc78SDaniel Sanders 
4425ee8613SDaniel Sanders raw_ostream &dbg() { return Quiet ? nulls() : errs(); }
4525ee8613SDaniel Sanders 
4625ee8613SDaniel Sanders uint64_t getAllocSizeInBits(Module &M, Type *Ty) {
4725ee8613SDaniel Sanders   return Ty->isSized() ? M.getDataLayout().getTypeAllocSizeInBits(Ty) : 0;
4825ee8613SDaniel Sanders }
4925ee8613SDaniel Sanders 
5025ee8613SDaniel Sanders bool isFunctionSkipped(Function &F) {
5125ee8613SDaniel Sanders   return F.isDeclaration() || !F.hasExactDefinition();
5225ee8613SDaniel Sanders }
5325ee8613SDaniel Sanders 
5425ee8613SDaniel Sanders /// Find the basic block's terminating instruction.
5525ee8613SDaniel Sanders ///
5625ee8613SDaniel Sanders /// Special care is needed to handle musttail and deopt calls, as these behave
5725ee8613SDaniel Sanders /// like (but are in fact not) terminators.
5825ee8613SDaniel Sanders Instruction *findTerminatingInstruction(BasicBlock &BB) {
5925ee8613SDaniel Sanders   if (auto *I = BB.getTerminatingMustTailCall())
6025ee8613SDaniel Sanders     return I;
6125ee8613SDaniel Sanders   if (auto *I = BB.getTerminatingDeoptimizeCall())
6225ee8613SDaniel Sanders     return I;
6325ee8613SDaniel Sanders   return BB.getTerminator();
6425ee8613SDaniel Sanders }
651adeeabbSDaniel Sanders } // end anonymous namespace
6625ee8613SDaniel Sanders 
671adeeabbSDaniel Sanders bool llvm::applyDebugifyMetadata(
681adeeabbSDaniel Sanders     Module &M, iterator_range<Module::iterator> Functions, StringRef Banner,
691adeeabbSDaniel Sanders     std::function<bool(DIBuilder &DIB, Function &F)> ApplyToMF) {
7025ee8613SDaniel Sanders   // Skip modules with debug info.
7125ee8613SDaniel Sanders   if (M.getNamedMetadata("llvm.dbg.cu")) {
7225ee8613SDaniel Sanders     dbg() << Banner << "Skipping module with debug info\n";
7325ee8613SDaniel Sanders     return false;
7425ee8613SDaniel Sanders   }
7525ee8613SDaniel Sanders 
7625ee8613SDaniel Sanders   DIBuilder DIB(M);
7725ee8613SDaniel Sanders   LLVMContext &Ctx = M.getContext();
7825ee8613SDaniel Sanders 
7925ee8613SDaniel Sanders   // Get a DIType which corresponds to Ty.
8025ee8613SDaniel Sanders   DenseMap<uint64_t, DIType *> TypeCache;
8125ee8613SDaniel Sanders   auto getCachedDIType = [&](Type *Ty) -> DIType * {
8225ee8613SDaniel Sanders     uint64_t Size = getAllocSizeInBits(M, Ty);
8325ee8613SDaniel Sanders     DIType *&DTy = TypeCache[Size];
8425ee8613SDaniel Sanders     if (!DTy) {
8525ee8613SDaniel Sanders       std::string Name = "ty" + utostr(Size);
8625ee8613SDaniel Sanders       DTy = DIB.createBasicType(Name, Size, dwarf::DW_ATE_unsigned);
8725ee8613SDaniel Sanders     }
8825ee8613SDaniel Sanders     return DTy;
8925ee8613SDaniel Sanders   };
9025ee8613SDaniel Sanders 
9125ee8613SDaniel Sanders   unsigned NextLine = 1;
9225ee8613SDaniel Sanders   unsigned NextVar = 1;
9325ee8613SDaniel Sanders   auto File = DIB.createFile(M.getName(), "/");
9425ee8613SDaniel Sanders   auto CU = DIB.createCompileUnit(dwarf::DW_LANG_C, File, "debugify",
9525ee8613SDaniel Sanders                                   /*isOptimized=*/true, "", 0);
9625ee8613SDaniel Sanders 
9725ee8613SDaniel Sanders   // Visit each instruction.
9825ee8613SDaniel Sanders   for (Function &F : Functions) {
9925ee8613SDaniel Sanders     if (isFunctionSkipped(F))
10025ee8613SDaniel Sanders       continue;
10125ee8613SDaniel Sanders 
10225ee8613SDaniel Sanders     auto SPType = DIB.createSubroutineType(DIB.getOrCreateTypeArray(None));
10325ee8613SDaniel Sanders     DISubprogram::DISPFlags SPFlags =
10425ee8613SDaniel Sanders         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized;
10525ee8613SDaniel Sanders     if (F.hasPrivateLinkage() || F.hasInternalLinkage())
10625ee8613SDaniel Sanders       SPFlags |= DISubprogram::SPFlagLocalToUnit;
10725ee8613SDaniel Sanders     auto SP = DIB.createFunction(CU, F.getName(), F.getName(), File, NextLine,
10825ee8613SDaniel Sanders                                  SPType, NextLine, DINode::FlagZero, SPFlags);
10925ee8613SDaniel Sanders     F.setSubprogram(SP);
11025ee8613SDaniel Sanders     for (BasicBlock &BB : F) {
11125ee8613SDaniel Sanders       // Attach debug locations.
11225ee8613SDaniel Sanders       for (Instruction &I : BB)
11325ee8613SDaniel Sanders         I.setDebugLoc(DILocation::get(Ctx, NextLine++, 1, SP));
11425ee8613SDaniel Sanders 
11515f7bc78SDaniel Sanders       if (DebugifyLevel < Level::LocationsAndVariables)
11615f7bc78SDaniel Sanders         continue;
11715f7bc78SDaniel Sanders 
11825ee8613SDaniel Sanders       // Inserting debug values into EH pads can break IR invariants.
11925ee8613SDaniel Sanders       if (BB.isEHPad())
12025ee8613SDaniel Sanders         continue;
12125ee8613SDaniel Sanders 
12225ee8613SDaniel Sanders       // Find the terminating instruction, after which no debug values are
12325ee8613SDaniel Sanders       // attached.
12425ee8613SDaniel Sanders       Instruction *LastInst = findTerminatingInstruction(BB);
12525ee8613SDaniel Sanders       assert(LastInst && "Expected basic block with a terminator");
12625ee8613SDaniel Sanders 
12725ee8613SDaniel Sanders       // Maintain an insertion point which can't be invalidated when updates
12825ee8613SDaniel Sanders       // are made.
12925ee8613SDaniel Sanders       BasicBlock::iterator InsertPt = BB.getFirstInsertionPt();
13025ee8613SDaniel Sanders       assert(InsertPt != BB.end() && "Expected to find an insertion point");
13125ee8613SDaniel Sanders       Instruction *InsertBefore = &*InsertPt;
13225ee8613SDaniel Sanders 
13325ee8613SDaniel Sanders       // Attach debug values.
13425ee8613SDaniel Sanders       for (Instruction *I = &*BB.begin(); I != LastInst; I = I->getNextNode()) {
13525ee8613SDaniel Sanders         // Skip void-valued instructions.
13625ee8613SDaniel Sanders         if (I->getType()->isVoidTy())
13725ee8613SDaniel Sanders           continue;
13825ee8613SDaniel Sanders 
13925ee8613SDaniel Sanders         // Phis and EH pads must be grouped at the beginning of the block.
14025ee8613SDaniel Sanders         // Only advance the insertion point when we finish visiting these.
14125ee8613SDaniel Sanders         if (!isa<PHINode>(I) && !I->isEHPad())
14225ee8613SDaniel Sanders           InsertBefore = I->getNextNode();
14325ee8613SDaniel Sanders 
14425ee8613SDaniel Sanders         std::string Name = utostr(NextVar++);
14525ee8613SDaniel Sanders         const DILocation *Loc = I->getDebugLoc().get();
14625ee8613SDaniel Sanders         auto LocalVar = DIB.createAutoVariable(SP, Name, File, Loc->getLine(),
14725ee8613SDaniel Sanders                                                getCachedDIType(I->getType()),
14825ee8613SDaniel Sanders                                                /*AlwaysPreserve=*/true);
14925ee8613SDaniel Sanders         DIB.insertDbgValueIntrinsic(I, LocalVar, DIB.createExpression(), Loc,
15025ee8613SDaniel Sanders                                     InsertBefore);
15125ee8613SDaniel Sanders       }
15225ee8613SDaniel Sanders     }
1531adeeabbSDaniel Sanders     if (ApplyToMF)
1541adeeabbSDaniel Sanders       ApplyToMF(DIB, F);
15525ee8613SDaniel Sanders     DIB.finalizeSubprogram(SP);
15625ee8613SDaniel Sanders   }
15725ee8613SDaniel Sanders   DIB.finalize();
15825ee8613SDaniel Sanders 
15925ee8613SDaniel Sanders   // Track the number of distinct lines and variables.
16025ee8613SDaniel Sanders   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.debugify");
16125ee8613SDaniel Sanders   auto *IntTy = Type::getInt32Ty(Ctx);
16225ee8613SDaniel Sanders   auto addDebugifyOperand = [&](unsigned N) {
16325ee8613SDaniel Sanders     NMD->addOperand(MDNode::get(
16425ee8613SDaniel Sanders         Ctx, ValueAsMetadata::getConstant(ConstantInt::get(IntTy, N))));
16525ee8613SDaniel Sanders   };
16625ee8613SDaniel Sanders   addDebugifyOperand(NextLine - 1); // Original number of lines.
16725ee8613SDaniel Sanders   addDebugifyOperand(NextVar - 1);  // Original number of variables.
16825ee8613SDaniel Sanders   assert(NMD->getNumOperands() == 2 &&
16925ee8613SDaniel Sanders          "llvm.debugify should have exactly 2 operands!");
17025ee8613SDaniel Sanders 
17125ee8613SDaniel Sanders   // Claim that this synthetic debug info is valid.
17225ee8613SDaniel Sanders   StringRef DIVersionKey = "Debug Info Version";
17325ee8613SDaniel Sanders   if (!M.getModuleFlag(DIVersionKey))
17425ee8613SDaniel Sanders     M.addModuleFlag(Module::Warning, DIVersionKey, DEBUG_METADATA_VERSION);
17525ee8613SDaniel Sanders 
17625ee8613SDaniel Sanders   return true;
17725ee8613SDaniel Sanders }
17825ee8613SDaniel Sanders 
179*122a6bfbSVedant Kumar bool llvm::stripDebugifyMetadata(Module &M) {
180*122a6bfbSVedant Kumar   bool Changed = false;
181*122a6bfbSVedant Kumar 
182*122a6bfbSVedant Kumar   // Remove the llvm.debugify module-level named metadata.
183*122a6bfbSVedant Kumar   NamedMDNode *DebugifyMD = M.getNamedMetadata("llvm.debugify");
184*122a6bfbSVedant Kumar   if (DebugifyMD) {
185*122a6bfbSVedant Kumar     M.eraseNamedMetadata(DebugifyMD);
186*122a6bfbSVedant Kumar     Changed = true;
187*122a6bfbSVedant Kumar   }
188*122a6bfbSVedant Kumar 
189*122a6bfbSVedant Kumar   // Strip out all debug intrinsics and supporting metadata (subprograms, types,
190*122a6bfbSVedant Kumar   // variables, etc).
191*122a6bfbSVedant Kumar   Changed |= StripDebugInfo(M);
192*122a6bfbSVedant Kumar 
193*122a6bfbSVedant Kumar   // Strip out the dead dbg.value prototype.
194*122a6bfbSVedant Kumar   Function *DbgValF = M.getFunction("llvm.dbg.value");
195*122a6bfbSVedant Kumar   if (DbgValF) {
196*122a6bfbSVedant Kumar     assert(DbgValF->isDeclaration() && DbgValF->use_empty() &&
197*122a6bfbSVedant Kumar            "Not all debug info stripped?");
198*122a6bfbSVedant Kumar     DbgValF->eraseFromParent();
199*122a6bfbSVedant Kumar     Changed = true;
200*122a6bfbSVedant Kumar   }
201*122a6bfbSVedant Kumar 
202*122a6bfbSVedant Kumar   // Strip out the module-level Debug Info Version metadata.
203*122a6bfbSVedant Kumar   // FIXME: There must be an easier way to remove an operand from a NamedMDNode.
204*122a6bfbSVedant Kumar   NamedMDNode *NMD = M.getModuleFlagsMetadata();
205*122a6bfbSVedant Kumar   assert(NMD && "debugify metadata present without Debug Info Version set?");
206*122a6bfbSVedant Kumar   SmallVector<MDNode *, 4> Flags;
207*122a6bfbSVedant Kumar   for (MDNode *Flag : NMD->operands())
208*122a6bfbSVedant Kumar     Flags.push_back(Flag);
209*122a6bfbSVedant Kumar   NMD->clearOperands();
210*122a6bfbSVedant Kumar   for (MDNode *Flag : Flags) {
211*122a6bfbSVedant Kumar     MDString *Key = dyn_cast_or_null<MDString>(Flag->getOperand(1));
212*122a6bfbSVedant Kumar     if (Key->getString() == "Debug Info Version") {
213*122a6bfbSVedant Kumar       Changed = true;
214*122a6bfbSVedant Kumar       continue;
215*122a6bfbSVedant Kumar     }
216*122a6bfbSVedant Kumar     NMD->addOperand(Flag);
217*122a6bfbSVedant Kumar   }
218*122a6bfbSVedant Kumar   // If we left it empty we might as well remove it.
219*122a6bfbSVedant Kumar   if (NMD->getNumOperands() == 0)
220*122a6bfbSVedant Kumar     NMD->eraseFromParent();
221*122a6bfbSVedant Kumar 
222*122a6bfbSVedant Kumar   return Changed;
223*122a6bfbSVedant Kumar }
224*122a6bfbSVedant Kumar 
2251adeeabbSDaniel Sanders namespace {
22625ee8613SDaniel Sanders /// Return true if a mis-sized diagnostic is issued for \p DVI.
22725ee8613SDaniel Sanders bool diagnoseMisSizedDbgValue(Module &M, DbgValueInst *DVI) {
22825ee8613SDaniel Sanders   // The size of a dbg.value's value operand should match the size of the
22925ee8613SDaniel Sanders   // variable it corresponds to.
23025ee8613SDaniel Sanders   //
23125ee8613SDaniel Sanders   // TODO: This, along with a check for non-null value operands, should be
23225ee8613SDaniel Sanders   // promoted to verifier failures.
23325ee8613SDaniel Sanders   Value *V = DVI->getValue();
23425ee8613SDaniel Sanders   if (!V)
23525ee8613SDaniel Sanders     return false;
23625ee8613SDaniel Sanders 
23725ee8613SDaniel Sanders   // For now, don't try to interpret anything more complicated than an empty
23825ee8613SDaniel Sanders   // DIExpression. Eventually we should try to handle OP_deref and fragments.
23925ee8613SDaniel Sanders   if (DVI->getExpression()->getNumElements())
24025ee8613SDaniel Sanders     return false;
24125ee8613SDaniel Sanders 
24225ee8613SDaniel Sanders   Type *Ty = V->getType();
24325ee8613SDaniel Sanders   uint64_t ValueOperandSize = getAllocSizeInBits(M, Ty);
24425ee8613SDaniel Sanders   Optional<uint64_t> DbgVarSize = DVI->getFragmentSizeInBits();
24525ee8613SDaniel Sanders   if (!ValueOperandSize || !DbgVarSize)
24625ee8613SDaniel Sanders     return false;
24725ee8613SDaniel Sanders 
24825ee8613SDaniel Sanders   bool HasBadSize = false;
24925ee8613SDaniel Sanders   if (Ty->isIntegerTy()) {
25025ee8613SDaniel Sanders     auto Signedness = DVI->getVariable()->getSignedness();
25125ee8613SDaniel Sanders     if (Signedness && *Signedness == DIBasicType::Signedness::Signed)
25225ee8613SDaniel Sanders       HasBadSize = ValueOperandSize < *DbgVarSize;
25325ee8613SDaniel Sanders   } else {
25425ee8613SDaniel Sanders     HasBadSize = ValueOperandSize != *DbgVarSize;
25525ee8613SDaniel Sanders   }
25625ee8613SDaniel Sanders 
25725ee8613SDaniel Sanders   if (HasBadSize) {
25825ee8613SDaniel Sanders     dbg() << "ERROR: dbg.value operand has size " << ValueOperandSize
25925ee8613SDaniel Sanders           << ", but its variable has size " << *DbgVarSize << ": ";
26025ee8613SDaniel Sanders     DVI->print(dbg());
26125ee8613SDaniel Sanders     dbg() << "\n";
26225ee8613SDaniel Sanders   }
26325ee8613SDaniel Sanders   return HasBadSize;
26425ee8613SDaniel Sanders }
26525ee8613SDaniel Sanders 
26625ee8613SDaniel Sanders bool checkDebugifyMetadata(Module &M,
26725ee8613SDaniel Sanders                            iterator_range<Module::iterator> Functions,
26825ee8613SDaniel Sanders                            StringRef NameOfWrappedPass, StringRef Banner,
26925ee8613SDaniel Sanders                            bool Strip, DebugifyStatsMap *StatsMap) {
27025ee8613SDaniel Sanders   // Skip modules without debugify metadata.
27125ee8613SDaniel Sanders   NamedMDNode *NMD = M.getNamedMetadata("llvm.debugify");
27225ee8613SDaniel Sanders   if (!NMD) {
27325ee8613SDaniel Sanders     dbg() << Banner << "Skipping module without debugify metadata\n";
27425ee8613SDaniel Sanders     return false;
27525ee8613SDaniel Sanders   }
27625ee8613SDaniel Sanders 
27725ee8613SDaniel Sanders   auto getDebugifyOperand = [&](unsigned Idx) -> unsigned {
27825ee8613SDaniel Sanders     return mdconst::extract<ConstantInt>(NMD->getOperand(Idx)->getOperand(0))
27925ee8613SDaniel Sanders         ->getZExtValue();
28025ee8613SDaniel Sanders   };
28125ee8613SDaniel Sanders   assert(NMD->getNumOperands() == 2 &&
28225ee8613SDaniel Sanders          "llvm.debugify should have exactly 2 operands!");
28325ee8613SDaniel Sanders   unsigned OriginalNumLines = getDebugifyOperand(0);
28425ee8613SDaniel Sanders   unsigned OriginalNumVars = getDebugifyOperand(1);
28525ee8613SDaniel Sanders   bool HasErrors = false;
28625ee8613SDaniel Sanders 
28725ee8613SDaniel Sanders   // Track debug info loss statistics if able.
28825ee8613SDaniel Sanders   DebugifyStatistics *Stats = nullptr;
28925ee8613SDaniel Sanders   if (StatsMap && !NameOfWrappedPass.empty())
29025ee8613SDaniel Sanders     Stats = &StatsMap->operator[](NameOfWrappedPass);
29125ee8613SDaniel Sanders 
29225ee8613SDaniel Sanders   BitVector MissingLines{OriginalNumLines, true};
29325ee8613SDaniel Sanders   BitVector MissingVars{OriginalNumVars, true};
29425ee8613SDaniel Sanders   for (Function &F : Functions) {
29525ee8613SDaniel Sanders     if (isFunctionSkipped(F))
29625ee8613SDaniel Sanders       continue;
29725ee8613SDaniel Sanders 
29825ee8613SDaniel Sanders     // Find missing lines.
29925ee8613SDaniel Sanders     for (Instruction &I : instructions(F)) {
300f64e457cSPierre-vh       if (isa<DbgValueInst>(&I) || isa<PHINode>(&I))
30125ee8613SDaniel Sanders         continue;
30225ee8613SDaniel Sanders 
30325ee8613SDaniel Sanders       auto DL = I.getDebugLoc();
30425ee8613SDaniel Sanders       if (DL && DL.getLine() != 0) {
30525ee8613SDaniel Sanders         MissingLines.reset(DL.getLine() - 1);
30625ee8613SDaniel Sanders         continue;
30725ee8613SDaniel Sanders       }
30825ee8613SDaniel Sanders 
30925ee8613SDaniel Sanders       if (!DL) {
31025ee8613SDaniel Sanders         dbg() << "ERROR: Instruction with empty DebugLoc in function ";
31125ee8613SDaniel Sanders         dbg() << F.getName() << " --";
31225ee8613SDaniel Sanders         I.print(dbg());
31325ee8613SDaniel Sanders         dbg() << "\n";
31425ee8613SDaniel Sanders         HasErrors = true;
31525ee8613SDaniel Sanders       }
31625ee8613SDaniel Sanders     }
31725ee8613SDaniel Sanders 
31825ee8613SDaniel Sanders     // Find missing variables and mis-sized debug values.
31925ee8613SDaniel Sanders     for (Instruction &I : instructions(F)) {
32025ee8613SDaniel Sanders       auto *DVI = dyn_cast<DbgValueInst>(&I);
32125ee8613SDaniel Sanders       if (!DVI)
32225ee8613SDaniel Sanders         continue;
32325ee8613SDaniel Sanders 
32425ee8613SDaniel Sanders       unsigned Var = ~0U;
32525ee8613SDaniel Sanders       (void)to_integer(DVI->getVariable()->getName(), Var, 10);
32625ee8613SDaniel Sanders       assert(Var <= OriginalNumVars && "Unexpected name for DILocalVariable");
32725ee8613SDaniel Sanders       bool HasBadSize = diagnoseMisSizedDbgValue(M, DVI);
32825ee8613SDaniel Sanders       if (!HasBadSize)
32925ee8613SDaniel Sanders         MissingVars.reset(Var - 1);
33025ee8613SDaniel Sanders       HasErrors |= HasBadSize;
33125ee8613SDaniel Sanders     }
33225ee8613SDaniel Sanders   }
33325ee8613SDaniel Sanders 
33425ee8613SDaniel Sanders   // Print the results.
33525ee8613SDaniel Sanders   for (unsigned Idx : MissingLines.set_bits())
33625ee8613SDaniel Sanders     dbg() << "WARNING: Missing line " << Idx + 1 << "\n";
33725ee8613SDaniel Sanders 
33825ee8613SDaniel Sanders   for (unsigned Idx : MissingVars.set_bits())
33925ee8613SDaniel Sanders     dbg() << "WARNING: Missing variable " << Idx + 1 << "\n";
34025ee8613SDaniel Sanders 
34125ee8613SDaniel Sanders   // Update DI loss statistics.
34225ee8613SDaniel Sanders   if (Stats) {
34325ee8613SDaniel Sanders     Stats->NumDbgLocsExpected += OriginalNumLines;
34425ee8613SDaniel Sanders     Stats->NumDbgLocsMissing += MissingLines.count();
34525ee8613SDaniel Sanders     Stats->NumDbgValuesExpected += OriginalNumVars;
34625ee8613SDaniel Sanders     Stats->NumDbgValuesMissing += MissingVars.count();
34725ee8613SDaniel Sanders   }
34825ee8613SDaniel Sanders 
34925ee8613SDaniel Sanders   dbg() << Banner;
35025ee8613SDaniel Sanders   if (!NameOfWrappedPass.empty())
35125ee8613SDaniel Sanders     dbg() << " [" << NameOfWrappedPass << "]";
35225ee8613SDaniel Sanders   dbg() << ": " << (HasErrors ? "FAIL" : "PASS") << '\n';
35325ee8613SDaniel Sanders 
354*122a6bfbSVedant Kumar   // Strip debugify metadata if required.
355*122a6bfbSVedant Kumar   if (Strip)
356*122a6bfbSVedant Kumar     return stripDebugifyMetadata(M);
35725ee8613SDaniel Sanders 
35825ee8613SDaniel Sanders   return false;
35925ee8613SDaniel Sanders }
36025ee8613SDaniel Sanders 
36125ee8613SDaniel Sanders /// ModulePass for attaching synthetic debug info to everything, used with the
36225ee8613SDaniel Sanders /// legacy module pass manager.
36325ee8613SDaniel Sanders struct DebugifyModulePass : public ModulePass {
36425ee8613SDaniel Sanders   bool runOnModule(Module &M) override {
3651adeeabbSDaniel Sanders     return applyDebugifyMetadata(M, M.functions(),
3661adeeabbSDaniel Sanders                                  "ModuleDebugify: ", /*ApplyToMF*/ nullptr);
36725ee8613SDaniel Sanders   }
36825ee8613SDaniel Sanders 
36925ee8613SDaniel Sanders   DebugifyModulePass() : ModulePass(ID) {}
37025ee8613SDaniel Sanders 
37125ee8613SDaniel Sanders   void getAnalysisUsage(AnalysisUsage &AU) const override {
37225ee8613SDaniel Sanders     AU.setPreservesAll();
37325ee8613SDaniel Sanders   }
37425ee8613SDaniel Sanders 
37525ee8613SDaniel Sanders   static char ID; // Pass identification.
37625ee8613SDaniel Sanders };
37725ee8613SDaniel Sanders 
37825ee8613SDaniel Sanders /// FunctionPass for attaching synthetic debug info to instructions within a
37925ee8613SDaniel Sanders /// single function, used with the legacy module pass manager.
38025ee8613SDaniel Sanders struct DebugifyFunctionPass : public FunctionPass {
38125ee8613SDaniel Sanders   bool runOnFunction(Function &F) override {
38225ee8613SDaniel Sanders     Module &M = *F.getParent();
38325ee8613SDaniel Sanders     auto FuncIt = F.getIterator();
38425ee8613SDaniel Sanders     return applyDebugifyMetadata(M, make_range(FuncIt, std::next(FuncIt)),
3851adeeabbSDaniel Sanders                                  "FunctionDebugify: ", /*ApplyToMF*/ nullptr);
38625ee8613SDaniel Sanders   }
38725ee8613SDaniel Sanders 
38825ee8613SDaniel Sanders   DebugifyFunctionPass() : FunctionPass(ID) {}
38925ee8613SDaniel Sanders 
39025ee8613SDaniel Sanders   void getAnalysisUsage(AnalysisUsage &AU) const override {
39125ee8613SDaniel Sanders     AU.setPreservesAll();
39225ee8613SDaniel Sanders   }
39325ee8613SDaniel Sanders 
39425ee8613SDaniel Sanders   static char ID; // Pass identification.
39525ee8613SDaniel Sanders };
39625ee8613SDaniel Sanders 
39725ee8613SDaniel Sanders /// ModulePass for checking debug info inserted by -debugify, used with the
39825ee8613SDaniel Sanders /// legacy module pass manager.
39925ee8613SDaniel Sanders struct CheckDebugifyModulePass : public ModulePass {
40025ee8613SDaniel Sanders   bool runOnModule(Module &M) override {
40125ee8613SDaniel Sanders     return checkDebugifyMetadata(M, M.functions(), NameOfWrappedPass,
40225ee8613SDaniel Sanders                                  "CheckModuleDebugify", Strip, StatsMap);
40325ee8613SDaniel Sanders   }
40425ee8613SDaniel Sanders 
40525ee8613SDaniel Sanders   CheckDebugifyModulePass(bool Strip = false, StringRef NameOfWrappedPass = "",
40625ee8613SDaniel Sanders                           DebugifyStatsMap *StatsMap = nullptr)
40725ee8613SDaniel Sanders       : ModulePass(ID), Strip(Strip), NameOfWrappedPass(NameOfWrappedPass),
40825ee8613SDaniel Sanders         StatsMap(StatsMap) {}
40925ee8613SDaniel Sanders 
41025ee8613SDaniel Sanders   void getAnalysisUsage(AnalysisUsage &AU) const override {
41125ee8613SDaniel Sanders     AU.setPreservesAll();
41225ee8613SDaniel Sanders   }
41325ee8613SDaniel Sanders 
41425ee8613SDaniel Sanders   static char ID; // Pass identification.
41525ee8613SDaniel Sanders 
41625ee8613SDaniel Sanders private:
41725ee8613SDaniel Sanders   bool Strip;
41825ee8613SDaniel Sanders   StringRef NameOfWrappedPass;
41925ee8613SDaniel Sanders   DebugifyStatsMap *StatsMap;
42025ee8613SDaniel Sanders };
42125ee8613SDaniel Sanders 
42225ee8613SDaniel Sanders /// FunctionPass for checking debug info inserted by -debugify-function, used
42325ee8613SDaniel Sanders /// with the legacy module pass manager.
42425ee8613SDaniel Sanders struct CheckDebugifyFunctionPass : public FunctionPass {
42525ee8613SDaniel Sanders   bool runOnFunction(Function &F) override {
42625ee8613SDaniel Sanders     Module &M = *F.getParent();
42725ee8613SDaniel Sanders     auto FuncIt = F.getIterator();
42825ee8613SDaniel Sanders     return checkDebugifyMetadata(M, make_range(FuncIt, std::next(FuncIt)),
42925ee8613SDaniel Sanders                                  NameOfWrappedPass, "CheckFunctionDebugify",
43025ee8613SDaniel Sanders                                  Strip, StatsMap);
43125ee8613SDaniel Sanders   }
43225ee8613SDaniel Sanders 
43325ee8613SDaniel Sanders   CheckDebugifyFunctionPass(bool Strip = false,
43425ee8613SDaniel Sanders                             StringRef NameOfWrappedPass = "",
43525ee8613SDaniel Sanders                             DebugifyStatsMap *StatsMap = nullptr)
43625ee8613SDaniel Sanders       : FunctionPass(ID), Strip(Strip), NameOfWrappedPass(NameOfWrappedPass),
43725ee8613SDaniel Sanders         StatsMap(StatsMap) {}
43825ee8613SDaniel Sanders 
43925ee8613SDaniel Sanders   void getAnalysisUsage(AnalysisUsage &AU) const override {
44025ee8613SDaniel Sanders     AU.setPreservesAll();
44125ee8613SDaniel Sanders   }
44225ee8613SDaniel Sanders 
44325ee8613SDaniel Sanders   static char ID; // Pass identification.
44425ee8613SDaniel Sanders 
44525ee8613SDaniel Sanders private:
44625ee8613SDaniel Sanders   bool Strip;
44725ee8613SDaniel Sanders   StringRef NameOfWrappedPass;
44825ee8613SDaniel Sanders   DebugifyStatsMap *StatsMap;
44925ee8613SDaniel Sanders };
45025ee8613SDaniel Sanders 
45125ee8613SDaniel Sanders } // end anonymous namespace
45225ee8613SDaniel Sanders 
45325ee8613SDaniel Sanders ModulePass *createDebugifyModulePass() { return new DebugifyModulePass(); }
45425ee8613SDaniel Sanders 
45525ee8613SDaniel Sanders FunctionPass *createDebugifyFunctionPass() {
45625ee8613SDaniel Sanders   return new DebugifyFunctionPass();
45725ee8613SDaniel Sanders }
45825ee8613SDaniel Sanders 
45925ee8613SDaniel Sanders PreservedAnalyses NewPMDebugifyPass::run(Module &M, ModuleAnalysisManager &) {
4601adeeabbSDaniel Sanders   applyDebugifyMetadata(M, M.functions(),
4611adeeabbSDaniel Sanders                         "ModuleDebugify: ", /*ApplyToMF*/ nullptr);
46225ee8613SDaniel Sanders   return PreservedAnalyses::all();
46325ee8613SDaniel Sanders }
46425ee8613SDaniel Sanders 
46525ee8613SDaniel Sanders ModulePass *createCheckDebugifyModulePass(bool Strip,
46625ee8613SDaniel Sanders                                           StringRef NameOfWrappedPass,
46725ee8613SDaniel Sanders                                           DebugifyStatsMap *StatsMap) {
46825ee8613SDaniel Sanders   return new CheckDebugifyModulePass(Strip, NameOfWrappedPass, StatsMap);
46925ee8613SDaniel Sanders }
47025ee8613SDaniel Sanders 
47125ee8613SDaniel Sanders FunctionPass *createCheckDebugifyFunctionPass(bool Strip,
47225ee8613SDaniel Sanders                                               StringRef NameOfWrappedPass,
47325ee8613SDaniel Sanders                                               DebugifyStatsMap *StatsMap) {
47425ee8613SDaniel Sanders   return new CheckDebugifyFunctionPass(Strip, NameOfWrappedPass, StatsMap);
47525ee8613SDaniel Sanders }
47625ee8613SDaniel Sanders 
47725ee8613SDaniel Sanders PreservedAnalyses NewPMCheckDebugifyPass::run(Module &M,
47825ee8613SDaniel Sanders                                               ModuleAnalysisManager &) {
47925ee8613SDaniel Sanders   checkDebugifyMetadata(M, M.functions(), "", "CheckModuleDebugify", false,
48025ee8613SDaniel Sanders                         nullptr);
48125ee8613SDaniel Sanders   return PreservedAnalyses::all();
48225ee8613SDaniel Sanders }
48325ee8613SDaniel Sanders 
48425ee8613SDaniel Sanders char DebugifyModulePass::ID = 0;
48525ee8613SDaniel Sanders static RegisterPass<DebugifyModulePass> DM("debugify",
48625ee8613SDaniel Sanders                                            "Attach debug info to everything");
48725ee8613SDaniel Sanders 
48825ee8613SDaniel Sanders char CheckDebugifyModulePass::ID = 0;
48925ee8613SDaniel Sanders static RegisterPass<CheckDebugifyModulePass>
49025ee8613SDaniel Sanders     CDM("check-debugify", "Check debug info from -debugify");
49125ee8613SDaniel Sanders 
49225ee8613SDaniel Sanders char DebugifyFunctionPass::ID = 0;
49325ee8613SDaniel Sanders static RegisterPass<DebugifyFunctionPass> DF("debugify-function",
49425ee8613SDaniel Sanders                                              "Attach debug info to a function");
49525ee8613SDaniel Sanders 
49625ee8613SDaniel Sanders char CheckDebugifyFunctionPass::ID = 0;
49725ee8613SDaniel Sanders static RegisterPass<CheckDebugifyFunctionPass>
49825ee8613SDaniel Sanders     CDF("check-debugify-function", "Check debug info from -debugify-function");
499