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