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 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
147 get()->replaceSubprograms(MDSubprogramArray(Subprograms));
150 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
151 get()->replaceGlobalVariables(MDGlobalVariableArray(GlobalVariables));
154 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
155 DILexicalBlockFile NewScope) {
156 assert(NewScope && "Expected valid scope");
158 const auto *Old = cast<MDLocation>(DbgNode);
159 return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
160 NewScope, Old->getInlinedAt()));
163 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
164 std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
165 return ++Ctx.pImpl->DiscriminatorTable[Key];
168 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
169 LLVMContext &VMContext) {
170 return cast<MDLocalVariable>(DV)
171 ->withInline(cast_or_null<MDLocation>(InlinedScope));
174 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
175 return cast<MDLocalVariable>(DV)->withoutInline();
178 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
179 if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
180 return LocalScope->getSubprogram();
184 DISubprogram llvm::getDISubprogram(const Function *F) {
185 // We look for the first instr that has a debug annotation leading back to F.
186 for (auto &BB : *F) {
187 auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
188 return Inst.getDebugLoc();
190 if (Inst == BB.end())
192 DebugLoc DLoc = Inst->getDebugLoc();
193 const MDNode *Scope = DLoc.getInlinedAtScope();
194 DISubprogram Subprogram = getDISubprogram(Scope);
195 return Subprogram.describes(F) ? Subprogram : DISubprogram();
198 return DISubprogram();
201 DICompositeType llvm::getDICompositeType(DIType T) {
202 if (auto *C = dyn_cast_or_null<MDCompositeTypeBase>(T))
205 if (auto *D = dyn_cast_or_null<MDDerivedTypeBase>(T)) {
206 // This function is currently used by dragonegg and dragonegg does
207 // not generate identifier for types, so using an empty map to resolve
208 // DerivedFrom should be fine.
209 DITypeIdentifierMap EmptyMap;
210 return getDICompositeType(
211 DIDerivedType(D).getTypeDerivedFrom().resolve(EmptyMap));
218 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
219 DITypeIdentifierMap Map;
220 for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
221 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(CUi));
222 DIArray Retain = CU.getRetainedTypes();
223 for (unsigned Ti = 0, Te = Retain.size(); Ti != Te; ++Ti) {
224 if (!isa<MDCompositeType>(Retain[Ti]))
226 DICompositeType Ty = cast<MDCompositeType>(Retain[Ti]);
227 if (MDString *TypeId = Ty.getIdentifier()) {
228 // Definition has priority over declaration.
229 // Try to insert (TypeId, Ty) to Map.
230 std::pair<DITypeIdentifierMap::iterator, bool> P =
231 Map.insert(std::make_pair(TypeId, Ty));
232 // If TypeId already exists in Map and this is a definition, replace
233 // whatever we had (declaration or definition) with the definition.
234 if (!P.second && !Ty.isForwardDecl())
235 P.first->second = Ty;
242 //===----------------------------------------------------------------------===//
243 // DebugInfoFinder implementations.
244 //===----------------------------------------------------------------------===//
246 void DebugInfoFinder::reset() {
253 TypeIdentifierMap.clear();
254 TypeMapInitialized = false;
257 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
258 if (!TypeMapInitialized)
259 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
260 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
261 TypeMapInitialized = true;
265 void DebugInfoFinder::processModule(const Module &M) {
266 InitializeTypeMap(M);
267 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
268 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
269 DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(i));
271 for (DIGlobalVariable DIG : CU->getGlobalVariables()) {
272 if (addGlobalVariable(DIG)) {
273 processScope(DIG.getContext());
274 processType(DIG.getType().resolve(TypeIdentifierMap));
277 for (auto *SP : CU->getSubprograms())
278 processSubprogram(SP);
279 for (auto *ET : CU->getEnumTypes())
281 for (auto *RT : CU->getRetainedTypes())
283 for (DIImportedEntity Import : CU->getImportedEntities()) {
284 DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
285 if (auto *T = dyn_cast<MDType>(Entity))
287 else if (auto *SP = dyn_cast<MDSubprogram>(Entity))
288 processSubprogram(SP);
289 else if (auto *NS = dyn_cast<MDNamespace>(Entity))
290 processScope(NS->getScope());
296 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
299 InitializeTypeMap(M);
300 processScope(Loc.getScope());
301 processLocation(M, Loc.getOrigLocation());
304 void DebugInfoFinder::processType(DIType DT) {
307 processScope(DT.getContext().resolve(TypeIdentifierMap));
308 if (DICompositeType DCT = dyn_cast<MDCompositeTypeBase>(DT)) {
309 processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
310 if (DISubroutineType ST = dyn_cast<MDSubroutineType>(DCT)) {
311 for (MDTypeRef Ref : ST->getTypeArray())
312 processType(Ref.resolve(TypeIdentifierMap));
315 for (Metadata *D : DCT->getElements()->operands()) {
316 if (DIType T = dyn_cast<MDType>(D))
318 else if (DISubprogram SP = dyn_cast<MDSubprogram>(D))
319 processSubprogram(SP);
321 } else if (DIDerivedType DDT = dyn_cast<MDDerivedTypeBase>(DT)) {
322 processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
326 void DebugInfoFinder::processScope(DIScope Scope) {
329 if (DIType Ty = dyn_cast<MDType>(Scope)) {
333 if (DICompileUnit CU = dyn_cast<MDCompileUnit>(Scope)) {
337 if (DISubprogram SP = dyn_cast<MDSubprogram>(Scope)) {
338 processSubprogram(SP);
341 if (!addScope(Scope))
343 if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(Scope)) {
344 processScope(LB.getContext());
345 } else if (DINameSpace NS = dyn_cast<MDNamespace>(Scope)) {
346 processScope(NS.getContext());
350 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
351 if (!addSubprogram(SP))
353 processScope(SP.getContext().resolve(TypeIdentifierMap));
354 processType(SP.getType());
355 for (auto *Element : SP.getTemplateParams()) {
356 if (DITemplateTypeParameter TType =
357 dyn_cast<MDTemplateTypeParameter>(Element)) {
358 processType(TType.getType().resolve(TypeIdentifierMap));
359 } else if (DITemplateValueParameter TVal =
360 dyn_cast<MDTemplateValueParameter>(Element)) {
361 processType(TVal.getType().resolve(TypeIdentifierMap));
366 void DebugInfoFinder::processDeclare(const Module &M,
367 const DbgDeclareInst *DDI) {
368 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
371 InitializeTypeMap(M);
373 DIVariable DV = dyn_cast<MDLocalVariable>(N);
377 if (!NodesSeen.insert(DV).second)
379 processScope(DV.getContext());
380 processType(DV.getType().resolve(TypeIdentifierMap));
383 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
384 MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
387 InitializeTypeMap(M);
389 DIVariable DV = dyn_cast<MDLocalVariable>(N);
393 if (!NodesSeen.insert(DV).second)
395 processScope(DV.getContext());
396 processType(DV.getType().resolve(TypeIdentifierMap));
399 bool DebugInfoFinder::addType(DIType DT) {
403 if (!NodesSeen.insert(DT).second)
410 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
413 if (!NodesSeen.insert(CU).second)
420 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
424 if (!NodesSeen.insert(DIG).second)
431 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
435 if (!NodesSeen.insert(SP).second)
442 bool DebugInfoFinder::addScope(DIScope Scope) {
445 // FIXME: Ocaml binding generates a scope with no content, we treat it
447 if (Scope->getNumOperands() == 0)
449 if (!NodesSeen.insert(Scope).second)
451 Scopes.push_back(Scope);
455 //===----------------------------------------------------------------------===//
456 // DIDescriptor: dump routines for all descriptors.
457 //===----------------------------------------------------------------------===//
459 void DIDescriptor::dump() const {
464 void DIDescriptor::print(raw_ostream &OS) const {
470 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
471 const LLVMContext &Ctx) {
475 DIScope Scope = cast<MDScope>(DL.getScope());
476 // Omit the directory, because it's likely to be long and uninteresting.
477 CommentOS << Scope.getFilename();
478 CommentOS << ':' << DL.getLine();
479 if (DL.getCol() != 0)
480 CommentOS << ':' << DL.getCol();
482 DebugLoc InlinedAtDL = DL.getInlinedAt();
487 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
491 void DIVariable::printExtendedName(raw_ostream &OS) const {
492 const LLVMContext &Ctx = DbgNode->getContext();
493 StringRef Res = getName();
495 OS << Res << "," << getLineNumber();
496 if (auto *InlinedAt = get()->getInlinedAt()) {
497 if (DebugLoc InlinedAtDL = InlinedAt) {
499 printDebugLoc(InlinedAtDL, OS, Ctx);
507 DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const {
508 return DIDescriptor(DebugNodeRef(Val).resolve(Map));
511 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const {
512 return MDScopeRef(Val).resolve(Map);
515 DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const {
516 return MDTypeRef(Val).resolve(Map);
519 bool llvm::stripDebugInfo(Function &F) {
520 bool Changed = false;
521 for (BasicBlock &BB : F) {
522 for (Instruction &I : BB) {
523 if (I.getDebugLoc()) {
525 I.setDebugLoc(DebugLoc());
532 bool llvm::StripDebugInfo(Module &M) {
533 bool Changed = false;
535 // Remove all of the calls to the debugger intrinsics, and remove them from
537 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
538 while (!Declare->use_empty()) {
539 CallInst *CI = cast<CallInst>(Declare->user_back());
540 CI->eraseFromParent();
542 Declare->eraseFromParent();
546 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
547 while (!DbgVal->use_empty()) {
548 CallInst *CI = cast<CallInst>(DbgVal->user_back());
549 CI->eraseFromParent();
551 DbgVal->eraseFromParent();
555 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
556 NME = M.named_metadata_end(); NMI != NME;) {
557 NamedMDNode *NMD = NMI;
559 if (NMD->getName().startswith("llvm.dbg.")) {
560 NMD->eraseFromParent();
565 for (Function &F : M)
566 Changed |= stripDebugInfo(F);
568 if (GVMaterializer *Materializer = M.getMaterializer())
569 Materializer->setStripDebugInfo();
574 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
575 if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
576 M.getModuleFlag("Debug Info Version")))
577 return Val->getZExtValue();
581 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
582 llvm::makeSubprogramMap(const Module &M) {
583 DenseMap<const Function *, DISubprogram> R;
585 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
589 for (MDNode *N : CU_Nodes->operands()) {
590 DICompileUnit CUNode = cast<MDCompileUnit>(N);
591 for (DISubprogram SP : CUNode->getSubprograms()) {
592 if (Function *F = SP.getFunction())
593 R.insert(std::make_pair(F, SP));