DebugInfo: Remove special iterators from DIExpression
[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 // DIDescriptor
38 //===----------------------------------------------------------------------===//
39
40 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
41   if (!DbgNode || Elt >= DbgNode->getNumOperands())
42     return nullptr;
43   return DbgNode->getOperand(Elt);
44 }
45
46 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
47   return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
48 }
49
50 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
51   MDNode *Field = getNodeField(DbgNode, Elt);
52   return DIDescriptor(Field);
53 }
54
55 /// \brief Return the size reported by the variable's type.
56 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
57   DIType Ty = getType().resolve(Map);
58   // Follow derived types until we reach a type that
59   // reports back a size.
60   while (isa<MDDerivedType>(Ty) && !Ty.getSizeInBits()) {
61     DIDerivedType DT = cast<MDDerivedType>(Ty);
62     Ty = DT.getTypeDerivedFrom().resolve(Map);
63   }
64   assert(Ty.getSizeInBits() && "type with size 0");
65   return Ty.getSizeInBits();
66 }
67
68 bool DIExpression::isBitPiece() const {
69   unsigned N = getNumElements();
70   return N >=3 && getElement(N-3) == dwarf::DW_OP_bit_piece;
71 }
72
73 uint64_t DIExpression::getBitPieceOffset() const {
74   assert(isBitPiece() && "not a piece");
75   return getElement(getNumElements()-2);
76 }
77
78 uint64_t DIExpression::getBitPieceSize() const {
79   assert(isBitPiece() && "not a piece");
80   return getElement(getNumElements()-1);
81 }
82
83 //===----------------------------------------------------------------------===//
84 // Simple Descriptor Constructors and other Methods
85 //===----------------------------------------------------------------------===//
86
87 void DIDescriptor::replaceAllUsesWith(LLVMContext &, DIDescriptor D) {
88   assert(DbgNode && "Trying to replace an unverified type!");
89   assert(DbgNode->isTemporary() && "Expected temporary node");
90   TempMDNode Temp(get());
91
92   // Since we use a TrackingVH for the node, its easy for clients to manufacture
93   // legitimate situations where they want to replaceAllUsesWith() on something
94   // which, due to uniquing, has merged with the source. We shield clients from
95   // this detail by allowing a value to be replaced with replaceAllUsesWith()
96   // itself.
97   if (Temp.get() == D.get()) {
98     DbgNode = MDNode::replaceWithUniqued(std::move(Temp));
99     return;
100   }
101
102   Temp->replaceAllUsesWith(D.get());
103   DbgNode = D.get();
104 }
105
106 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
107   assert(DbgNode && "Trying to replace an unverified type!");
108   assert(DbgNode != D && "This replacement should always happen");
109   assert(DbgNode->isTemporary() && "Expected temporary node");
110   TempMDNode Node(get());
111   Node->replaceAllUsesWith(D);
112 }
113
114 #ifndef NDEBUG
115 /// \brief Check if a value can be a reference to a type.
116 static bool isTypeRef(const Metadata *MD) {
117   if (!MD)
118     return true;
119   if (auto *S = dyn_cast<MDString>(MD))
120     return !S->getString().empty();
121   return isa<MDType>(MD);
122 }
123
124 /// \brief Check if a value can be a ScopeRef.
125 static bool isScopeRef(const Metadata *MD) {
126   if (!MD)
127     return true;
128   if (auto *S = dyn_cast<MDString>(MD))
129     return !S->getString().empty();
130   return isa<MDScope>(MD);
131 }
132
133 /// \brief Check if a value can be a DescriptorRef.
134 static bool isDescriptorRef(const Metadata *MD) {
135   if (!MD)
136     return true;
137   if (auto *S = dyn_cast<MDString>(MD))
138     return !S->getString().empty();
139   return isa<MDNode>(MD);
140 }
141 #endif
142
143 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
144   TypedTrackingMDRef<MDCompositeTypeBase> N(get());
145   if (Elements)
146     N->replaceElements(cast<MDTuple>(Elements));
147   if (TParams)
148     N->replaceTemplateParams(cast<MDTuple>(TParams));
149   DbgNode = N;
150 }
151
152 DIScopeRef DIScope::getRef() const { return MDScopeRef::get(get()); }
153
154 void DICompositeType::setContainingType(DICompositeType ContainingType) {
155   TypedTrackingMDRef<MDCompositeTypeBase> N(get());
156   N->replaceVTableHolder(MDTypeRef::get(ContainingType));
157   DbgNode = N;
158 }
159
160 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
161   assert(CurFn && "Invalid function");
162   DISubprogram SP = dyn_cast<MDSubprogram>(getContext());
163   if (!SP)
164     return false;
165   // This variable is not inlined function argument if its scope
166   // does not describe current function.
167   return !SP.describes(CurFn);
168 }
169
170 Function *DISubprogram::getFunction() const {
171   if (auto *N = get())
172     if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
173       return dyn_cast<Function>(C->getValue());
174   return nullptr;
175 }
176
177 bool DISubprogram::describes(const Function *F) {
178   assert(F && "Invalid function");
179   if (F == getFunction())
180     return true;
181   StringRef Name = getLinkageName();
182   if (Name.empty())
183     Name = getName();
184   if (F->getName() == Name)
185     return true;
186   return false;
187 }
188
189 GlobalVariable *DIGlobalVariable::getGlobal() const {
190   return dyn_cast_or_null<GlobalVariable>(getConstant());
191 }
192
193 DIScopeRef DIScope::getContext() const {
194   if (DIType T = dyn_cast<MDType>(*this))
195     return T.getContext();
196
197   if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
198     return DIScopeRef(SP.getContext());
199
200   if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(*this))
201     return DIScopeRef(LB.getContext());
202
203   if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
204     return DIScopeRef(NS.getContext());
205
206   assert((isa<MDFile>(*this) || isa<MDCompileUnit>(*this)) &&
207          "Unhandled type of scope.");
208   return DIScopeRef(nullptr);
209 }
210
211 StringRef DIScope::getName() const {
212   if (DIType T = dyn_cast<MDType>(*this))
213     return T.getName();
214   if (DISubprogram SP = dyn_cast<MDSubprogram>(*this))
215     return SP.getName();
216   if (DINameSpace NS = dyn_cast<MDNamespace>(*this))
217     return NS.getName();
218   assert((isa<MDLexicalBlockBase>(*this) || isa<MDFile>(*this) ||
219           isa<MDCompileUnit>(*this)) &&
220          "Unhandled type of scope.");
221   return StringRef();
222 }
223
224 StringRef DIScope::getFilename() const {
225   if (auto *N = get())
226     if (auto *F = N->getFile())
227       return F->getFilename();
228   return "";
229 }
230
231 StringRef DIScope::getDirectory() const {
232   if (auto *N = get())
233     if (auto *F = N->getFile())
234       return F->getDirectory();
235   return "";
236 }
237
238 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
239   get()->replaceSubprograms(cast_or_null<MDTuple>(Subprograms.get()));
240 }
241
242 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
243   get()->replaceGlobalVariables(cast_or_null<MDTuple>(GlobalVariables.get()));
244 }
245
246 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
247                                         DILexicalBlockFile NewScope) {
248   assert(NewScope && "Expected valid scope");
249
250   const auto *Old = cast<MDLocation>(DbgNode);
251   return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
252                                     NewScope, Old->getInlinedAt()));
253 }
254
255 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
256   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
257   return ++Ctx.pImpl->DiscriminatorTable[Key];
258 }
259
260 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
261                                        LLVMContext &VMContext) {
262   return cast<MDLocalVariable>(DV)
263       ->withInline(cast_or_null<MDLocation>(InlinedScope));
264 }
265
266 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
267   return cast<MDLocalVariable>(DV)->withoutInline();
268 }
269
270 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
271   if (auto *LocalScope = dyn_cast_or_null<MDLocalScope>(Scope))
272     return LocalScope->getSubprogram();
273   return nullptr;
274 }
275
276 DISubprogram llvm::getDISubprogram(const Function *F) {
277   // We look for the first instr that has a debug annotation leading back to F.
278   for (auto &BB : *F) {
279     auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
280       return Inst.getDebugLoc();
281     });
282     if (Inst == BB.end())
283       continue;
284     DebugLoc DLoc = Inst->getDebugLoc();
285     const MDNode *Scope = DLoc.getInlinedAtScope();
286     DISubprogram Subprogram = getDISubprogram(Scope);
287     return Subprogram.describes(F) ? Subprogram : DISubprogram();
288   }
289
290   return DISubprogram();
291 }
292
293 DICompositeType llvm::getDICompositeType(DIType T) {
294   if (auto *C = dyn_cast_or_null<MDCompositeTypeBase>(T))
295     return C;
296
297   if (auto *D = dyn_cast_or_null<MDDerivedTypeBase>(T)) {
298     // This function is currently used by dragonegg and dragonegg does
299     // not generate identifier for types, so using an empty map to resolve
300     // DerivedFrom should be fine.
301     DITypeIdentifierMap EmptyMap;
302     return getDICompositeType(
303         DIDerivedType(D).getTypeDerivedFrom().resolve(EmptyMap));
304   }
305
306   return nullptr;
307 }
308
309 DITypeIdentifierMap
310 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
311   DITypeIdentifierMap Map;
312   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
313     DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(CUi));
314     DIArray Retain = CU.getRetainedTypes();
315     for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
316       if (!isa<MDCompositeType>(Retain.getElement(Ti)))
317         continue;
318       DICompositeType Ty = cast<MDCompositeType>(Retain.getElement(Ti));
319       if (MDString *TypeId = Ty.getIdentifier()) {
320         // Definition has priority over declaration.
321         // Try to insert (TypeId, Ty) to Map.
322         std::pair<DITypeIdentifierMap::iterator, bool> P =
323             Map.insert(std::make_pair(TypeId, Ty));
324         // If TypeId already exists in Map and this is a definition, replace
325         // whatever we had (declaration or definition) with the definition.
326         if (!P.second && !Ty.isForwardDecl())
327           P.first->second = Ty;
328       }
329     }
330   }
331   return Map;
332 }
333
334 //===----------------------------------------------------------------------===//
335 // DebugInfoFinder implementations.
336 //===----------------------------------------------------------------------===//
337
338 void DebugInfoFinder::reset() {
339   CUs.clear();
340   SPs.clear();
341   GVs.clear();
342   TYs.clear();
343   Scopes.clear();
344   NodesSeen.clear();
345   TypeIdentifierMap.clear();
346   TypeMapInitialized = false;
347 }
348
349 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
350   if (!TypeMapInitialized)
351     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
352       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
353       TypeMapInitialized = true;
354     }
355 }
356
357 void DebugInfoFinder::processModule(const Module &M) {
358   InitializeTypeMap(M);
359   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
360     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
361       DICompileUnit CU = cast<MDCompileUnit>(CU_Nodes->getOperand(i));
362       addCompileUnit(CU);
363       DIArray GVs = CU.getGlobalVariables();
364       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
365         DIGlobalVariable DIG = cast<MDGlobalVariable>(GVs.getElement(i));
366         if (addGlobalVariable(DIG)) {
367           processScope(DIG.getContext());
368           processType(DIG.getType().resolve(TypeIdentifierMap));
369         }
370       }
371       DIArray SPs = CU.getSubprograms();
372       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
373         processSubprogram(cast<MDSubprogram>(SPs.getElement(i)));
374       DIArray EnumTypes = CU.getEnumTypes();
375       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
376         processType(cast<MDType>(EnumTypes.getElement(i)));
377       DIArray RetainedTypes = CU.getRetainedTypes();
378       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
379         processType(cast<MDType>(RetainedTypes.getElement(i)));
380       DIArray Imports = CU.getImportedEntities();
381       for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
382         DIImportedEntity Import = cast<MDImportedEntity>(Imports.getElement(i));
383         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
384         if (auto *T = dyn_cast<MDType>(Entity))
385           processType(T);
386         else if (auto *SP = dyn_cast<MDSubprogram>(Entity))
387           processSubprogram(SP);
388         else if (auto *NS = dyn_cast<MDNamespace>(Entity))
389           processScope(NS->getScope());
390       }
391     }
392   }
393 }
394
395 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
396   if (!Loc)
397     return;
398   InitializeTypeMap(M);
399   processScope(Loc.getScope());
400   processLocation(M, Loc.getOrigLocation());
401 }
402
403 void DebugInfoFinder::processType(DIType DT) {
404   if (!addType(DT))
405     return;
406   processScope(DT.getContext().resolve(TypeIdentifierMap));
407   if (DICompositeType DCT = dyn_cast<MDCompositeTypeBase>(DT)) {
408     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
409     if (DISubroutineType ST = dyn_cast<MDSubroutineType>(DCT)) {
410       DITypeArray DTA = ST.getTypeArray();
411       for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
412         processType(DTA.getElement(i).resolve(TypeIdentifierMap));
413       return;
414     }
415     DIArray DA = DCT.getElements();
416     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
417       DIDescriptor D = DA.getElement(i);
418       if (DIType T = dyn_cast<MDType>(D))
419         processType(T);
420       else if (DISubprogram SP = dyn_cast<MDSubprogram>(D))
421         processSubprogram(SP);
422     }
423   } else if (DIDerivedType DDT = dyn_cast<MDDerivedTypeBase>(DT)) {
424     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
425   }
426 }
427
428 void DebugInfoFinder::processScope(DIScope Scope) {
429   if (!Scope)
430     return;
431   if (DIType Ty = dyn_cast<MDType>(Scope)) {
432     processType(Ty);
433     return;
434   }
435   if (DICompileUnit CU = dyn_cast<MDCompileUnit>(Scope)) {
436     addCompileUnit(CU);
437     return;
438   }
439   if (DISubprogram SP = dyn_cast<MDSubprogram>(Scope)) {
440     processSubprogram(SP);
441     return;
442   }
443   if (!addScope(Scope))
444     return;
445   if (DILexicalBlock LB = dyn_cast<MDLexicalBlockBase>(Scope)) {
446     processScope(LB.getContext());
447   } else if (DINameSpace NS = dyn_cast<MDNamespace>(Scope)) {
448     processScope(NS.getContext());
449   }
450 }
451
452 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
453   if (!addSubprogram(SP))
454     return;
455   processScope(SP.getContext().resolve(TypeIdentifierMap));
456   processType(SP.getType());
457   DIArray TParams = SP.getTemplateParams();
458   for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
459     DIDescriptor Element = TParams.getElement(I);
460     if (DITemplateTypeParameter TType =
461             dyn_cast<MDTemplateTypeParameter>(Element)) {
462       processType(TType.getType().resolve(TypeIdentifierMap));
463     } else if (DITemplateValueParameter TVal =
464                    dyn_cast<MDTemplateValueParameter>(Element)) {
465       processType(TVal.getType().resolve(TypeIdentifierMap));
466     }
467   }
468 }
469
470 void DebugInfoFinder::processDeclare(const Module &M,
471                                      const DbgDeclareInst *DDI) {
472   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
473   if (!N)
474     return;
475   InitializeTypeMap(M);
476
477   DIVariable DV = dyn_cast<MDLocalVariable>(N);
478   if (!DV)
479     return;
480
481   if (!NodesSeen.insert(DV).second)
482     return;
483   processScope(DV.getContext());
484   processType(DV.getType().resolve(TypeIdentifierMap));
485 }
486
487 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
488   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
489   if (!N)
490     return;
491   InitializeTypeMap(M);
492
493   DIVariable DV = dyn_cast<MDLocalVariable>(N);
494   if (!DV)
495     return;
496
497   if (!NodesSeen.insert(DV).second)
498     return;
499   processScope(DV.getContext());
500   processType(DV.getType().resolve(TypeIdentifierMap));
501 }
502
503 bool DebugInfoFinder::addType(DIType DT) {
504   if (!DT)
505     return false;
506
507   if (!NodesSeen.insert(DT).second)
508     return false;
509
510   TYs.push_back(DT);
511   return true;
512 }
513
514 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
515   if (!CU)
516     return false;
517   if (!NodesSeen.insert(CU).second)
518     return false;
519
520   CUs.push_back(CU);
521   return true;
522 }
523
524 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
525   if (!DIG)
526     return false;
527
528   if (!NodesSeen.insert(DIG).second)
529     return false;
530
531   GVs.push_back(DIG);
532   return true;
533 }
534
535 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
536   if (!SP)
537     return false;
538
539   if (!NodesSeen.insert(SP).second)
540     return false;
541
542   SPs.push_back(SP);
543   return true;
544 }
545
546 bool DebugInfoFinder::addScope(DIScope Scope) {
547   if (!Scope)
548     return false;
549   // FIXME: Ocaml binding generates a scope with no content, we treat it
550   // as null for now.
551   if (Scope->getNumOperands() == 0)
552     return false;
553   if (!NodesSeen.insert(Scope).second)
554     return false;
555   Scopes.push_back(Scope);
556   return true;
557 }
558
559 //===----------------------------------------------------------------------===//
560 // DIDescriptor: dump routines for all descriptors.
561 //===----------------------------------------------------------------------===//
562
563 void DIDescriptor::dump() const {
564   print(dbgs());
565   dbgs() << '\n';
566 }
567
568 void DIDescriptor::print(raw_ostream &OS) const {
569   if (!get())
570     return;
571   get()->print(OS);
572 }
573
574 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
575                           const LLVMContext &Ctx) {
576   if (!DL)
577     return;
578
579   DIScope Scope = cast<MDScope>(DL.getScope());
580   // Omit the directory, because it's likely to be long and uninteresting.
581   CommentOS << Scope.getFilename();
582   CommentOS << ':' << DL.getLine();
583   if (DL.getCol() != 0)
584     CommentOS << ':' << DL.getCol();
585
586   DebugLoc InlinedAtDL = DL.getInlinedAt();
587   if (!InlinedAtDL)
588     return;
589
590   CommentOS << " @[ ";
591   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
592   CommentOS << " ]";
593 }
594
595 void DIVariable::printExtendedName(raw_ostream &OS) const {
596   const LLVMContext &Ctx = DbgNode->getContext();
597   StringRef Res = getName();
598   if (!Res.empty())
599     OS << Res << "," << getLineNumber();
600   if (auto *InlinedAt = get()->getInlinedAt()) {
601     if (DebugLoc InlinedAtDL = InlinedAt) {
602       OS << " @[";
603       printDebugLoc(InlinedAtDL, OS, Ctx);
604       OS << "]";
605     }
606   }
607 }
608
609 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V) : Val(V) {
610   assert(isDescriptorRef(V) &&
611          "DIDescriptorRef should be a MDString or MDNode");
612 }
613 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
614   assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
615 }
616 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
617   assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
618 }
619
620 template <>
621 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const {
622   return DIDescriptorRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
623 }
624 template <>
625 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
626   return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
627 }
628 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
629   return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
630 }
631
632 template <>
633 DIDescriptor
634 DIRef<DIDescriptor>::resolve(const DITypeIdentifierMap &Map) const {
635   return DIDescriptor(DebugNodeRef(Val).resolve(Map));
636 }
637 template <>
638 DIScope DIRef<DIScope>::resolve(const DITypeIdentifierMap &Map) const {
639   return MDScopeRef(Val).resolve(Map);
640 }
641 template <>
642 DIType DIRef<DIType>::resolve(const DITypeIdentifierMap &Map) const {
643   return MDTypeRef(Val).resolve(Map);
644 }
645
646 bool llvm::stripDebugInfo(Function &F) {
647   bool Changed = false;
648   for (BasicBlock &BB : F) {
649     for (Instruction &I : BB) {
650       if (I.getDebugLoc()) {
651         Changed = true;
652         I.setDebugLoc(DebugLoc());
653       }
654     }
655   }
656   return Changed;
657 }
658
659 bool llvm::StripDebugInfo(Module &M) {
660   bool Changed = false;
661
662   // Remove all of the calls to the debugger intrinsics, and remove them from
663   // the module.
664   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
665     while (!Declare->use_empty()) {
666       CallInst *CI = cast<CallInst>(Declare->user_back());
667       CI->eraseFromParent();
668     }
669     Declare->eraseFromParent();
670     Changed = true;
671   }
672
673   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
674     while (!DbgVal->use_empty()) {
675       CallInst *CI = cast<CallInst>(DbgVal->user_back());
676       CI->eraseFromParent();
677     }
678     DbgVal->eraseFromParent();
679     Changed = true;
680   }
681
682   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
683          NME = M.named_metadata_end(); NMI != NME;) {
684     NamedMDNode *NMD = NMI;
685     ++NMI;
686     if (NMD->getName().startswith("llvm.dbg.")) {
687       NMD->eraseFromParent();
688       Changed = true;
689     }
690   }
691
692   for (Function &F : M)
693     Changed |= stripDebugInfo(F);
694
695   if (GVMaterializer *Materializer = M.getMaterializer())
696     Materializer->setStripDebugInfo();
697
698   return Changed;
699 }
700
701 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
702   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
703           M.getModuleFlag("Debug Info Version")))
704     return Val->getZExtValue();
705   return 0;
706 }
707
708 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
709 llvm::makeSubprogramMap(const Module &M) {
710   DenseMap<const Function *, DISubprogram> R;
711
712   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
713   if (!CU_Nodes)
714     return R;
715
716   for (MDNode *N : CU_Nodes->operands()) {
717     DICompileUnit CUNode = cast<MDCompileUnit>(N);
718     DIArray SPs = CUNode.getSubprograms();
719     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
720       DISubprogram SP = cast<MDSubprogram>(SPs.getElement(i));
721       if (Function *F = SP.getFunction())
722         R.insert(std::make_pair(F, SP));
723     }
724   }
725   return R;
726 }