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 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
41 if (!DbgNode || Elt >= DbgNode->getNumOperands())
43 return DbgNode->getOperand(Elt);
46 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
47 return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
50 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
51 MDNode *Field = getNodeField(DbgNode, Elt);
52 return DIDescriptor(Field);
55 /// \brief Return the size reported by the variable's type.
56 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
57 DIType Ty = getType().resolve(Map);
58 // Follow derived types until we reach a type that
59 // reports back a size.
60 while (isa<MDDerivedType>(Ty) && !Ty.getSizeInBits()) {
61 DIDerivedType DT = cast<MDDerivedType>(Ty);
62 Ty = DT.getTypeDerivedFrom().resolve(Map);
64 assert(Ty.getSizeInBits() && "type with size 0");
65 return Ty.getSizeInBits();
68 //===----------------------------------------------------------------------===//
69 // Simple Descriptor Constructors and other Methods
70 //===----------------------------------------------------------------------===//
72 void DIDescriptor::replaceAllUsesWith(LLVMContext &, DIDescriptor D) {
73 assert(DbgNode && "Trying to replace an unverified type!");
74 assert(DbgNode->isTemporary() && "Expected temporary node");
75 TempMDNode Temp(get());
77 // Since we use a TrackingVH for the node, its easy for clients to manufacture
78 // legitimate situations where they want to replaceAllUsesWith() on something
79 // which, due to uniquing, has merged with the source. We shield clients from
80 // this detail by allowing a value to be replaced with replaceAllUsesWith()
82 if (Temp.get() == D.get()) {
83 DbgNode = MDNode::replaceWithUniqued(std::move(Temp));
87 Temp->replaceAllUsesWith(D.get());
91 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
92 assert(DbgNode && "Trying to replace an unverified type!");
93 assert(DbgNode != D && "This replacement should always happen");
94 assert(DbgNode->isTemporary() && "Expected temporary node");
95 TempMDNode Node(get());
96 Node->replaceAllUsesWith(D);
99 DIScopeRef DIScope::getRef() const { return MDScopeRef::get(get()); }
101 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
102 assert(CurFn && "Invalid function");
103 DISubprogram SP = dyn_cast<MDSubprogram>(getContext());
106 // This variable is not inlined function argument if its scope
107 // does not describe current function.
108 return !SP.describes(CurFn);
111 Function *DISubprogram::getFunction() const {
113 if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
114 return dyn_cast<Function>(C->getValue());
118 bool DISubprogram::describes(const Function *F) {
119 assert(F && "Invalid function");
120 if (F == getFunction())
122 StringRef Name = getLinkageName();
125 if (F->getName() == Name)
130 GlobalVariable *DIGlobalVariable::getGlobal() const {
131 return dyn_cast_or_null<GlobalVariable>(getConstant());
134 DIScopeRef DIScope::getContext() const {
135 if (DIType T = dyn_cast<MDType>(*this))
136 return T.getContext();
138 if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
139 return MDScopeRef(SP.getContext());
141 if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(*this))
142 return MDScopeRef(LB.getContext());
144 if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
145 return MDScopeRef(NS.getContext());
147 assert((isa<MDFile>(*this) || isa<MDCompileUnit>(*this)) &&
148 "Unhandled type of scope.");
152 StringRef DIScope::getName() const {
153 if (DIType T = dyn_cast<MDType>(*this))
155 if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
157 if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
159 assert((isa<MDLexicalBlockBase>(*this) || isa<MDFile>(*this) ||
160 isa<MDCompileUnit>(*this)) &&
161 "Unhandled type of scope.");
165 StringRef DIScope::getFilename() const {
167 if (auto *F = N->getFile())
168 return F->getFilename();
172 StringRef DIScope::getDirectory() const {
174 if (auto *F = N->getFile())
175 return F->getDirectory();
179 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
180 get()->replaceSubprograms(MDSubprogramArray(Subprograms));
183 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
184 get()->replaceGlobalVariables(MDGlobalVariableArray(GlobalVariables));
187 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
188 DILexicalBlockFile NewScope) {
189 assert(NewScope && "Expected valid scope");
191 const auto *Old = cast<MDLocation>(DbgNode);
192 return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
193 NewScope, Old->getInlinedAt()));
196 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
197 std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
198 return ++Ctx.pImpl->DiscriminatorTable[Key];
201 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
202 LLVMContext &VMContext) {
203 return cast<MDLocalVariable>(DV)
204 ->withInline(cast_or_null<MDLocation>(InlinedScope));
207 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
208 return cast<MDLocalVariable>(DV)->withoutInline();
211 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
212 if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
213 return LocalScope->getSubprogram();
217 DISubprogram llvm::getDISubprogram(const Function *F) {
218 // We look for the first instr that has a debug annotation leading back to F.
219 for (auto &BB : *F) {
220 auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
221 return Inst.getDebugLoc();
223 if (Inst == BB.end())
225 DebugLoc DLoc = Inst->getDebugLoc();
226 const MDNode *Scope = DLoc.getInlinedAtScope();
227 DISubprogram Subprogram = getDISubprogram(Scope);
228 return Subprogram.describes(F) ? Subprogram : DISubprogram();
231 return DISubprogram();
234 DICompositeType llvm::getDICompositeType(DIType T) {
235 if (auto *C = dyn_cast_or_null<MDCompositeTypeBase>(T))
238 if (auto *D = dyn_cast_or_null<MDDerivedTypeBase>(T)) {
239 // This function is currently used by dragonegg and dragonegg does
240 // not generate identifier for types, so using an empty map to resolve
241 // DerivedFrom should be fine.
242 DITypeIdentifierMap EmptyMap;
243 return getDICompositeType(
244 DIDerivedType(D).getTypeDerivedFrom().resolve(EmptyMap));
251 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
252 DITypeIdentifierMap Map;
253 for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
254 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(CUi));
255 DIArray Retain = CU.getRetainedTypes();
256 for (unsigned Ti = 0, Te = Retain.size(); Ti != Te; ++Ti) {
257 if (!isa<MDCompositeType>(Retain[Ti]))
259 DICompositeType Ty = cast<MDCompositeType>(Retain[Ti]);
260 if (MDString *TypeId = Ty.getIdentifier()) {
261 // Definition has priority over declaration.
262 // Try to insert (TypeId, Ty) to Map.
263 std::pair<DITypeIdentifierMap::iterator, bool> P =
264 Map.insert(std::make_pair(TypeId, Ty));
265 // If TypeId already exists in Map and this is a definition, replace
266 // whatever we had (declaration or definition) with the definition.
267 if (!P.second && !Ty.isForwardDecl())
268 P.first->second = Ty;
275 //===----------------------------------------------------------------------===//
276 // DebugInfoFinder implementations.
277 //===----------------------------------------------------------------------===//
279 void DebugInfoFinder::reset() {
286 TypeIdentifierMap.clear();
287 TypeMapInitialized = false;
290 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
291 if (!TypeMapInitialized)
292 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
293 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
294 TypeMapInitialized = true;
298 void DebugInfoFinder::processModule(const Module &M) {
299 InitializeTypeMap(M);
300 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
301 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
302 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(i));
304 for (DIGlobalVariable DIG : CU->getGlobalVariables()) {
305 if (addGlobalVariable(DIG)) {
306 processScope(DIG.getContext());
307 processType(DIG.getType().resolve(TypeIdentifierMap));
310 for (auto *SP : CU->getSubprograms())
311 processSubprogram(SP);
312 for (auto *ET : CU->getEnumTypes())
314 for (auto *RT : CU->getRetainedTypes())
316 for (DIImportedEntity Import : CU->getImportedEntities()) {
317 DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
318 if (auto *T = dyn_cast<MDType>(Entity))
320 else if (auto *SP = dyn_cast<MDSubprogram>(Entity))
321 processSubprogram(SP);
322 else if (auto *NS = dyn_cast<MDNamespace>(Entity))
323 processScope(NS->getScope());
329 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
332 InitializeTypeMap(M);
333 processScope(Loc.getScope());
334 processLocation(M, Loc.getOrigLocation());
337 void DebugInfoFinder::processType(DIType DT) {
340 processScope(DT.getContext().resolve(TypeIdentifierMap));
341 if (DICompositeType DCT = dyn_cast<MDCompositeTypeBase>(DT)) {
342 processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
343 if (DISubroutineType ST = dyn_cast<MDSubroutineType>(DCT)) {
344 for (MDTypeRef Ref : ST->getTypeArray())
345 processType(Ref.resolve(TypeIdentifierMap));
348 for (Metadata *D : DCT->getElements()->operands()) {
349 if (DIType T = dyn_cast<MDType>(D))
351 else if (DISubprogram SP = dyn_cast<MDSubprogram>(D))
352 processSubprogram(SP);
354 } else if (DIDerivedType DDT = dyn_cast<MDDerivedTypeBase>(DT)) {
355 processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
359 void DebugInfoFinder::processScope(DIScope Scope) {
362 if (DIType Ty = dyn_cast<MDType>(Scope)) {
366 if (DICompileUnit CU = dyn_cast<MDCompileUnit>(Scope)) {
370 if (DISubprogram SP = dyn_cast<MDSubprogram>(Scope)) {
371 processSubprogram(SP);
374 if (!addScope(Scope))
376 if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(Scope)) {
377 processScope(LB.getContext());
378 } else if (DINameSpace NS = dyn_cast<MDNamespace>(Scope)) {
379 processScope(NS.getContext());
383 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
384 if (!addSubprogram(SP))
386 processScope(SP.getContext().resolve(TypeIdentifierMap));
387 processType(SP.getType());
388 for (auto *Element : SP.getTemplateParams()) {
389 if (DITemplateTypeParameter TType =
390 dyn_cast<MDTemplateTypeParameter>(Element)) {
391 processType(TType.getType().resolve(TypeIdentifierMap));
392 } else if (DITemplateValueParameter TVal =
393 dyn_cast<MDTemplateValueParameter>(Element)) {
394 processType(TVal.getType().resolve(TypeIdentifierMap));
399 void DebugInfoFinder::processDeclare(const Module &M,
400 const DbgDeclareInst *DDI) {
401 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
404 InitializeTypeMap(M);
406 DIVariable DV = dyn_cast<MDLocalVariable>(N);
410 if (!NodesSeen.insert(DV).second)
412 processScope(DV.getContext());
413 processType(DV.getType().resolve(TypeIdentifierMap));
416 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
417 MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
420 InitializeTypeMap(M);
422 DIVariable DV = dyn_cast<MDLocalVariable>(N);
426 if (!NodesSeen.insert(DV).second)
428 processScope(DV.getContext());
429 processType(DV.getType().resolve(TypeIdentifierMap));
432 bool DebugInfoFinder::addType(DIType DT) {
436 if (!NodesSeen.insert(DT).second)
443 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
446 if (!NodesSeen.insert(CU).second)
453 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
457 if (!NodesSeen.insert(DIG).second)
464 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
468 if (!NodesSeen.insert(SP).second)
475 bool DebugInfoFinder::addScope(DIScope Scope) {
478 // FIXME: Ocaml binding generates a scope with no content, we treat it
480 if (Scope->getNumOperands() == 0)
482 if (!NodesSeen.insert(Scope).second)
484 Scopes.push_back(Scope);
488 //===----------------------------------------------------------------------===//
489 // DIDescriptor: dump routines for all descriptors.
490 //===----------------------------------------------------------------------===//
492 void DIDescriptor::dump() const {
497 void DIDescriptor::print(raw_ostream &OS) const {
503 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
504 const LLVMContext &Ctx) {
508 DIScope Scope = cast<MDScope>(DL.getScope());
509 // Omit the directory, because it's likely to be long and uninteresting.
510 CommentOS << Scope.getFilename();
511 CommentOS << ':' << DL.getLine();
512 if (DL.getCol() != 0)
513 CommentOS << ':' << DL.getCol();
515 DebugLoc InlinedAtDL = DL.getInlinedAt();
520 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
524 void DIVariable::printExtendedName(raw_ostream &OS) const {
525 const LLVMContext &Ctx = DbgNode->getContext();
526 StringRef Res = getName();
528 OS << Res << "," << getLineNumber();
529 if (auto *InlinedAt = get()->getInlinedAt()) {
530 if (DebugLoc InlinedAtDL = InlinedAt) {
532 printDebugLoc(InlinedAtDL, OS, Ctx);
540 DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const {
541 return DIDescriptor(DebugNodeRef(Val).resolve(Map));
544 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const {
545 return MDScopeRef(Val).resolve(Map);
548 DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const {
549 return MDTypeRef(Val).resolve(Map);
552 bool llvm::stripDebugInfo(Function &F) {
553 bool Changed = false;
554 for (BasicBlock &BB : F) {
555 for (Instruction &I : BB) {
556 if (I.getDebugLoc()) {
558 I.setDebugLoc(DebugLoc());
565 bool llvm::StripDebugInfo(Module &M) {
566 bool Changed = false;
568 // Remove all of the calls to the debugger intrinsics, and remove them from
570 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
571 while (!Declare->use_empty()) {
572 CallInst *CI = cast<CallInst>(Declare->user_back());
573 CI->eraseFromParent();
575 Declare->eraseFromParent();
579 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
580 while (!DbgVal->use_empty()) {
581 CallInst *CI = cast<CallInst>(DbgVal->user_back());
582 CI->eraseFromParent();
584 DbgVal->eraseFromParent();
588 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
589 NME = M.named_metadata_end(); NMI != NME;) {
590 NamedMDNode *NMD = NMI;
592 if (NMD->getName().startswith("llvm.dbg.")) {
593 NMD->eraseFromParent();
598 for (Function &F : M)
599 Changed |= stripDebugInfo(F);
601 if (GVMaterializer *Materializer = M.getMaterializer())
602 Materializer->setStripDebugInfo();
607 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
608 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
609 M.getModuleFlag("Debug Info Version")))
610 return Val->getZExtValue();
614 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
615 llvm::makeSubprogramMap(const Module &M) {
616 DenseMap<const Function *, DISubprogram> R;
618 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
622 for (MDNode *N : CU_Nodes->operands()) {
623 DICompileUnit CUNode = cast<MDCompileUnit>(N);
624 for (DISubprogram SP : CUNode->getSubprograms()) {
625 if (Function *F = SP.getFunction())
626 R.insert(std::make_pair(F, SP));