DebugInfo: Remove dead DIDescriptor::getDescriptorField()
[oota-llvm.git] / lib / IR / DebugInfo.cpp
1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
12 //
13 //===----------------------------------------------------------------------===//
14
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"
33 using namespace llvm;
34 using namespace llvm::dwarf;
35
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);
44   }
45   assert(Ty.getSizeInBits() && "type with size 0");
46   return Ty.getSizeInBits();
47 }
48
49 //===----------------------------------------------------------------------===//
50 // Simple Descriptor Constructors and other Methods
51 //===----------------------------------------------------------------------===//
52
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());
57
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()
62   // itself.
63   if (Temp.get() == D.get()) {
64     DbgNode = MDNode::replaceWithUniqued(std::move(Temp));
65     return;
66   }
67
68   Temp->replaceAllUsesWith(D.get());
69   DbgNode = D.get();
70 }
71
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);
78 }
79
80 DIScopeRef DIScope::getRef() const { return MDScopeRef::get(get()); }
81
82 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
83   assert(CurFn && "Invalid function");
84   DISubprogram SP = dyn_cast<MDSubprogram>(getContext());
85   if (!SP)
86     return false;
87   // This variable is not inlined function argument if its scope
88   // does not describe current function.
89   return !SP.describes(CurFn);
90 }
91
92 Function *DISubprogram::getFunction() const {
93   if (auto *N = get())
94     if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
95       return dyn_cast<Function>(C->getValue());
96   return nullptr;
97 }
98
99 bool DISubprogram::describes(const Function *F) {
100   assert(F && "Invalid function");
101   if (F == getFunction())
102     return true;
103   StringRef Name = getLinkageName();
104   if (Name.empty())
105     Name = getName();
106   if (F->getName() == Name)
107     return true;
108   return false;
109 }
110
111 GlobalVariable *DIGlobalVariable::getGlobal() const {
112   return dyn_cast_or_null<GlobalVariable>(getConstant());
113 }
114
115 DIScopeRef DIScope::getContext() const {
116   if (DIType T = dyn_cast<MDType>(*this))
117     return T.getContext();
118
119   if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
120     return MDScopeRef(SP.getContext());
121
122   if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(*this))
123     return MDScopeRef(LB.getContext());
124
125   if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
126     return MDScopeRef(NS.getContext());
127
128   assert((isa<MDFile>(*this) || isa<MDCompileUnit>(*this)) &&
129          "Unhandled type of scope.");
130   return MDScopeRef();
131 }
132
133 StringRef DIScope::getName() const {
134   if (DIType T = dyn_cast<MDType>(*this))
135     return T.getName();
136   if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
137     return SP.getName();
138   if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
139     return NS.getName();
140   assert((isa<MDLexicalBlockBase>(*this) || isa<MDFile>(*this) ||
141           isa<MDCompileUnit>(*this)) &&
142          "Unhandled type of scope.");
143   return StringRef();
144 }
145
146 StringRef DIScope::getFilename() const {
147   if (auto *N = get())
148     if (auto *F = N->getFile())
149       return F->getFilename();
150   return "";
151 }
152
153 StringRef DIScope::getDirectory() const {
154   if (auto *N = get())
155     if (auto *F = N->getFile())
156       return F->getDirectory();
157   return "";
158 }
159
160 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
161   get()->replaceSubprograms(MDSubprogramArray(Subprograms));
162 }
163
164 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
165   get()->replaceGlobalVariables(MDGlobalVariableArray(GlobalVariables));
166 }
167
168 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
169                                         DILexicalBlockFile NewScope) {
170   assert(NewScope && "Expected valid scope");
171
172   const auto *Old = cast<MDLocation>(DbgNode);
173   return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
174                                     NewScope, Old->getInlinedAt()));
175 }
176
177 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
178   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
179   return ++Ctx.pImpl->DiscriminatorTable[Key];
180 }
181
182 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
183                                        LLVMContext &VMContext) {
184   return cast<MDLocalVariable>(DV)
185       ->withInline(cast_or_null<MDLocation>(InlinedScope));
186 }
187
188 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
189   return cast<MDLocalVariable>(DV)->withoutInline();
190 }
191
192 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
193   if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
194     return LocalScope->getSubprogram();
195   return nullptr;
196 }
197
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();
203     });
204     if (Inst == BB.end())
205       continue;
206     DebugLoc DLoc = Inst->getDebugLoc();
207     const MDNode *Scope = DLoc.getInlinedAtScope();
208     DISubprogram Subprogram = getDISubprogram(Scope);
209     return Subprogram.describes(F) ? Subprogram : DISubprogram();
210   }
211
212   return DISubprogram();
213 }
214
215 DICompositeType llvm::getDICompositeType(DIType T) {
216   if (auto *C = dyn_cast_or_null<MDCompositeTypeBase>(T))
217     return C;
218
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));
226   }
227
228   return nullptr;
229 }
230
231 DITypeIdentifierMap
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]))
239         continue;
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;
250       }
251     }
252   }
253   return Map;
254 }
255
256 //===----------------------------------------------------------------------===//
257 // DebugInfoFinder implementations.
258 //===----------------------------------------------------------------------===//
259
260 void DebugInfoFinder::reset() {
261   CUs.clear();
262   SPs.clear();
263   GVs.clear();
264   TYs.clear();
265   Scopes.clear();
266   NodesSeen.clear();
267   TypeIdentifierMap.clear();
268   TypeMapInitialized = false;
269 }
270
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;
276     }
277 }
278
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));
284       addCompileUnit(CU);
285       for (DIGlobalVariable DIG : CU->getGlobalVariables()) {
286         if (addGlobalVariable(DIG)) {
287           processScope(DIG.getContext());
288           processType(DIG.getType().resolve(TypeIdentifierMap));
289         }
290       }
291       for (auto *SP : CU->getSubprograms())
292         processSubprogram(SP);
293       for (auto *ET : CU->getEnumTypes())
294         processType(ET);
295       for (auto *RT : CU->getRetainedTypes())
296         processType(RT);
297       for (DIImportedEntity Import : CU->getImportedEntities()) {
298         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
299         if (auto *T = dyn_cast<MDType>(Entity))
300           processType(T);
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());
305       }
306     }
307   }
308 }
309
310 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
311   if (!Loc)
312     return;
313   InitializeTypeMap(M);
314   processScope(Loc.getScope());
315   processLocation(M, Loc.getOrigLocation());
316 }
317
318 void DebugInfoFinder::processType(DIType DT) {
319   if (!addType(DT))
320     return;
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));
327       return;
328     }
329     for (Metadata *D : DCT->getElements()->operands()) {
330       if (DIType T = dyn_cast<MDType>(D))
331         processType(T);
332       else if (DISubprogram SP = dyn_cast<MDSubprogram>(D))
333         processSubprogram(SP);
334     }
335   } else if (DIDerivedType DDT = dyn_cast<MDDerivedTypeBase>(DT)) {
336     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
337   }
338 }
339
340 void DebugInfoFinder::processScope(DIScope Scope) {
341   if (!Scope)
342     return;
343   if (DIType Ty = dyn_cast<MDType>(Scope)) {
344     processType(Ty);
345     return;
346   }
347   if (DICompileUnit CU = dyn_cast<MDCompileUnit>(Scope)) {
348     addCompileUnit(CU);
349     return;
350   }
351   if (DISubprogram SP = dyn_cast<MDSubprogram>(Scope)) {
352     processSubprogram(SP);
353     return;
354   }
355   if (!addScope(Scope))
356     return;
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());
361   }
362 }
363
364 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
365   if (!addSubprogram(SP))
366     return;
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));
376     }
377   }
378 }
379
380 void DebugInfoFinder::processDeclare(const Module &M,
381                                      const DbgDeclareInst *DDI) {
382   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
383   if (!N)
384     return;
385   InitializeTypeMap(M);
386
387   DIVariable DV = dyn_cast<MDLocalVariable>(N);
388   if (!DV)
389     return;
390
391   if (!NodesSeen.insert(DV).second)
392     return;
393   processScope(DV.getContext());
394   processType(DV.getType().resolve(TypeIdentifierMap));
395 }
396
397 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
398   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
399   if (!N)
400     return;
401   InitializeTypeMap(M);
402
403   DIVariable DV = dyn_cast<MDLocalVariable>(N);
404   if (!DV)
405     return;
406
407   if (!NodesSeen.insert(DV).second)
408     return;
409   processScope(DV.getContext());
410   processType(DV.getType().resolve(TypeIdentifierMap));
411 }
412
413 bool DebugInfoFinder::addType(DIType DT) {
414   if (!DT)
415     return false;
416
417   if (!NodesSeen.insert(DT).second)
418     return false;
419
420   TYs.push_back(DT);
421   return true;
422 }
423
424 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
425   if (!CU)
426     return false;
427   if (!NodesSeen.insert(CU).second)
428     return false;
429
430   CUs.push_back(CU);
431   return true;
432 }
433
434 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
435   if (!DIG)
436     return false;
437
438   if (!NodesSeen.insert(DIG).second)
439     return false;
440
441   GVs.push_back(DIG);
442   return true;
443 }
444
445 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
446   if (!SP)
447     return false;
448
449   if (!NodesSeen.insert(SP).second)
450     return false;
451
452   SPs.push_back(SP);
453   return true;
454 }
455
456 bool DebugInfoFinder::addScope(DIScope Scope) {
457   if (!Scope)
458     return false;
459   // FIXME: Ocaml binding generates a scope with no content, we treat it
460   // as null for now.
461   if (Scope->getNumOperands() == 0)
462     return false;
463   if (!NodesSeen.insert(Scope).second)
464     return false;
465   Scopes.push_back(Scope);
466   return true;
467 }
468
469 //===----------------------------------------------------------------------===//
470 // DIDescriptor: dump routines for all descriptors.
471 //===----------------------------------------------------------------------===//
472
473 void DIDescriptor::dump() const {
474   print(dbgs());
475   dbgs() << '\n';
476 }
477
478 void DIDescriptor::print(raw_ostream &OS) const {
479   if (!get())
480     return;
481   get()->print(OS);
482 }
483
484 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
485                           const LLVMContext &Ctx) {
486   if (!DL)
487     return;
488
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();
495
496   DebugLoc InlinedAtDL = DL.getInlinedAt();
497   if (!InlinedAtDL)
498     return;
499
500   CommentOS << " @[ ";
501   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
502   CommentOS << " ]";
503 }
504
505 void DIVariable::printExtendedName(raw_ostream &OS) const {
506   const LLVMContext &Ctx = DbgNode->getContext();
507   StringRef Res = getName();
508   if (!Res.empty())
509     OS << Res << "," << getLineNumber();
510   if (auto *InlinedAt = get()->getInlinedAt()) {
511     if (DebugLoc InlinedAtDL = InlinedAt) {
512       OS << " @[";
513       printDebugLoc(InlinedAtDL, OS, Ctx);
514       OS << "]";
515     }
516   }
517 }
518
519 template <>
520 DIDescriptor
521 DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const {
522   return DIDescriptor(DebugNodeRef(Val).resolve(Map));
523 }
524 template <>
525 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const {
526   return MDScopeRef(Val).resolve(Map);
527 }
528 template <>
529 DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const {
530   return MDTypeRef(Val).resolve(Map);
531 }
532
533 bool llvm::stripDebugInfo(Function &F) {
534   bool Changed = false;
535   for (BasicBlock &BB : F) {
536     for (Instruction &I : BB) {
537       if (I.getDebugLoc()) {
538         Changed = true;
539         I.setDebugLoc(DebugLoc());
540       }
541     }
542   }
543   return Changed;
544 }
545
546 bool llvm::StripDebugInfo(Module &M) {
547   bool Changed = false;
548
549   // Remove all of the calls to the debugger intrinsics, and remove them from
550   // the module.
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();
555     }
556     Declare->eraseFromParent();
557     Changed = true;
558   }
559
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();
564     }
565     DbgVal->eraseFromParent();
566     Changed = true;
567   }
568
569   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
570          NME = M.named_metadata_end(); NMI != NME;) {
571     NamedMDNode *NMD = NMI;
572     ++NMI;
573     if (NMD->getName().startswith("llvm.dbg.")) {
574       NMD->eraseFromParent();
575       Changed = true;
576     }
577   }
578
579   for (Function &F : M)
580     Changed |= stripDebugInfo(F);
581
582   if (GVMaterializer *Materializer = M.getMaterializer())
583     Materializer->setStripDebugInfo();
584
585   return Changed;
586 }
587
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();
592   return 0;
593 }
594
595 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
596 llvm::makeSubprogramMap(const Module &M) {
597   DenseMap<const Function *, DISubprogram> R;
598
599   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
600   if (!CU_Nodes)
601     return R;
602
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));
608     }
609   }
610   return R;
611 }