DebugInfo: Add forwarding getFilename() accessor to new hierarchy
[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 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
147   get()->replaceSubprograms(MDSubprogramArray(Subprograms));
148 }
149
150 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
151   get()->replaceGlobalVariables(MDGlobalVariableArray(GlobalVariables));
152 }
153
154 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
155                                         DILexicalBlockFile NewScope) {
156   assert(NewScope && "Expected valid scope");
157
158   const auto *Old = cast<MDLocation>(DbgNode);
159   return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
160                                     NewScope, Old->getInlinedAt()));
161 }
162
163 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
164   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
165   return ++Ctx.pImpl->DiscriminatorTable[Key];
166 }
167
168 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
169                                        LLVMContext &VMContext) {
170   return cast<MDLocalVariable>(DV)
171       ->withInline(cast_or_null<MDLocation>(InlinedScope));
172 }
173
174 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
175   return cast<MDLocalVariable>(DV)->withoutInline();
176 }
177
178 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
179   if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
180     return LocalScope->getSubprogram();
181   return nullptr;
182 }
183
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();
189     });
190     if (Inst == BB.end())
191       continue;
192     DebugLoc DLoc = Inst->getDebugLoc();
193     const MDNode *Scope = DLoc.getInlinedAtScope();
194     DISubprogram Subprogram = getDISubprogram(Scope);
195     return Subprogram.describes(F) ? Subprogram : DISubprogram();
196   }
197
198   return DISubprogram();
199 }
200
201 DICompositeType llvm::getDICompositeType(DIType T) {
202   if (auto *C = dyn_cast_or_null<MDCompositeTypeBase>(T))
203     return C;
204
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));
212   }
213
214   return nullptr;
215 }
216
217 DITypeIdentifierMap
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]))
225         continue;
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;
236       }
237     }
238   }
239   return Map;
240 }
241
242 //===----------------------------------------------------------------------===//
243 // DebugInfoFinder implementations.
244 //===----------------------------------------------------------------------===//
245
246 void DebugInfoFinder::reset() {
247   CUs.clear();
248   SPs.clear();
249   GVs.clear();
250   TYs.clear();
251   Scopes.clear();
252   NodesSeen.clear();
253   TypeIdentifierMap.clear();
254   TypeMapInitialized = false;
255 }
256
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;
262     }
263 }
264
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));
270       addCompileUnit(CU);
271       for (DIGlobalVariable DIG : CU->getGlobalVariables()) {
272         if (addGlobalVariable(DIG)) {
273           processScope(DIG.getContext());
274           processType(DIG.getType().resolve(TypeIdentifierMap));
275         }
276       }
277       for (auto *SP : CU->getSubprograms())
278         processSubprogram(SP);
279       for (auto *ET : CU->getEnumTypes())
280         processType(ET);
281       for (auto *RT : CU->getRetainedTypes())
282         processType(RT);
283       for (DIImportedEntity Import : CU->getImportedEntities()) {
284         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
285         if (auto *T = dyn_cast<MDType>(Entity))
286           processType(T);
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());
291       }
292     }
293   }
294 }
295
296 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
297   if (!Loc)
298     return;
299   InitializeTypeMap(M);
300   processScope(Loc.getScope());
301   processLocation(M, Loc.getOrigLocation());
302 }
303
304 void DebugInfoFinder::processType(DIType DT) {
305   if (!addType(DT))
306     return;
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));
313       return;
314     }
315     for (Metadata *D : DCT->getElements()->operands()) {
316       if (DIType T = dyn_cast<MDType>(D))
317         processType(T);
318       else if (DISubprogram SP = dyn_cast<MDSubprogram>(D))
319         processSubprogram(SP);
320     }
321   } else if (DIDerivedType DDT = dyn_cast<MDDerivedTypeBase>(DT)) {
322     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
323   }
324 }
325
326 void DebugInfoFinder::processScope(DIScope Scope) {
327   if (!Scope)
328     return;
329   if (DIType Ty = dyn_cast<MDType>(Scope)) {
330     processType(Ty);
331     return;
332   }
333   if (DICompileUnit CU = dyn_cast<MDCompileUnit>(Scope)) {
334     addCompileUnit(CU);
335     return;
336   }
337   if (DISubprogram SP = dyn_cast<MDSubprogram>(Scope)) {
338     processSubprogram(SP);
339     return;
340   }
341   if (!addScope(Scope))
342     return;
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());
347   }
348 }
349
350 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
351   if (!addSubprogram(SP))
352     return;
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));
362     }
363   }
364 }
365
366 void DebugInfoFinder::processDeclare(const Module &M,
367                                      const DbgDeclareInst *DDI) {
368   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
369   if (!N)
370     return;
371   InitializeTypeMap(M);
372
373   DIVariable DV = dyn_cast<MDLocalVariable>(N);
374   if (!DV)
375     return;
376
377   if (!NodesSeen.insert(DV).second)
378     return;
379   processScope(DV.getContext());
380   processType(DV.getType().resolve(TypeIdentifierMap));
381 }
382
383 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
384   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
385   if (!N)
386     return;
387   InitializeTypeMap(M);
388
389   DIVariable DV = dyn_cast<MDLocalVariable>(N);
390   if (!DV)
391     return;
392
393   if (!NodesSeen.insert(DV).second)
394     return;
395   processScope(DV.getContext());
396   processType(DV.getType().resolve(TypeIdentifierMap));
397 }
398
399 bool DebugInfoFinder::addType(DIType DT) {
400   if (!DT)
401     return false;
402
403   if (!NodesSeen.insert(DT).second)
404     return false;
405
406   TYs.push_back(DT);
407   return true;
408 }
409
410 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
411   if (!CU)
412     return false;
413   if (!NodesSeen.insert(CU).second)
414     return false;
415
416   CUs.push_back(CU);
417   return true;
418 }
419
420 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
421   if (!DIG)
422     return false;
423
424   if (!NodesSeen.insert(DIG).second)
425     return false;
426
427   GVs.push_back(DIG);
428   return true;
429 }
430
431 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
432   if (!SP)
433     return false;
434
435   if (!NodesSeen.insert(SP).second)
436     return false;
437
438   SPs.push_back(SP);
439   return true;
440 }
441
442 bool DebugInfoFinder::addScope(DIScope Scope) {
443   if (!Scope)
444     return false;
445   // FIXME: Ocaml binding generates a scope with no content, we treat it
446   // as null for now.
447   if (Scope->getNumOperands() == 0)
448     return false;
449   if (!NodesSeen.insert(Scope).second)
450     return false;
451   Scopes.push_back(Scope);
452   return true;
453 }
454
455 //===----------------------------------------------------------------------===//
456 // DIDescriptor: dump routines for all descriptors.
457 //===----------------------------------------------------------------------===//
458
459 void DIDescriptor::dump() const {
460   print(dbgs());
461   dbgs() << '\n';
462 }
463
464 void DIDescriptor::print(raw_ostream &OS) const {
465   if (!get())
466     return;
467   get()->print(OS);
468 }
469
470 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
471                           const LLVMContext &Ctx) {
472   if (!DL)
473     return;
474
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();
481
482   DebugLoc InlinedAtDL = DL.getInlinedAt();
483   if (!InlinedAtDL)
484     return;
485
486   CommentOS << " @[ ";
487   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
488   CommentOS << " ]";
489 }
490
491 void DIVariable::printExtendedName(raw_ostream &OS) const {
492   const LLVMContext &Ctx = DbgNode->getContext();
493   StringRef Res = getName();
494   if (!Res.empty())
495     OS << Res << "," << getLineNumber();
496   if (auto *InlinedAt = get()->getInlinedAt()) {
497     if (DebugLoc InlinedAtDL = InlinedAt) {
498       OS << " @[";
499       printDebugLoc(InlinedAtDL, OS, Ctx);
500       OS << "]";
501     }
502   }
503 }
504
505 template <>
506 DIDescriptor
507 DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const {
508   return DIDescriptor(DebugNodeRef(Val).resolve(Map));
509 }
510 template <>
511 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const {
512   return MDScopeRef(Val).resolve(Map);
513 }
514 template <>
515 DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const {
516   return MDTypeRef(Val).resolve(Map);
517 }
518
519 bool llvm::stripDebugInfo(Function &F) {
520   bool Changed = false;
521   for (BasicBlock &BB : F) {
522     for (Instruction &I : BB) {
523       if (I.getDebugLoc()) {
524         Changed = true;
525         I.setDebugLoc(DebugLoc());
526       }
527     }
528   }
529   return Changed;
530 }
531
532 bool llvm::StripDebugInfo(Module &M) {
533   bool Changed = false;
534
535   // Remove all of the calls to the debugger intrinsics, and remove them from
536   // the module.
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();
541     }
542     Declare->eraseFromParent();
543     Changed = true;
544   }
545
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();
550     }
551     DbgVal->eraseFromParent();
552     Changed = true;
553   }
554
555   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
556          NME = M.named_metadata_end(); NMI != NME;) {
557     NamedMDNode *NMD = NMI;
558     ++NMI;
559     if (NMD->getName().startswith("llvm.dbg.")) {
560       NMD->eraseFromParent();
561       Changed = true;
562     }
563   }
564
565   for (Function &F : M)
566     Changed |= stripDebugInfo(F);
567
568   if (GVMaterializer *Materializer = M.getMaterializer())
569     Materializer->setStripDebugInfo();
570
571   return Changed;
572 }
573
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();
578   return 0;
579 }
580
581 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
582 llvm::makeSubprogramMap(const Module &M) {
583   DenseMap<const Function *, DISubprogram> R;
584
585   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
586   if (!CU_Nodes)
587     return R;
588
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));
594     }
595   }
596   return R;
597 }