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 /// \brief Return the size reported by the variable's type.
37 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
38 DIType Ty = getType().resolve(Map);
39 // Follow derived types until we reach a type that
40 // reports back a size.
41 while (isa<MDDerivedType>(Ty) && !Ty.getSizeInBits()) {
42 DIDerivedType DT = cast<MDDerivedType>(Ty);
43 Ty = DT.getTypeDerivedFrom().resolve(Map);
45 assert(Ty.getSizeInBits() && "type with size 0");
46 return Ty.getSizeInBits();
49 //===----------------------------------------------------------------------===//
50 // Simple Descriptor Constructors and other Methods
51 //===----------------------------------------------------------------------===//
53 void DIDescriptor::replaceAllUsesWith(LLVMContext &, DIDescriptor D) {
54 assert(DbgNode && "Trying to replace an unverified type!");
55 assert(DbgNode->isTemporary() && "Expected temporary node");
56 TempMDNode Temp(get());
58 // Since we use a TrackingVH for the node, its easy for clients to manufacture
59 // legitimate situations where they want to replaceAllUsesWith() on something
60 // which, due to uniquing, has merged with the source. We shield clients from
61 // this detail by allowing a value to be replaced with replaceAllUsesWith()
63 if (Temp.get() == D.get()) {
64 DbgNode = MDNode::replaceWithUniqued(std::move(Temp));
68 Temp->replaceAllUsesWith(D.get());
72 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
73 assert(DbgNode && "Trying to replace an unverified type!");
74 assert(DbgNode != D && "This replacement should always happen");
75 assert(DbgNode->isTemporary() && "Expected temporary node");
76 TempMDNode Node(get());
77 Node->replaceAllUsesWith(D);
80 DIScopeRef DIScope::getRef() const { return MDScopeRef::get(get()); }
82 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
83 assert(CurFn && "Invalid function");
84 DISubprogram SP = dyn_cast<MDSubprogram>(getContext());
87 // This variable is not inlined function argument if its scope
88 // does not describe current function.
89 return !SP.describes(CurFn);
92 Function *DISubprogram::getFunction() const {
94 if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
95 return dyn_cast<Function>(C->getValue());
99 bool DISubprogram::describes(const Function *F) {
100 assert(F && "Invalid function");
101 if (F == getFunction())
103 StringRef Name = getLinkageName();
106 if (F->getName() == Name)
111 GlobalVariable *DIGlobalVariable::getGlobal() const {
112 return dyn_cast_or_null<GlobalVariable>(getConstant());
115 DIScopeRef DIScope::getContext() const {
116 if (DIType T = dyn_cast<MDType>(*this))
117 return T.getContext();
119 if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
120 return MDScopeRef(SP.getContext());
122 if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(*this))
123 return MDScopeRef(LB.getContext());
125 if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
126 return MDScopeRef(NS.getContext());
128 assert((isa<MDFile>(*this) || isa<MDCompileUnit>(*this)) &&
129 "Unhandled type of scope.");
133 StringRef DIScope::getName() const {
134 if (DIType T = dyn_cast<MDType>(*this))
136 if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
138 if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
140 assert((isa<MDLexicalBlockBase>(*this) || isa<MDFile>(*this) ||
141 isa<MDCompileUnit>(*this)) &&
142 "Unhandled type of scope.");
146 StringRef DIScope::getFilename() const {
148 if (auto *F = N->getFile())
149 return F->getFilename();
153 StringRef DIScope::getDirectory() const {
155 if (auto *F = N->getFile())
156 return F->getDirectory();
160 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
161 get()->replaceSubprograms(MDSubprogramArray(Subprograms));
164 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
165 get()->replaceGlobalVariables(MDGlobalVariableArray(GlobalVariables));
168 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
169 DILexicalBlockFile NewScope) {
170 assert(NewScope && "Expected valid scope");
172 const auto *Old = cast<MDLocation>(DbgNode);
173 return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
174 NewScope, Old->getInlinedAt()));
177 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
178 std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
179 return ++Ctx.pImpl->DiscriminatorTable[Key];
182 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
183 LLVMContext &VMContext) {
184 return cast<MDLocalVariable>(DV)
185 ->withInline(cast_or_null<MDLocation>(InlinedScope));
188 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
189 return cast<MDLocalVariable>(DV)->withoutInline();
192 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
193 if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
194 return LocalScope->getSubprogram();
198 DISubprogram llvm::getDISubprogram(const Function *F) {
199 // We look for the first instr that has a debug annotation leading back to F.
200 for (auto &BB : *F) {
201 auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
202 return Inst.getDebugLoc();
204 if (Inst == BB.end())
206 DebugLoc DLoc = Inst->getDebugLoc();
207 const MDNode *Scope = DLoc.getInlinedAtScope();
208 DISubprogram Subprogram = getDISubprogram(Scope);
209 return Subprogram.describes(F) ? Subprogram : DISubprogram();
212 return DISubprogram();
215 DICompositeType llvm::getDICompositeType(DIType T) {
216 if (auto *C = dyn_cast_or_null<MDCompositeTypeBase>(T))
219 if (auto *D = dyn_cast_or_null<MDDerivedTypeBase>(T)) {
220 // This function is currently used by dragonegg and dragonegg does
221 // not generate identifier for types, so using an empty map to resolve
222 // DerivedFrom should be fine.
223 DITypeIdentifierMap EmptyMap;
224 return getDICompositeType(
225 DIDerivedType(D).getTypeDerivedFrom().resolve(EmptyMap));
232 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
233 DITypeIdentifierMap Map;
234 for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
235 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(CUi));
236 DIArray Retain = CU.getRetainedTypes();
237 for (unsigned Ti = 0, Te = Retain.size(); Ti != Te; ++Ti) {
238 if (!isa<MDCompositeType>(Retain[Ti]))
240 DICompositeType Ty = cast<MDCompositeType>(Retain[Ti]);
241 if (MDString *TypeId = Ty.getIdentifier()) {
242 // Definition has priority over declaration.
243 // Try to insert (TypeId, Ty) to Map.
244 std::pair<DITypeIdentifierMap::iterator, bool> P =
245 Map.insert(std::make_pair(TypeId, Ty));
246 // If TypeId already exists in Map and this is a definition, replace
247 // whatever we had (declaration or definition) with the definition.
248 if (!P.second && !Ty.isForwardDecl())
249 P.first->second = Ty;
256 //===----------------------------------------------------------------------===//
257 // DebugInfoFinder implementations.
258 //===----------------------------------------------------------------------===//
260 void DebugInfoFinder::reset() {
267 TypeIdentifierMap.clear();
268 TypeMapInitialized = false;
271 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
272 if (!TypeMapInitialized)
273 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
274 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
275 TypeMapInitialized = true;
279 void DebugInfoFinder::processModule(const Module &M) {
280 InitializeTypeMap(M);
281 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
282 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
283 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(i));
285 for (DIGlobalVariable DIG : CU->getGlobalVariables()) {
286 if (addGlobalVariable(DIG)) {
287 processScope(DIG.getContext());
288 processType(DIG.getType().resolve(TypeIdentifierMap));
291 for (auto *SP : CU->getSubprograms())
292 processSubprogram(SP);
293 for (auto *ET : CU->getEnumTypes())
295 for (auto *RT : CU->getRetainedTypes())
297 for (DIImportedEntity Import : CU->getImportedEntities()) {
298 DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
299 if (auto *T = dyn_cast<MDType>(Entity))
301 else if (auto *SP = dyn_cast<MDSubprogram>(Entity))
302 processSubprogram(SP);
303 else if (auto *NS = dyn_cast<MDNamespace>(Entity))
304 processScope(NS->getScope());
310 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
313 InitializeTypeMap(M);
314 processScope(Loc.getScope());
315 processLocation(M, Loc.getOrigLocation());
318 void DebugInfoFinder::processType(DIType DT) {
321 processScope(DT.getContext().resolve(TypeIdentifierMap));
322 if (DICompositeType DCT = dyn_cast<MDCompositeTypeBase>(DT)) {
323 processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
324 if (DISubroutineType ST = dyn_cast<MDSubroutineType>(DCT)) {
325 for (MDTypeRef Ref : ST->getTypeArray())
326 processType(Ref.resolve(TypeIdentifierMap));
329 for (Metadata *D : DCT->getElements()->operands()) {
330 if (DIType T = dyn_cast<MDType>(D))
332 else if (DISubprogram SP = dyn_cast<MDSubprogram>(D))
333 processSubprogram(SP);
335 } else if (DIDerivedType DDT = dyn_cast<MDDerivedTypeBase>(DT)) {
336 processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
340 void DebugInfoFinder::processScope(DIScope Scope) {
343 if (DIType Ty = dyn_cast<MDType>(Scope)) {
347 if (DICompileUnit CU = dyn_cast<MDCompileUnit>(Scope)) {
351 if (DISubprogram SP = dyn_cast<MDSubprogram>(Scope)) {
352 processSubprogram(SP);
355 if (!addScope(Scope))
357 if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(Scope)) {
358 processScope(LB.getContext());
359 } else if (DINameSpace NS = dyn_cast<MDNamespace>(Scope)) {
360 processScope(NS.getContext());
364 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
365 if (!addSubprogram(SP))
367 processScope(SP.getContext().resolve(TypeIdentifierMap));
368 processType(SP.getType());
369 for (auto *Element : SP.getTemplateParams()) {
370 if (DITemplateTypeParameter TType =
371 dyn_cast<MDTemplateTypeParameter>(Element)) {
372 processType(TType.getType().resolve(TypeIdentifierMap));
373 } else if (DITemplateValueParameter TVal =
374 dyn_cast<MDTemplateValueParameter>(Element)) {
375 processType(TVal.getType().resolve(TypeIdentifierMap));
380 void DebugInfoFinder::processDeclare(const Module &M,
381 const DbgDeclareInst *DDI) {
382 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
385 InitializeTypeMap(M);
387 DIVariable DV = dyn_cast<MDLocalVariable>(N);
391 if (!NodesSeen.insert(DV).second)
393 processScope(DV.getContext());
394 processType(DV.getType().resolve(TypeIdentifierMap));
397 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
398 MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
401 InitializeTypeMap(M);
403 DIVariable DV = dyn_cast<MDLocalVariable>(N);
407 if (!NodesSeen.insert(DV).second)
409 processScope(DV.getContext());
410 processType(DV.getType().resolve(TypeIdentifierMap));
413 bool DebugInfoFinder::addType(DIType DT) {
417 if (!NodesSeen.insert(DT).second)
424 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
427 if (!NodesSeen.insert(CU).second)
434 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
438 if (!NodesSeen.insert(DIG).second)
445 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
449 if (!NodesSeen.insert(SP).second)
456 bool DebugInfoFinder::addScope(DIScope Scope) {
459 // FIXME: Ocaml binding generates a scope with no content, we treat it
461 if (Scope->getNumOperands() == 0)
463 if (!NodesSeen.insert(Scope).second)
465 Scopes.push_back(Scope);
469 //===----------------------------------------------------------------------===//
470 // DIDescriptor: dump routines for all descriptors.
471 //===----------------------------------------------------------------------===//
473 void DIDescriptor::dump() const {
478 void DIDescriptor::print(raw_ostream &OS) const {
484 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
485 const LLVMContext &Ctx) {
489 DIScope Scope = cast<MDScope>(DL.getScope());
490 // Omit the directory, because it's likely to be long and uninteresting.
491 CommentOS << Scope.getFilename();
492 CommentOS << ':' << DL.getLine();
493 if (DL.getCol() != 0)
494 CommentOS << ':' << DL.getCol();
496 DebugLoc InlinedAtDL = DL.getInlinedAt();
501 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
505 void DIVariable::printExtendedName(raw_ostream &OS) const {
506 const LLVMContext &Ctx = DbgNode->getContext();
507 StringRef Res = getName();
509 OS << Res << "," << getLineNumber();
510 if (auto *InlinedAt = get()->getInlinedAt()) {
511 if (DebugLoc InlinedAtDL = InlinedAt) {
513 printDebugLoc(InlinedAtDL, OS, Ctx);
521 DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const {
522 return DIDescriptor(DebugNodeRef(Val).resolve(Map));
525 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const {
526 return MDScopeRef(Val).resolve(Map);
529 DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const {
530 return MDTypeRef(Val).resolve(Map);
533 bool llvm::stripDebugInfo(Function &F) {
534 bool Changed = false;
535 for (BasicBlock &BB : F) {
536 for (Instruction &I : BB) {
537 if (I.getDebugLoc()) {
539 I.setDebugLoc(DebugLoc());
546 bool llvm::StripDebugInfo(Module &M) {
547 bool Changed = false;
549 // Remove all of the calls to the debugger intrinsics, and remove them from
551 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
552 while (!Declare->use_empty()) {
553 CallInst *CI = cast<CallInst>(Declare->user_back());
554 CI->eraseFromParent();
556 Declare->eraseFromParent();
560 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
561 while (!DbgVal->use_empty()) {
562 CallInst *CI = cast<CallInst>(DbgVal->user_back());
563 CI->eraseFromParent();
565 DbgVal->eraseFromParent();
569 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
570 NME = M.named_metadata_end(); NMI != NME;) {
571 NamedMDNode *NMD = NMI;
573 if (NMD->getName().startswith("llvm.dbg.")) {
574 NMD->eraseFromParent();
579 for (Function &F : M)
580 Changed |= stripDebugInfo(F);
582 if (GVMaterializer *Materializer = M.getMaterializer())
583 Materializer->setStripDebugInfo();
588 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
589 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
590 M.getModuleFlag("Debug Info Version")))
591 return Val->getZExtValue();
595 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
596 llvm::makeSubprogramMap(const Module &M) {
597 DenseMap<const Function *, DISubprogram> R;
599 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
603 for (MDNode *N : CU_Nodes->operands()) {
604 DICompileUnit CUNode = cast<MDCompileUnit>(N);
605 for (DISubprogram SP : CUNode->getSubprograms()) {
606 if (Function *F = SP.getFunction())
607 R.insert(std::make_pair(F, SP));