SelectionDAG: Stop using DIVariable::isInlinedFnArgument()
[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 //===----------------------------------------------------------------------===//
37 // Simple Descriptor Constructors and other Methods
38 //===----------------------------------------------------------------------===//
39
40 DIScopeRef DIScope::getRef() const { return MDScopeRef::get(get()); }
41
42 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
43   get()->replaceSubprograms(MDSubprogramArray(Subprograms));
44 }
45
46 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
47   get()->replaceGlobalVariables(MDGlobalVariableArray(GlobalVariables));
48 }
49
50 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
51                                         DILexicalBlockFile NewScope) {
52   assert(NewScope && "Expected valid scope");
53
54   const auto *Old = cast<MDLocation>(DbgNode);
55   return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
56                                     NewScope, Old->getInlinedAt()));
57 }
58
59 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
60   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
61   return ++Ctx.pImpl->DiscriminatorTable[Key];
62 }
63
64 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
65                                        LLVMContext &VMContext) {
66   return cast<MDLocalVariable>(DV)
67       ->withInline(cast_or_null<MDLocation>(InlinedScope));
68 }
69
70 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
71   return cast<MDLocalVariable>(DV)->withoutInline();
72 }
73
74 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
75   if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
76     return LocalScope->getSubprogram();
77   return nullptr;
78 }
79
80 DISubprogram llvm::getDISubprogram(const Function *F) {
81   // We look for the first instr that has a debug annotation leading back to F.
82   for (auto &BB : *F) {
83     auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
84       return Inst.getDebugLoc();
85     });
86     if (Inst == BB.end())
87       continue;
88     DebugLoc DLoc = Inst->getDebugLoc();
89     const MDNode *Scope = DLoc.getInlinedAtScope();
90     DISubprogram Subprogram = getDISubprogram(Scope);
91     return Subprogram.describes(F) ? Subprogram : DISubprogram();
92   }
93
94   return DISubprogram();
95 }
96
97 DICompositeType llvm::getDICompositeType(DIType T) {
98   if (auto *C = dyn_cast_or_null<MDCompositeTypeBase>(T))
99     return C;
100
101   if (auto *D = dyn_cast_or_null<MDDerivedTypeBase>(T)) {
102     // This function is currently used by dragonegg and dragonegg does
103     // not generate identifier for types, so using an empty map to resolve
104     // DerivedFrom should be fine.
105     DITypeIdentifierMap EmptyMap;
106     return getDICompositeType(
107         DIDerivedType(D).getTypeDerivedFrom().resolve(EmptyMap));
108   }
109
110   return nullptr;
111 }
112
113 DITypeIdentifierMap
114 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
115   DITypeIdentifierMap Map;
116   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
117     DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(CUi));
118     DIArray Retain = CU.getRetainedTypes();
119     for (unsigned Ti = 0, Te = Retain.size(); Ti != Te; ++Ti) {
120       if (!isa<MDCompositeType>(Retain[Ti]))
121         continue;
122       DICompositeType Ty = cast<MDCompositeType>(Retain[Ti]);
123       if (MDString *TypeId = Ty.getIdentifier()) {
124         // Definition has priority over declaration.
125         // Try to insert (TypeId, Ty) to Map.
126         std::pair<DITypeIdentifierMap::iterator, bool> P =
127             Map.insert(std::make_pair(TypeId, Ty));
128         // If TypeId already exists in Map and this is a definition, replace
129         // whatever we had (declaration or definition) with the definition.
130         if (!P.second && !Ty.isForwardDecl())
131           P.first->second = Ty;
132       }
133     }
134   }
135   return Map;
136 }
137
138 //===----------------------------------------------------------------------===//
139 // DebugInfoFinder implementations.
140 //===----------------------------------------------------------------------===//
141
142 void DebugInfoFinder::reset() {
143   CUs.clear();
144   SPs.clear();
145   GVs.clear();
146   TYs.clear();
147   Scopes.clear();
148   NodesSeen.clear();
149   TypeIdentifierMap.clear();
150   TypeMapInitialized = false;
151 }
152
153 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
154   if (!TypeMapInitialized)
155     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
156       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
157       TypeMapInitialized = true;
158     }
159 }
160
161 void DebugInfoFinder::processModule(const Module &M) {
162   InitializeTypeMap(M);
163   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
164     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
165       DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(i));
166       addCompileUnit(CU);
167       for (DIGlobalVariable DIG : CU->getGlobalVariables()) {
168         if (addGlobalVariable(DIG)) {
169           processScope(DIG.getContext());
170           processType(DIG.getType().resolve(TypeIdentifierMap));
171         }
172       }
173       for (auto *SP : CU->getSubprograms())
174         processSubprogram(SP);
175       for (auto *ET : CU->getEnumTypes())
176         processType(ET);
177       for (auto *RT : CU->getRetainedTypes())
178         processType(RT);
179       for (DIImportedEntity Import : CU->getImportedEntities()) {
180         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
181         if (auto *T = dyn_cast<MDType>(Entity))
182           processType(T);
183         else if (auto *SP = dyn_cast<MDSubprogram>(Entity))
184           processSubprogram(SP);
185         else if (auto *NS = dyn_cast<MDNamespace>(Entity))
186           processScope(NS->getScope());
187       }
188     }
189   }
190 }
191
192 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
193   if (!Loc)
194     return;
195   InitializeTypeMap(M);
196   processScope(Loc.getScope());
197   processLocation(M, Loc.getOrigLocation());
198 }
199
200 void DebugInfoFinder::processType(DIType DT) {
201   if (!addType(DT))
202     return;
203   processScope(DT.getContext().resolve(TypeIdentifierMap));
204   if (DICompositeType DCT = dyn_cast<MDCompositeTypeBase>(DT)) {
205     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
206     if (DISubroutineType ST = dyn_cast<MDSubroutineType>(DCT)) {
207       for (MDTypeRef Ref : ST->getTypeArray())
208         processType(Ref.resolve(TypeIdentifierMap));
209       return;
210     }
211     for (Metadata *D : DCT->getElements()->operands()) {
212       if (DIType T = dyn_cast<MDType>(D))
213         processType(T);
214       else if (DISubprogram SP = dyn_cast<MDSubprogram>(D))
215         processSubprogram(SP);
216     }
217   } else if (DIDerivedType DDT = dyn_cast<MDDerivedTypeBase>(DT)) {
218     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
219   }
220 }
221
222 void DebugInfoFinder::processScope(DIScope Scope) {
223   if (!Scope)
224     return;
225   if (DIType Ty = dyn_cast<MDType>(Scope)) {
226     processType(Ty);
227     return;
228   }
229   if (DICompileUnit CU = dyn_cast<MDCompileUnit>(Scope)) {
230     addCompileUnit(CU);
231     return;
232   }
233   if (DISubprogram SP = dyn_cast<MDSubprogram>(Scope)) {
234     processSubprogram(SP);
235     return;
236   }
237   if (!addScope(Scope))
238     return;
239   if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(Scope)) {
240     processScope(LB.getContext());
241   } else if (DINameSpace NS = dyn_cast<MDNamespace>(Scope)) {
242     processScope(NS.getContext());
243   }
244 }
245
246 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
247   if (!addSubprogram(SP))
248     return;
249   processScope(SP.getContext().resolve(TypeIdentifierMap));
250   processType(SP.getType());
251   for (auto *Element : SP.getTemplateParams()) {
252     if (DITemplateTypeParameter TType =
253             dyn_cast<MDTemplateTypeParameter>(Element)) {
254       processType(TType.getType().resolve(TypeIdentifierMap));
255     } else if (DITemplateValueParameter TVal =
256                    dyn_cast<MDTemplateValueParameter>(Element)) {
257       processType(TVal.getType().resolve(TypeIdentifierMap));
258     }
259   }
260 }
261
262 void DebugInfoFinder::processDeclare(const Module &M,
263                                      const DbgDeclareInst *DDI) {
264   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
265   if (!N)
266     return;
267   InitializeTypeMap(M);
268
269   DIVariable DV = dyn_cast<MDLocalVariable>(N);
270   if (!DV)
271     return;
272
273   if (!NodesSeen.insert(DV).second)
274     return;
275   processScope(DV.getContext());
276   processType(DV.getType().resolve(TypeIdentifierMap));
277 }
278
279 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
280   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
281   if (!N)
282     return;
283   InitializeTypeMap(M);
284
285   DIVariable DV = dyn_cast<MDLocalVariable>(N);
286   if (!DV)
287     return;
288
289   if (!NodesSeen.insert(DV).second)
290     return;
291   processScope(DV.getContext());
292   processType(DV.getType().resolve(TypeIdentifierMap));
293 }
294
295 bool DebugInfoFinder::addType(DIType DT) {
296   if (!DT)
297     return false;
298
299   if (!NodesSeen.insert(DT).second)
300     return false;
301
302   TYs.push_back(DT);
303   return true;
304 }
305
306 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
307   if (!CU)
308     return false;
309   if (!NodesSeen.insert(CU).second)
310     return false;
311
312   CUs.push_back(CU);
313   return true;
314 }
315
316 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
317   if (!DIG)
318     return false;
319
320   if (!NodesSeen.insert(DIG).second)
321     return false;
322
323   GVs.push_back(DIG);
324   return true;
325 }
326
327 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
328   if (!SP)
329     return false;
330
331   if (!NodesSeen.insert(SP).second)
332     return false;
333
334   SPs.push_back(SP);
335   return true;
336 }
337
338 bool DebugInfoFinder::addScope(DIScope Scope) {
339   if (!Scope)
340     return false;
341   // FIXME: Ocaml binding generates a scope with no content, we treat it
342   // as null for now.
343   if (Scope->getNumOperands() == 0)
344     return false;
345   if (!NodesSeen.insert(Scope).second)
346     return false;
347   Scopes.push_back(Scope);
348   return true;
349 }
350
351 //===----------------------------------------------------------------------===//
352 // DIDescriptor: dump routines for all descriptors.
353 //===----------------------------------------------------------------------===//
354
355 void DIDescriptor::dump() const {
356   print(dbgs());
357   dbgs() << '\n';
358 }
359
360 void DIDescriptor::print(raw_ostream &OS) const {
361   if (!get())
362     return;
363   get()->print(OS);
364 }
365
366 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
367                           const LLVMContext &Ctx) {
368   if (!DL)
369     return;
370
371   DIScope Scope = cast<MDScope>(DL.getScope());
372   // Omit the directory, because it's likely to be long and uninteresting.
373   CommentOS << Scope.getFilename();
374   CommentOS << ':' << DL.getLine();
375   if (DL.getCol() != 0)
376     CommentOS << ':' << DL.getCol();
377
378   DebugLoc InlinedAtDL = DL.getInlinedAt();
379   if (!InlinedAtDL)
380     return;
381
382   CommentOS << " @[ ";
383   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
384   CommentOS << " ]";
385 }
386
387 void DIVariable::printExtendedName(raw_ostream &OS) const {
388   const LLVMContext &Ctx = DbgNode->getContext();
389   StringRef Res = getName();
390   if (!Res.empty())
391     OS << Res << "," << getLineNumber();
392   if (auto *InlinedAt = get()->getInlinedAt()) {
393     if (DebugLoc InlinedAtDL = InlinedAt) {
394       OS << " @[";
395       printDebugLoc(InlinedAtDL, OS, Ctx);
396       OS << "]";
397     }
398   }
399 }
400
401 template <>
402 DIDescriptor
403 DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const {
404   return DIDescriptor(DebugNodeRef(Val).resolve(Map));
405 }
406 template <>
407 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const {
408   return MDScopeRef(Val).resolve(Map);
409 }
410 template <>
411 DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const {
412   return MDTypeRef(Val).resolve(Map);
413 }
414
415 bool llvm::stripDebugInfo(Function &F) {
416   bool Changed = false;
417   for (BasicBlock &BB : F) {
418     for (Instruction &I : BB) {
419       if (I.getDebugLoc()) {
420         Changed = true;
421         I.setDebugLoc(DebugLoc());
422       }
423     }
424   }
425   return Changed;
426 }
427
428 bool llvm::StripDebugInfo(Module &M) {
429   bool Changed = false;
430
431   // Remove all of the calls to the debugger intrinsics, and remove them from
432   // the module.
433   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
434     while (!Declare->use_empty()) {
435       CallInst *CI = cast<CallInst>(Declare->user_back());
436       CI->eraseFromParent();
437     }
438     Declare->eraseFromParent();
439     Changed = true;
440   }
441
442   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
443     while (!DbgVal->use_empty()) {
444       CallInst *CI = cast<CallInst>(DbgVal->user_back());
445       CI->eraseFromParent();
446     }
447     DbgVal->eraseFromParent();
448     Changed = true;
449   }
450
451   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
452          NME = M.named_metadata_end(); NMI != NME;) {
453     NamedMDNode *NMD = NMI;
454     ++NMI;
455     if (NMD->getName().startswith("llvm.dbg.")) {
456       NMD->eraseFromParent();
457       Changed = true;
458     }
459   }
460
461   for (Function &F : M)
462     Changed |= stripDebugInfo(F);
463
464   if (GVMaterializer *Materializer = M.getMaterializer())
465     Materializer->setStripDebugInfo();
466
467   return Changed;
468 }
469
470 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
471   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
472           M.getModuleFlag("Debug Info Version")))
473     return Val->getZExtValue();
474   return 0;
475 }
476
477 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
478 llvm::makeSubprogramMap(const Module &M) {
479   DenseMap<const Function *, DISubprogram> R;
480
481   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
482   if (!CU_Nodes)
483     return R;
484
485   for (MDNode *N : CU_Nodes->operands()) {
486     DICompileUnit CUNode = cast<MDCompileUnit>(N);
487     for (DISubprogram SP : CUNode->getSubprograms()) {
488       if (Function *F = SP.getFunction())
489         R.insert(std::make_pair(F, SP));
490     }
491   }
492   return R;
493 }