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 bool DIExpression::isBitPiece() const {
69 unsigned N = getNumElements();
70 return N >=3 && getElement(N-3) == dwarf::DW_OP_bit_piece;
73 uint64_t DIExpression::getBitPieceOffset() const {
74 assert(isBitPiece() && "not a piece");
75 return getElement(getNumElements()-2);
78 uint64_t DIExpression::getBitPieceSize() const {
79 assert(isBitPiece() && "not a piece");
80 return getElement(getNumElements()-1);
83 //===----------------------------------------------------------------------===//
84 // Simple Descriptor Constructors and other Methods
85 //===----------------------------------------------------------------------===//
87 void DIDescriptor::replaceAllUsesWith(LLVMContext &, DIDescriptor D) {
88 assert(DbgNode && "Trying to replace an unverified type!");
89 assert(DbgNode->isTemporary() && "Expected temporary node");
90 TempMDNode Temp(get());
92 // Since we use a TrackingVH for the node, its easy for clients to manufacture
93 // legitimate situations where they want to replaceAllUsesWith() on something
94 // which, due to uniquing, has merged with the source. We shield clients from
95 // this detail by allowing a value to be replaced with replaceAllUsesWith()
97 if (Temp.get() == D.get()) {
98 DbgNode = MDNode::replaceWithUniqued(std::move(Temp));
102 Temp->replaceAllUsesWith(D.get());
106 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
107 assert(DbgNode && "Trying to replace an unverified type!");
108 assert(DbgNode != D && "This replacement should always happen");
109 assert(DbgNode->isTemporary() && "Expected temporary node");
110 TempMDNode Node(get());
111 Node->replaceAllUsesWith(D);
115 /// \brief Check if a value can be a reference to a type.
116 static bool isTypeRef(const Metadata *MD) {
119 if (auto *S = dyn_cast<MDString>(MD))
120 return !S->getString().empty();
121 return isa<MDType>(MD);
124 /// \brief Check if a value can be a ScopeRef.
125 static bool isScopeRef(const Metadata *MD) {
128 if (auto *S = dyn_cast<MDString>(MD))
129 return !S->getString().empty();
130 return isa<MDScope>(MD);
133 /// \brief Check if a value can be a DescriptorRef.
134 static bool isDescriptorRef(const Metadata *MD) {
137 if (auto *S = dyn_cast<MDString>(MD))
138 return !S->getString().empty();
139 return isa<MDNode>(MD);
143 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
144 TypedTrackingMDRef<MDCompositeTypeBase> N(get());
146 N->replaceElements(cast<MDTuple>(Elements));
148 N->replaceTemplateParams(cast<MDTuple>(TParams));
152 DIScopeRef DIScope::getRef() const { return MDScopeRef::get(get()); }
154 void DICompositeType::setContainingType(DICompositeType ContainingType) {
155 TypedTrackingMDRef<MDCompositeTypeBase> N(get());
156 N->replaceVTableHolder(MDTypeRef::get(ContainingType));
160 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
161 assert(CurFn && "Invalid function");
162 DISubprogram SP = dyn_cast<MDSubprogram>(getContext());
165 // This variable is not inlined function argument if its scope
166 // does not describe current function.
167 return !SP.describes(CurFn);
170 Function *DISubprogram::getFunction() const {
172 if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
173 return dyn_cast<Function>(C->getValue());
177 bool DISubprogram::describes(const Function *F) {
178 assert(F && "Invalid function");
179 if (F == getFunction())
181 StringRef Name = getLinkageName();
184 if (F->getName() == Name)
189 GlobalVariable *DIGlobalVariable::getGlobal() const {
190 return dyn_cast_or_null<GlobalVariable>(getConstant());
193 DIScopeRef DIScope::getContext() const {
194 if (DIType T = dyn_cast<MDType>(*this))
195 return T.getContext();
197 if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
198 return DIScopeRef(SP.getContext());
200 if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(*this))
201 return DIScopeRef(LB.getContext());
203 if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
204 return DIScopeRef(NS.getContext());
206 assert((isa<MDFile>(*this) || isa<MDCompileUnit>(*this)) &&
207 "Unhandled type of scope.");
208 return DIScopeRef(nullptr);
211 StringRef DIScope::getName() const {
212 if (DIType T = dyn_cast<MDType>(*this))
214 if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
216 if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
218 assert((isa<MDLexicalBlockBase>(*this) || isa<MDFile>(*this) ||
219 isa<MDCompileUnit>(*this)) &&
220 "Unhandled type of scope.");
224 StringRef DIScope::getFilename() const {
226 if (auto *F = N->getFile())
227 return F->getFilename();
231 StringRef DIScope::getDirectory() const {
233 if (auto *F = N->getFile())
234 return F->getDirectory();
238 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
239 get()->replaceSubprograms(cast_or_null<MDTuple>(Subprograms.get()));
242 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
243 get()->replaceGlobalVariables(cast_or_null<MDTuple>(GlobalVariables.get()));
246 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
247 DILexicalBlockFile NewScope) {
248 assert(NewScope && "Expected valid scope");
250 const auto *Old = cast<MDLocation>(DbgNode);
251 return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
252 NewScope, Old->getInlinedAt()));
255 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
256 std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
257 return ++Ctx.pImpl->DiscriminatorTable[Key];
260 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
261 LLVMContext &VMContext) {
262 return cast<MDLocalVariable>(DV)
263 ->withInline(cast_or_null<MDLocation>(InlinedScope));
266 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
267 return cast<MDLocalVariable>(DV)->withoutInline();
270 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
271 if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
272 return LocalScope->getSubprogram();
276 DISubprogram llvm::getDISubprogram(const Function *F) {
277 // We look for the first instr that has a debug annotation leading back to F.
278 for (auto &BB : *F) {
279 auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
280 return Inst.getDebugLoc();
282 if (Inst == BB.end())
284 DebugLoc DLoc = Inst->getDebugLoc();
285 const MDNode *Scope = DLoc.getInlinedAtScope();
286 DISubprogram Subprogram = getDISubprogram(Scope);
287 return Subprogram.describes(F) ? Subprogram : DISubprogram();
290 return DISubprogram();
293 DICompositeType llvm::getDICompositeType(DIType T) {
294 if (auto *C = dyn_cast_or_null<MDCompositeTypeBase>(T))
297 if (auto *D = dyn_cast_or_null<MDDerivedTypeBase>(T)) {
298 // This function is currently used by dragonegg and dragonegg does
299 // not generate identifier for types, so using an empty map to resolve
300 // DerivedFrom should be fine.
301 DITypeIdentifierMap EmptyMap;
302 return getDICompositeType(
303 DIDerivedType(D).getTypeDerivedFrom().resolve(EmptyMap));
310 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
311 DITypeIdentifierMap Map;
312 for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
313 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(CUi));
314 DIArray Retain = CU.getRetainedTypes();
315 for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
316 if (!isa<MDCompositeType>(Retain.getElement(Ti)))
318 DICompositeType Ty = cast<MDCompositeType>(Retain.getElement(Ti));
319 if (MDString *TypeId = Ty.getIdentifier()) {
320 // Definition has priority over declaration.
321 // Try to insert (TypeId, Ty) to Map.
322 std::pair<DITypeIdentifierMap::iterator, bool> P =
323 Map.insert(std::make_pair(TypeId, Ty));
324 // If TypeId already exists in Map and this is a definition, replace
325 // whatever we had (declaration or definition) with the definition.
326 if (!P.second && !Ty.isForwardDecl())
327 P.first->second = Ty;
334 //===----------------------------------------------------------------------===//
335 // DebugInfoFinder implementations.
336 //===----------------------------------------------------------------------===//
338 void DebugInfoFinder::reset() {
345 TypeIdentifierMap.clear();
346 TypeMapInitialized = false;
349 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
350 if (!TypeMapInitialized)
351 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
352 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
353 TypeMapInitialized = true;
357 void DebugInfoFinder::processModule(const Module &M) {
358 InitializeTypeMap(M);
359 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
360 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
361 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(i));
363 DIArray GVs = CU.getGlobalVariables();
364 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
365 DIGlobalVariable DIG = cast<MDGlobalVariable>(GVs.getElement(i));
366 if (addGlobalVariable(DIG)) {
367 processScope(DIG.getContext());
368 processType(DIG.getType().resolve(TypeIdentifierMap));
371 DIArray SPs = CU.getSubprograms();
372 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
373 processSubprogram(cast<MDSubprogram>(SPs.getElement(i)));
374 DIArray EnumTypes = CU.getEnumTypes();
375 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
376 processType(cast<MDType>(EnumTypes.getElement(i)));
377 DIArray RetainedTypes = CU.getRetainedTypes();
378 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
379 processType(cast<MDType>(RetainedTypes.getElement(i)));
380 DIArray Imports = CU.getImportedEntities();
381 for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
382 DIImportedEntity Import = cast<MDImportedEntity>(Imports.getElement(i));
383 DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
384 if (auto *T = dyn_cast<MDType>(Entity))
386 else if (auto *SP = dyn_cast<MDSubprogram>(Entity))
387 processSubprogram(SP);
388 else if (auto *NS = dyn_cast<MDNamespace>(Entity))
389 processScope(NS->getScope());
395 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
398 InitializeTypeMap(M);
399 processScope(Loc.getScope());
400 processLocation(M, Loc.getOrigLocation());
403 void DebugInfoFinder::processType(DIType DT) {
406 processScope(DT.getContext().resolve(TypeIdentifierMap));
407 if (DICompositeType DCT = dyn_cast<MDCompositeTypeBase>(DT)) {
408 processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
409 if (DISubroutineType ST = dyn_cast<MDSubroutineType>(DCT)) {
410 DITypeArray DTA = ST.getTypeArray();
411 for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
412 processType(DTA.getElement(i).resolve(TypeIdentifierMap));
415 DIArray DA = DCT.getElements();
416 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
417 DIDescriptor D = DA.getElement(i);
418 if (DIType T = dyn_cast<MDType>(D))
420 else if (DISubprogram SP = dyn_cast<MDSubprogram>(D))
421 processSubprogram(SP);
423 } else if (DIDerivedType DDT = dyn_cast<MDDerivedTypeBase>(DT)) {
424 processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
428 void DebugInfoFinder::processScope(DIScope Scope) {
431 if (DIType Ty = dyn_cast<MDType>(Scope)) {
435 if (DICompileUnit CU = dyn_cast<MDCompileUnit>(Scope)) {
439 if (DISubprogram SP = dyn_cast<MDSubprogram>(Scope)) {
440 processSubprogram(SP);
443 if (!addScope(Scope))
445 if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(Scope)) {
446 processScope(LB.getContext());
447 } else if (DINameSpace NS = dyn_cast<MDNamespace>(Scope)) {
448 processScope(NS.getContext());
452 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
453 if (!addSubprogram(SP))
455 processScope(SP.getContext().resolve(TypeIdentifierMap));
456 processType(SP.getType());
457 DIArray TParams = SP.getTemplateParams();
458 for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
459 DIDescriptor Element = TParams.getElement(I);
460 if (DITemplateTypeParameter TType =
461 dyn_cast<MDTemplateTypeParameter>(Element)) {
462 processType(TType.getType().resolve(TypeIdentifierMap));
463 } else if (DITemplateValueParameter TVal =
464 dyn_cast<MDTemplateValueParameter>(Element)) {
465 processType(TVal.getType().resolve(TypeIdentifierMap));
470 void DebugInfoFinder::processDeclare(const Module &M,
471 const DbgDeclareInst *DDI) {
472 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
475 InitializeTypeMap(M);
477 DIVariable DV = dyn_cast<MDLocalVariable>(N);
481 if (!NodesSeen.insert(DV).second)
483 processScope(DV.getContext());
484 processType(DV.getType().resolve(TypeIdentifierMap));
487 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
488 MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
491 InitializeTypeMap(M);
493 DIVariable DV = dyn_cast<MDLocalVariable>(N);
497 if (!NodesSeen.insert(DV).second)
499 processScope(DV.getContext());
500 processType(DV.getType().resolve(TypeIdentifierMap));
503 bool DebugInfoFinder::addType(DIType DT) {
507 if (!NodesSeen.insert(DT).second)
514 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
517 if (!NodesSeen.insert(CU).second)
524 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
528 if (!NodesSeen.insert(DIG).second)
535 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
539 if (!NodesSeen.insert(SP).second)
546 bool DebugInfoFinder::addScope(DIScope Scope) {
549 // FIXME: Ocaml binding generates a scope with no content, we treat it
551 if (Scope->getNumOperands() == 0)
553 if (!NodesSeen.insert(Scope).second)
555 Scopes.push_back(Scope);
559 //===----------------------------------------------------------------------===//
560 // DIDescriptor: dump routines for all descriptors.
561 //===----------------------------------------------------------------------===//
563 void DIDescriptor::dump() const {
568 void DIDescriptor::print(raw_ostream &OS) const {
574 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
575 const LLVMContext &Ctx) {
579 DIScope Scope = cast<MDScope>(DL.getScope());
580 // Omit the directory, because it's likely to be long and uninteresting.
581 CommentOS << Scope.getFilename();
582 CommentOS << ':' << DL.getLine();
583 if (DL.getCol() != 0)
584 CommentOS << ':' << DL.getCol();
586 DebugLoc InlinedAtDL = DL.getInlinedAt();
591 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
595 void DIVariable::printExtendedName(raw_ostream &OS) const {
596 const LLVMContext &Ctx = DbgNode->getContext();
597 StringRef Res = getName();
599 OS << Res << "," << getLineNumber();
600 if (auto *InlinedAt = get()->getInlinedAt()) {
601 if (DebugLoc InlinedAtDL = InlinedAt) {
603 printDebugLoc(InlinedAtDL, OS, Ctx);
609 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V) : Val(V) {
610 assert(isDescriptorRef(V) &&
611 "DIDescriptorRef should be a MDString or MDNode");
613 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
614 assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
616 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
617 assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
621 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const {
622 return DIDescriptorRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
625 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
626 return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
628 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
629 return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
634 DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const {
635 return DIDescriptor(DebugNodeRef(Val).resolve(Map));
638 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const {
639 return MDScopeRef(Val).resolve(Map);
642 DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const {
643 return MDTypeRef(Val).resolve(Map);
646 bool llvm::stripDebugInfo(Function &F) {
647 bool Changed = false;
648 for (BasicBlock &BB : F) {
649 for (Instruction &I : BB) {
650 if (I.getDebugLoc()) {
652 I.setDebugLoc(DebugLoc());
659 bool llvm::StripDebugInfo(Module &M) {
660 bool Changed = false;
662 // Remove all of the calls to the debugger intrinsics, and remove them from
664 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
665 while (!Declare->use_empty()) {
666 CallInst *CI = cast<CallInst>(Declare->user_back());
667 CI->eraseFromParent();
669 Declare->eraseFromParent();
673 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
674 while (!DbgVal->use_empty()) {
675 CallInst *CI = cast<CallInst>(DbgVal->user_back());
676 CI->eraseFromParent();
678 DbgVal->eraseFromParent();
682 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
683 NME = M.named_metadata_end(); NMI != NME;) {
684 NamedMDNode *NMD = NMI;
686 if (NMD->getName().startswith("llvm.dbg.")) {
687 NMD->eraseFromParent();
692 for (Function &F : M)
693 Changed |= stripDebugInfo(F);
695 if (GVMaterializer *Materializer = M.getMaterializer())
696 Materializer->setStripDebugInfo();
701 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
702 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
703 M.getModuleFlag("Debug Info Version")))
704 return Val->getZExtValue();
708 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
709 llvm::makeSubprogramMap(const Module &M) {
710 DenseMap<const Function *, DISubprogram> R;
712 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
716 for (MDNode *N : CU_Nodes->operands()) {
717 DICompileUnit CUNode = cast<MDCompileUnit>(N);
718 DIArray SPs = CUNode.getSubprograms();
719 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
720 DISubprogram SP = cast<MDSubprogram>(SPs.getElement(i));
721 if (Function *F = SP.getFunction())
722 R.insert(std::make_pair(F, SP));