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/ADT/SmallString.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DIBuilder.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/GVMaterializer.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/ValueHandle.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Dwarf.h"
32 #include "llvm/Support/raw_ostream.h"
34 using namespace llvm::dwarf;
36 //===----------------------------------------------------------------------===//
37 // Simple Descriptor Constructors and other Methods
38 //===----------------------------------------------------------------------===//
40 DIScopeRef DIScope::getRef() const { return MDScopeRef::get(get()); }
42 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
43 assert(CurFn && "Invalid function");
44 DISubprogram SP = dyn_cast<MDSubprogram>(getContext());
47 // This variable is not inlined function argument if its scope
48 // does not describe current function.
49 return !SP.describes(CurFn);
52 bool DISubprogram::describes(const Function *F) {
53 assert(F && "Invalid function");
54 if (F == getFunction())
56 StringRef Name = getLinkageName();
59 if (F->getName() == Name)
64 GlobalVariable *DIGlobalVariable::getGlobal() const {
65 return dyn_cast_or_null<GlobalVariable>(getConstant());
68 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
69 get()->replaceSubprograms(MDSubprogramArray(Subprograms));
72 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
73 get()->replaceGlobalVariables(MDGlobalVariableArray(GlobalVariables));
76 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
77 DILexicalBlockFile NewScope) {
78 assert(NewScope && "Expected valid scope");
80 const auto *Old = cast<MDLocation>(DbgNode);
81 return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
82 NewScope, Old->getInlinedAt()));
85 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
86 std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
87 return ++Ctx.pImpl->DiscriminatorTable[Key];
90 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
91 LLVMContext &VMContext) {
92 return cast<MDLocalVariable>(DV)
93 ->withInline(cast_or_null<MDLocation>(InlinedScope));
96 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
97 return cast<MDLocalVariable>(DV)->withoutInline();
100 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
101 if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
102 return LocalScope->getSubprogram();
106 DISubprogram llvm::getDISubprogram(const Function *F) {
107 // We look for the first instr that has a debug annotation leading back to F.
108 for (auto &BB : *F) {
109 auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
110 return Inst.getDebugLoc();
112 if (Inst == BB.end())
114 DebugLoc DLoc = Inst->getDebugLoc();
115 const MDNode *Scope = DLoc.getInlinedAtScope();
116 DISubprogram Subprogram = getDISubprogram(Scope);
117 return Subprogram.describes(F) ? Subprogram : DISubprogram();
120 return DISubprogram();
123 DICompositeType llvm::getDICompositeType(DIType T) {
124 if (auto *C = dyn_cast_or_null<MDCompositeTypeBase>(T))
127 if (auto *D = dyn_cast_or_null<MDDerivedTypeBase>(T)) {
128 // This function is currently used by dragonegg and dragonegg does
129 // not generate identifier for types, so using an empty map to resolve
130 // DerivedFrom should be fine.
131 DITypeIdentifierMap EmptyMap;
132 return getDICompositeType(
133 DIDerivedType(D).getTypeDerivedFrom().resolve(EmptyMap));
140 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
141 DITypeIdentifierMap Map;
142 for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
143 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(CUi));
144 DIArray Retain = CU.getRetainedTypes();
145 for (unsigned Ti = 0, Te = Retain.size(); Ti != Te; ++Ti) {
146 if (!isa<MDCompositeType>(Retain[Ti]))
148 DICompositeType Ty = cast<MDCompositeType>(Retain[Ti]);
149 if (MDString *TypeId = Ty.getIdentifier()) {
150 // Definition has priority over declaration.
151 // Try to insert (TypeId, Ty) to Map.
152 std::pair<DITypeIdentifierMap::iterator, bool> P =
153 Map.insert(std::make_pair(TypeId, Ty));
154 // If TypeId already exists in Map and this is a definition, replace
155 // whatever we had (declaration or definition) with the definition.
156 if (!P.second && !Ty.isForwardDecl())
157 P.first->second = Ty;
164 //===----------------------------------------------------------------------===//
165 // DebugInfoFinder implementations.
166 //===----------------------------------------------------------------------===//
168 void DebugInfoFinder::reset() {
175 TypeIdentifierMap.clear();
176 TypeMapInitialized = false;
179 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
180 if (!TypeMapInitialized)
181 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
182 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
183 TypeMapInitialized = true;
187 void DebugInfoFinder::processModule(const Module &M) {
188 InitializeTypeMap(M);
189 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
190 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
191 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(i));
193 for (DIGlobalVariable DIG : CU->getGlobalVariables()) {
194 if (addGlobalVariable(DIG)) {
195 processScope(DIG.getContext());
196 processType(DIG.getType().resolve(TypeIdentifierMap));
199 for (auto *SP : CU->getSubprograms())
200 processSubprogram(SP);
201 for (auto *ET : CU->getEnumTypes())
203 for (auto *RT : CU->getRetainedTypes())
205 for (DIImportedEntity Import : CU->getImportedEntities()) {
206 DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
207 if (auto *T = dyn_cast<MDType>(Entity))
209 else if (auto *SP = dyn_cast<MDSubprogram>(Entity))
210 processSubprogram(SP);
211 else if (auto *NS = dyn_cast<MDNamespace>(Entity))
212 processScope(NS->getScope());
218 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
221 InitializeTypeMap(M);
222 processScope(Loc.getScope());
223 processLocation(M, Loc.getOrigLocation());
226 void DebugInfoFinder::processType(DIType DT) {
229 processScope(DT.getContext().resolve(TypeIdentifierMap));
230 if (DICompositeType DCT = dyn_cast<MDCompositeTypeBase>(DT)) {
231 processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
232 if (DISubroutineType ST = dyn_cast<MDSubroutineType>(DCT)) {
233 for (MDTypeRef Ref : ST->getTypeArray())
234 processType(Ref.resolve(TypeIdentifierMap));
237 for (Metadata *D : DCT->getElements()->operands()) {
238 if (DIType T = dyn_cast<MDType>(D))
240 else if (DISubprogram SP = dyn_cast<MDSubprogram>(D))
241 processSubprogram(SP);
243 } else if (DIDerivedType DDT = dyn_cast<MDDerivedTypeBase>(DT)) {
244 processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
248 void DebugInfoFinder::processScope(DIScope Scope) {
251 if (DIType Ty = dyn_cast<MDType>(Scope)) {
255 if (DICompileUnit CU = dyn_cast<MDCompileUnit>(Scope)) {
259 if (DISubprogram SP = dyn_cast<MDSubprogram>(Scope)) {
260 processSubprogram(SP);
263 if (!addScope(Scope))
265 if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(Scope)) {
266 processScope(LB.getContext());
267 } else if (DINameSpace NS = dyn_cast<MDNamespace>(Scope)) {
268 processScope(NS.getContext());
272 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
273 if (!addSubprogram(SP))
275 processScope(SP.getContext().resolve(TypeIdentifierMap));
276 processType(SP.getType());
277 for (auto *Element : SP.getTemplateParams()) {
278 if (DITemplateTypeParameter TType =
279 dyn_cast<MDTemplateTypeParameter>(Element)) {
280 processType(TType.getType().resolve(TypeIdentifierMap));
281 } else if (DITemplateValueParameter TVal =
282 dyn_cast<MDTemplateValueParameter>(Element)) {
283 processType(TVal.getType().resolve(TypeIdentifierMap));
288 void DebugInfoFinder::processDeclare(const Module &M,
289 const DbgDeclareInst *DDI) {
290 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
293 InitializeTypeMap(M);
295 DIVariable DV = dyn_cast<MDLocalVariable>(N);
299 if (!NodesSeen.insert(DV).second)
301 processScope(DV.getContext());
302 processType(DV.getType().resolve(TypeIdentifierMap));
305 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
306 MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
309 InitializeTypeMap(M);
311 DIVariable DV = dyn_cast<MDLocalVariable>(N);
315 if (!NodesSeen.insert(DV).second)
317 processScope(DV.getContext());
318 processType(DV.getType().resolve(TypeIdentifierMap));
321 bool DebugInfoFinder::addType(DIType DT) {
325 if (!NodesSeen.insert(DT).second)
332 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
335 if (!NodesSeen.insert(CU).second)
342 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
346 if (!NodesSeen.insert(DIG).second)
353 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
357 if (!NodesSeen.insert(SP).second)
364 bool DebugInfoFinder::addScope(DIScope Scope) {
367 // FIXME: Ocaml binding generates a scope with no content, we treat it
369 if (Scope->getNumOperands() == 0)
371 if (!NodesSeen.insert(Scope).second)
373 Scopes.push_back(Scope);
377 //===----------------------------------------------------------------------===//
378 // DIDescriptor: dump routines for all descriptors.
379 //===----------------------------------------------------------------------===//
381 void DIDescriptor::dump() const {
386 void DIDescriptor::print(raw_ostream &OS) const {
392 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
393 const LLVMContext &Ctx) {
397 DIScope Scope = cast<MDScope>(DL.getScope());
398 // Omit the directory, because it's likely to be long and uninteresting.
399 CommentOS << Scope.getFilename();
400 CommentOS << ':' << DL.getLine();
401 if (DL.getCol() != 0)
402 CommentOS << ':' << DL.getCol();
404 DebugLoc InlinedAtDL = DL.getInlinedAt();
409 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
413 void DIVariable::printExtendedName(raw_ostream &OS) const {
414 const LLVMContext &Ctx = DbgNode->getContext();
415 StringRef Res = getName();
417 OS << Res << "," << getLineNumber();
418 if (auto *InlinedAt = get()->getInlinedAt()) {
419 if (DebugLoc InlinedAtDL = InlinedAt) {
421 printDebugLoc(InlinedAtDL, OS, Ctx);
429 DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const {
430 return DIDescriptor(DebugNodeRef(Val).resolve(Map));
433 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const {
434 return MDScopeRef(Val).resolve(Map);
437 DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const {
438 return MDTypeRef(Val).resolve(Map);
441 bool llvm::stripDebugInfo(Function &F) {
442 bool Changed = false;
443 for (BasicBlock &BB : F) {
444 for (Instruction &I : BB) {
445 if (I.getDebugLoc()) {
447 I.setDebugLoc(DebugLoc());
454 bool llvm::StripDebugInfo(Module &M) {
455 bool Changed = false;
457 // Remove all of the calls to the debugger intrinsics, and remove them from
459 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
460 while (!Declare->use_empty()) {
461 CallInst *CI = cast<CallInst>(Declare->user_back());
462 CI->eraseFromParent();
464 Declare->eraseFromParent();
468 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
469 while (!DbgVal->use_empty()) {
470 CallInst *CI = cast<CallInst>(DbgVal->user_back());
471 CI->eraseFromParent();
473 DbgVal->eraseFromParent();
477 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
478 NME = M.named_metadata_end(); NMI != NME;) {
479 NamedMDNode *NMD = NMI;
481 if (NMD->getName().startswith("llvm.dbg.")) {
482 NMD->eraseFromParent();
487 for (Function &F : M)
488 Changed |= stripDebugInfo(F);
490 if (GVMaterializer *Materializer = M.getMaterializer())
491 Materializer->setStripDebugInfo();
496 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
497 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
498 M.getModuleFlag("Debug Info Version")))
499 return Val->getZExtValue();
503 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
504 llvm::makeSubprogramMap(const Module &M) {
505 DenseMap<const Function *, DISubprogram> R;
507 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
511 for (MDNode *N : CU_Nodes->operands()) {
512 DICompileUnit CUNode = cast<MDCompileUnit>(N);
513 for (DISubprogram SP : CUNode->getSubprograms()) {
514 if (Function *F = SP.getFunction())
515 R.insert(std::make_pair(F, SP));