1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/IR/DebugInfo.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DIBuilder.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/GVMaterializer.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/ValueHandle.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Dwarf.h"
30 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm::dwarf;
34 DISubprogram *llvm::getDISubprogram(const MDNode *Scope) {
35 if (auto *LocalScope = dyn_cast_or_null<DILocalScope>(Scope))
36 return LocalScope->getSubprogram();
40 //===----------------------------------------------------------------------===//
41 // DebugInfoFinder implementations.
42 //===----------------------------------------------------------------------===//
44 void DebugInfoFinder::reset() {
53 void DebugInfoFinder::processModule(const Module &M) {
54 for (auto *CU : M.debug_compile_units()) {
56 for (auto DIG : CU->getGlobalVariables()) {
57 if (!addGlobalVariable(DIG))
59 auto *GV = DIG->getVariable();
60 processScope(GV->getScope());
61 processType(GV->getType().resolve());
63 for (auto *ET : CU->getEnumTypes())
65 for (auto *RT : CU->getRetainedTypes())
66 if (auto *T = dyn_cast<DIType>(RT))
69 processSubprogram(cast<DISubprogram>(RT));
70 for (auto *Import : CU->getImportedEntities()) {
71 auto *Entity = Import->getEntity().resolve();
72 if (auto *T = dyn_cast<DIType>(Entity))
74 else if (auto *SP = dyn_cast<DISubprogram>(Entity))
75 processSubprogram(SP);
76 else if (auto *NS = dyn_cast<DINamespace>(Entity))
77 processScope(NS->getScope());
78 else if (auto *M = dyn_cast<DIModule>(Entity))
79 processScope(M->getScope());
82 for (auto &F : M.functions()) {
83 if (auto *SP = cast_or_null<DISubprogram>(F.getSubprogram()))
84 processSubprogram(SP);
85 // There could be subprograms from inlined functions referenced from
86 // instructions only. Walk the function to find them.
87 for (const BasicBlock &BB : F) {
88 for (const Instruction &I : BB) {
91 processLocation(M, I.getDebugLoc().get());
97 void DebugInfoFinder::processLocation(const Module &M, const DILocation *Loc) {
100 processScope(Loc->getScope());
101 processLocation(M, Loc->getInlinedAt());
104 void DebugInfoFinder::processType(DIType *DT) {
107 processScope(DT->getScope().resolve());
108 if (auto *ST = dyn_cast<DISubroutineType>(DT)) {
109 for (DITypeRef Ref : ST->getTypeArray())
110 processType(Ref.resolve());
113 if (auto *DCT = dyn_cast<DICompositeType>(DT)) {
114 processType(DCT->getBaseType().resolve());
115 for (Metadata *D : DCT->getElements()) {
116 if (auto *T = dyn_cast<DIType>(D))
118 else if (auto *SP = dyn_cast<DISubprogram>(D))
119 processSubprogram(SP);
123 if (auto *DDT = dyn_cast<DIDerivedType>(DT)) {
124 processType(DDT->getBaseType().resolve());
128 void DebugInfoFinder::processScope(DIScope *Scope) {
131 if (auto *Ty = dyn_cast<DIType>(Scope)) {
135 if (auto *CU = dyn_cast<DICompileUnit>(Scope)) {
139 if (auto *SP = dyn_cast<DISubprogram>(Scope)) {
140 processSubprogram(SP);
143 if (!addScope(Scope))
145 if (auto *LB = dyn_cast<DILexicalBlockBase>(Scope)) {
146 processScope(LB->getScope());
147 } else if (auto *NS = dyn_cast<DINamespace>(Scope)) {
148 processScope(NS->getScope());
149 } else if (auto *M = dyn_cast<DIModule>(Scope)) {
150 processScope(M->getScope());
154 void DebugInfoFinder::processSubprogram(DISubprogram *SP) {
155 if (!addSubprogram(SP))
157 processScope(SP->getScope().resolve());
158 processType(SP->getType());
159 for (auto *Element : SP->getTemplateParams()) {
160 if (auto *TType = dyn_cast<DITemplateTypeParameter>(Element)) {
161 processType(TType->getType().resolve());
162 } else if (auto *TVal = dyn_cast<DITemplateValueParameter>(Element)) {
163 processType(TVal->getType().resolve());
168 void DebugInfoFinder::processDeclare(const Module &M,
169 const DbgDeclareInst *DDI) {
170 auto *N = dyn_cast<MDNode>(DDI->getVariable());
174 auto *DV = dyn_cast<DILocalVariable>(N);
178 if (!NodesSeen.insert(DV).second)
180 processScope(DV->getScope());
181 processType(DV->getType().resolve());
184 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
185 auto *N = dyn_cast<MDNode>(DVI->getVariable());
189 auto *DV = dyn_cast<DILocalVariable>(N);
193 if (!NodesSeen.insert(DV).second)
195 processScope(DV->getScope());
196 processType(DV->getType().resolve());
199 bool DebugInfoFinder::addType(DIType *DT) {
203 if (!NodesSeen.insert(DT).second)
206 TYs.push_back(const_cast<DIType *>(DT));
210 bool DebugInfoFinder::addCompileUnit(DICompileUnit *CU) {
213 if (!NodesSeen.insert(CU).second)
220 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariableExpression *DIG) {
221 if (!NodesSeen.insert(DIG).second)
228 bool DebugInfoFinder::addSubprogram(DISubprogram *SP) {
232 if (!NodesSeen.insert(SP).second)
239 bool DebugInfoFinder::addScope(DIScope *Scope) {
242 // FIXME: Ocaml binding generates a scope with no content, we treat it
244 if (Scope->getNumOperands() == 0)
246 if (!NodesSeen.insert(Scope).second)
248 Scopes.push_back(Scope);
252 static llvm::MDNode *stripDebugLocFromLoopID(llvm::MDNode *N) {
253 assert(N->op_begin() != N->op_end() && "Missing self reference?");
255 // if there is no debug location, we do not have to rewrite this MDNode.
256 if (std::none_of(N->op_begin() + 1, N->op_end(), [](const MDOperand &Op) {
257 return isa<DILocation>(Op.get());
261 // If there is only the debug location without any actual loop metadata, we
262 // can remove the metadata.
263 if (std::none_of(N->op_begin() + 1, N->op_end(), [](const MDOperand &Op) {
264 return !isa<DILocation>(Op.get());
268 SmallVector<Metadata *, 4> Args;
269 // Reserve operand 0 for loop id self reference.
270 auto TempNode = MDNode::getTemporary(N->getContext(), None);
271 Args.push_back(TempNode.get());
272 // Add all non-debug location operands back.
273 for (auto Op = N->op_begin() + 1; Op != N->op_end(); Op++) {
274 if (!isa<DILocation>(*Op))
278 // Set the first operand to itself.
279 MDNode *LoopID = MDNode::get(N->getContext(), Args);
280 LoopID->replaceOperandWith(0, LoopID);
284 bool llvm::stripDebugInfo(Function &F) {
285 bool Changed = false;
286 if (F.getSubprogram()) {
288 F.setSubprogram(nullptr);
291 llvm::DenseMap<llvm::MDNode*, llvm::MDNode*> LoopIDsMap;
292 for (BasicBlock &BB : F) {
293 for (auto II = BB.begin(), End = BB.end(); II != End;) {
294 Instruction &I = *II++; // We may delete the instruction, increment now.
295 if (isa<DbgInfoIntrinsic>(&I)) {
300 if (I.getDebugLoc()) {
302 I.setDebugLoc(DebugLoc());
306 auto *TermInst = BB.getTerminator();
307 if (auto *LoopID = TermInst->getMetadata(LLVMContext::MD_loop)) {
308 auto *NewLoopID = LoopIDsMap.lookup(LoopID);
310 NewLoopID = LoopIDsMap[LoopID] = stripDebugLocFromLoopID(LoopID);
311 if (NewLoopID != LoopID)
312 TermInst->setMetadata(LLVMContext::MD_loop, NewLoopID);
318 bool llvm::StripDebugInfo(Module &M) {
319 bool Changed = false;
321 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
322 NME = M.named_metadata_end(); NMI != NME;) {
323 NamedMDNode *NMD = &*NMI;
326 // We're stripping debug info, and without them, coverage information
327 // doesn't quite make sense.
328 if (NMD->getName().startswith("llvm.dbg.") ||
329 NMD->getName() == "llvm.gcov") {
330 NMD->eraseFromParent();
335 for (Function &F : M)
336 Changed |= stripDebugInfo(F);
338 for (auto &GV : M.globals()) {
339 SmallVector<MDNode *, 1> MDs;
340 GV.getMetadata(LLVMContext::MD_dbg, MDs);
342 GV.eraseMetadata(LLVMContext::MD_dbg);
347 if (GVMaterializer *Materializer = M.getMaterializer())
348 Materializer->setStripDebugInfo();
355 /// Helper class to downgrade -g metadata to -gline-tables-only metadata.
356 class DebugTypeInfoRemoval {
357 DenseMap<Metadata *, Metadata *> Replacements;
360 /// The (void)() type.
361 MDNode *EmptySubroutineType;
364 /// Remember what linkage name we originally had before stripping. If we end
365 /// up making two subprograms identical who originally had different linkage
366 /// names, then we need to make one of them distinct, to avoid them getting
367 /// uniqued. Maps the new node to the old linkage name.
368 DenseMap<DISubprogram *, StringRef> NewToLinkageName;
370 // TODO: Remember the distinct subprogram we created for a given linkage name,
371 // so that we can continue to unique whenever possible. Map <newly created
372 // node, old linkage name> to the first (possibly distinct) mdsubprogram
373 // created for that combination. This is not strictly needed for correctness,
374 // but can cut down on the number of MDNodes and let us diff cleanly with the
375 // output of -gline-tables-only.
378 DebugTypeInfoRemoval(LLVMContext &C)
379 : EmptySubroutineType(DISubroutineType::get(C, DINode::FlagZero, 0,
380 MDNode::get(C, {}))) {}
382 Metadata *map(Metadata *M) {
385 auto Replacement = Replacements.find(M);
386 if (Replacement != Replacements.end())
387 return Replacement->second;
391 MDNode *mapNode(Metadata *N) { return dyn_cast_or_null<MDNode>(map(N)); }
393 /// Recursively remap N and all its referenced children. Does a DF post-order
394 /// traversal, so as to remap bottoms up.
395 void traverseAndRemap(MDNode *N) { traverse(N); }
398 // Create a new DISubprogram, to replace the one given.
399 DISubprogram *getReplacementSubprogram(DISubprogram *MDS) {
400 auto *FileAndScope = cast_or_null<DIFile>(map(MDS->getFile()));
401 StringRef LinkageName = MDS->getName().empty() ? MDS->getLinkageName() : "";
402 DISubprogram *Declaration = nullptr;
403 auto *Type = cast_or_null<DISubroutineType>(map(MDS->getType()));
404 DITypeRef ContainingType(map(MDS->getContainingType()));
405 auto *Unit = cast_or_null<DICompileUnit>(map(MDS->getUnit()));
406 auto Variables = nullptr;
407 auto TemplateParams = nullptr;
409 // Make a distinct DISubprogram, for situations that warrent it.
410 auto distinctMDSubprogram = [&]() {
411 return DISubprogram::getDistinct(
412 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
413 FileAndScope, MDS->getLine(), Type, MDS->isLocalToUnit(),
414 MDS->isDefinition(), MDS->getScopeLine(), ContainingType,
415 MDS->getVirtuality(), MDS->getVirtualIndex(),
416 MDS->getThisAdjustment(), MDS->getFlags(), MDS->isOptimized(), Unit,
417 TemplateParams, Declaration, Variables);
420 if (MDS->isDistinct())
421 return distinctMDSubprogram();
423 auto *NewMDS = DISubprogram::get(
424 MDS->getContext(), FileAndScope, MDS->getName(), LinkageName,
425 FileAndScope, MDS->getLine(), Type, MDS->isLocalToUnit(),
426 MDS->isDefinition(), MDS->getScopeLine(), ContainingType,
427 MDS->getVirtuality(), MDS->getVirtualIndex(), MDS->getThisAdjustment(),
428 MDS->getFlags(), MDS->isOptimized(), Unit, TemplateParams, Declaration,
431 StringRef OldLinkageName = MDS->getLinkageName();
433 // See if we need to make a distinct one.
434 auto OrigLinkage = NewToLinkageName.find(NewMDS);
435 if (OrigLinkage != NewToLinkageName.end()) {
436 if (OrigLinkage->second == OldLinkageName)
440 // Otherwise, need to make a distinct one.
441 // TODO: Query the map to see if we already have one.
442 return distinctMDSubprogram();
445 NewToLinkageName.insert({NewMDS, MDS->getLinkageName()});
449 /// Create a new compile unit, to replace the one given
450 DICompileUnit *getReplacementCU(DICompileUnit *CU) {
451 // Drop skeleton CUs.
455 auto *File = cast_or_null<DIFile>(map(CU->getFile()));
456 MDTuple *EnumTypes = nullptr;
457 MDTuple *RetainedTypes = nullptr;
458 MDTuple *GlobalVariables = nullptr;
459 MDTuple *ImportedEntities = nullptr;
460 return DICompileUnit::getDistinct(
461 CU->getContext(), CU->getSourceLanguage(), File, CU->getProducer(),
462 CU->isOptimized(), CU->getFlags(), CU->getRuntimeVersion(),
463 CU->getSplitDebugFilename(), DICompileUnit::LineTablesOnly, EnumTypes,
464 RetainedTypes, GlobalVariables, ImportedEntities, CU->getMacros(),
465 CU->getDWOId(), CU->getSplitDebugInlining(),
466 CU->getDebugInfoForProfiling());
469 DILocation *getReplacementMDLocation(DILocation *MLD) {
470 auto *Scope = map(MLD->getScope());
471 auto *InlinedAt = map(MLD->getInlinedAt());
472 if (MLD->isDistinct())
473 return DILocation::getDistinct(MLD->getContext(), MLD->getLine(),
474 MLD->getColumn(), Scope, InlinedAt);
475 return DILocation::get(MLD->getContext(), MLD->getLine(), MLD->getColumn(),
479 /// Create a new generic MDNode, to replace the one given
480 MDNode *getReplacementMDNode(MDNode *N) {
481 SmallVector<Metadata *, 8> Ops;
482 Ops.reserve(N->getNumOperands());
483 for (auto &I : N->operands())
485 Ops.push_back(map(I));
486 auto *Ret = MDNode::get(N->getContext(), Ops);
490 /// Attempt to re-map N to a newly created node.
491 void remap(MDNode *N) {
492 if (Replacements.count(N))
495 auto doRemap = [&](MDNode *N) -> MDNode * {
498 if (auto *MDSub = dyn_cast<DISubprogram>(N)) {
499 remap(MDSub->getUnit());
500 return getReplacementSubprogram(MDSub);
502 if (isa<DISubroutineType>(N))
503 return EmptySubroutineType;
504 if (auto *CU = dyn_cast<DICompileUnit>(N))
505 return getReplacementCU(CU);
508 if (auto *MDLB = dyn_cast<DILexicalBlockBase>(N))
509 // Remap to our referenced scope (recursively).
510 return mapNode(MDLB->getScope());
511 if (auto *MLD = dyn_cast<DILocation>(N))
512 return getReplacementMDLocation(MLD);
514 // Otherwise, if we see these, just drop them now. Not strictly necessary,
515 // but this speeds things up a little.
519 return getReplacementMDNode(N);
521 Replacements[N] = doRemap(N);
524 /// Do the remapping traversal.
525 void traverse(MDNode *);
528 } // Anonymous namespace.
530 void DebugTypeInfoRemoval::traverse(MDNode *N) {
531 if (!N || Replacements.count(N))
534 // To avoid cycles, as well as for efficiency sake, we will sometimes prune
535 // parts of the graph.
536 auto prune = [](MDNode *Parent, MDNode *Child) {
537 if (auto *MDS = dyn_cast<DISubprogram>(Parent))
538 return Child == MDS->getVariables().get();
542 SmallVector<MDNode *, 16> ToVisit;
543 DenseSet<MDNode *> Opened;
545 // Visit each node starting at N in post order, and map them.
546 ToVisit.push_back(N);
547 while (!ToVisit.empty()) {
548 auto *N = ToVisit.back();
549 if (!Opened.insert(N).second) {
555 for (auto &I : N->operands())
556 if (auto *MDN = dyn_cast_or_null<MDNode>(I))
557 if (!Opened.count(MDN) && !Replacements.count(MDN) && !prune(N, MDN) &&
558 !isa<DICompileUnit>(MDN))
559 ToVisit.push_back(MDN);
563 bool llvm::stripNonLineTableDebugInfo(Module &M) {
564 bool Changed = false;
566 // First off, delete the debug intrinsics.
567 auto RemoveUses = [&](StringRef Name) {
568 if (auto *DbgVal = M.getFunction(Name)) {
569 while (!DbgVal->use_empty())
570 cast<Instruction>(DbgVal->user_back())->eraseFromParent();
571 DbgVal->eraseFromParent();
575 RemoveUses("llvm.dbg.declare");
576 RemoveUses("llvm.dbg.value");
578 // Delete non-CU debug info named metadata nodes.
579 for (auto NMI = M.named_metadata_begin(), NME = M.named_metadata_end();
581 NamedMDNode *NMD = &*NMI;
583 // Specifically keep dbg.cu around.
584 if (NMD->getName() == "llvm.dbg.cu")
588 // Drop all dbg attachments from global variables.
589 for (auto &GV : M.globals())
590 GV.eraseMetadata(LLVMContext::MD_dbg);
592 DebugTypeInfoRemoval Mapper(M.getContext());
593 auto remap = [&](llvm::MDNode *Node) -> llvm::MDNode * {
596 Mapper.traverseAndRemap(Node);
597 auto *NewNode = Mapper.mapNode(Node);
598 Changed |= Node != NewNode;
603 // Rewrite the DebugLocs to be equivalent to what
604 // -gline-tables-only would have created.
606 if (auto *SP = F.getSubprogram()) {
607 Mapper.traverseAndRemap(SP);
608 auto *NewSP = cast<DISubprogram>(Mapper.mapNode(SP));
609 Changed |= SP != NewSP;
610 F.setSubprogram(NewSP);
614 auto remapDebugLoc = [&](DebugLoc DL) -> DebugLoc {
615 auto *Scope = DL.getScope();
616 MDNode *InlinedAt = DL.getInlinedAt();
617 Scope = remap(Scope);
618 InlinedAt = remap(InlinedAt);
619 return DebugLoc::get(DL.getLine(), DL.getCol(), Scope, InlinedAt);
622 if (I.getDebugLoc() != DebugLoc())
623 I.setDebugLoc(remapDebugLoc(I.getDebugLoc()));
625 // Remap DILocations in untyped MDNodes (e.g., llvm.loop).
626 SmallVector<std::pair<unsigned, MDNode *>, 2> MDs;
627 I.getAllMetadata(MDs);
628 for (auto Attachment : MDs)
629 if (auto *T = dyn_cast_or_null<MDTuple>(Attachment.second))
630 for (unsigned N = 0; N < T->getNumOperands(); ++N)
631 if (auto *Loc = dyn_cast_or_null<DILocation>(T->getOperand(N)))
632 if (Loc != DebugLoc())
633 T->replaceOperandWith(N, remapDebugLoc(Loc));
638 // Create a new llvm.dbg.cu, which is equivalent to the one
639 // -gline-tables-only would have created.
640 for (auto &NMD : M.getNamedMDList()) {
641 SmallVector<MDNode *, 8> Ops;
642 for (MDNode *Op : NMD.operands())
643 Ops.push_back(remap(Op));
656 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
657 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
658 M.getModuleFlag("Debug Info Version")))
659 return Val->getZExtValue();