DebugInfo: Hide isScopeRef() and isTypeRef() behind NDEBUG
[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/ADT/StringSwitch.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DIBuilder.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/GVMaterializer.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/Dwarf.h"
33 #include "llvm/Support/raw_ostream.h"
34 using namespace llvm;
35 using namespace llvm::dwarf;
36
37 //===----------------------------------------------------------------------===//
38 // DIDescriptor
39 //===----------------------------------------------------------------------===//
40
41 unsigned DIDescriptor::getFlag(StringRef Flag) {
42   return StringSwitch<unsigned>(Flag)
43 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
44 #include "llvm/IR/DebugInfoFlags.def"
45       .Default(0);
46 }
47
48 const char *DIDescriptor::getFlagString(unsigned Flag) {
49   switch (Flag) {
50   default:
51     return "";
52 #define HANDLE_DI_FLAG(ID, NAME)                                               \
53   case Flag##NAME:                                                             \
54     return "DIFlag" #NAME;
55 #include "llvm/IR/DebugInfoFlags.def"
56   }
57 }
58
59 unsigned DIDescriptor::splitFlags(unsigned Flags,
60                                   SmallVectorImpl<unsigned> &SplitFlags) {
61   // Accessibility flags need to be specially handled, since they're packed
62   // together.
63   if (unsigned A = Flags & FlagAccessibility) {
64     if (A == FlagPrivate)
65       SplitFlags.push_back(FlagPrivate);
66     else if (A == FlagProtected)
67       SplitFlags.push_back(FlagProtected);
68     else
69       SplitFlags.push_back(FlagPublic);
70     Flags &= ~A;
71   }
72
73 #define HANDLE_DI_FLAG(ID, NAME)                                               \
74   if (unsigned Bit = Flags & ID) {                                             \
75     SplitFlags.push_back(Bit);                                                 \
76     Flags &= ~Bit;                                                             \
77   }
78 #include "llvm/IR/DebugInfoFlags.def"
79
80   return Flags;
81 }
82
83 bool DIDescriptor::Verify() const {
84   return DbgNode &&
85          (DIDerivedType(DbgNode).Verify() ||
86           DICompositeType(DbgNode).Verify() || DIBasicType(DbgNode).Verify() ||
87           DIVariable(DbgNode).Verify() || DISubprogram(DbgNode).Verify() ||
88           DIGlobalVariable(DbgNode).Verify() || DIFile(DbgNode).Verify() ||
89           DICompileUnit(DbgNode).Verify() || DINameSpace(DbgNode).Verify() ||
90           DILexicalBlock(DbgNode).Verify() ||
91           DILexicalBlockFile(DbgNode).Verify() ||
92           DISubrange(DbgNode).Verify() || DIEnumerator(DbgNode).Verify() ||
93           DIObjCProperty(DbgNode).Verify() ||
94           DITemplateTypeParameter(DbgNode).Verify() ||
95           DITemplateValueParameter(DbgNode).Verify() ||
96           DIImportedEntity(DbgNode).Verify());
97 }
98
99 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
100   if (!DbgNode || Elt >= DbgNode->getNumOperands())
101     return nullptr;
102   return DbgNode->getOperand(Elt);
103 }
104
105 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
106   return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
107 }
108
109 static StringRef getStringField(const MDNode *DbgNode, unsigned Elt) {
110   if (MDString *MDS = dyn_cast_or_null<MDString>(getField(DbgNode, Elt)))
111     return MDS->getString();
112   return StringRef();
113 }
114
115 StringRef DIDescriptor::getStringField(unsigned Elt) const {
116   return ::getStringField(DbgNode, Elt);
117 }
118
119 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
120   if (auto *C = getConstantField(Elt))
121     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
122       return CI->getZExtValue();
123
124   return 0;
125 }
126
127 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
128   if (auto *C = getConstantField(Elt))
129     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
130       return CI->getZExtValue();
131
132   return 0;
133 }
134
135 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
136   MDNode *Field = getNodeField(DbgNode, Elt);
137   return DIDescriptor(Field);
138 }
139
140 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
141   return dyn_cast_or_null<GlobalVariable>(getConstantField(Elt));
142 }
143
144 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
145   if (!DbgNode)
146     return nullptr;
147
148   if (Elt < DbgNode->getNumOperands())
149     if (auto *C =
150             dyn_cast_or_null<ConstantAsMetadata>(DbgNode->getOperand(Elt)))
151       return C->getValue();
152   return nullptr;
153 }
154
155 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
156   return dyn_cast_or_null<Function>(getConstantField(Elt));
157 }
158
159 /// \brief Return the size reported by the variable's type.
160 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
161   DIType Ty = getType().resolve(Map);
162   // Follow derived types until we reach a type that
163   // reports back a size.
164   while (Ty.isDerivedType() && !Ty.getSizeInBits()) {
165     DIDerivedType DT(&*Ty);
166     Ty = DT.getTypeDerivedFrom().resolve(Map);
167   }
168   assert(Ty.getSizeInBits() && "type with size 0");
169   return Ty.getSizeInBits();
170 }
171
172 bool DIExpression::isBitPiece() const {
173   unsigned N = getNumElements();
174   return N >=3 && getElement(N-3) == dwarf::DW_OP_bit_piece;
175 }
176
177 uint64_t DIExpression::getBitPieceOffset() const {
178   assert(isBitPiece() && "not a piece");
179   return getElement(getNumElements()-2);
180 }
181
182 uint64_t DIExpression::getBitPieceSize() const {
183   assert(isBitPiece() && "not a piece");
184   return getElement(getNumElements()-1);
185 }
186
187 DIExpression::iterator DIExpression::Operand::getNext() const {
188   iterator it(I);
189   return ++it;
190 }
191
192 //===----------------------------------------------------------------------===//
193 // Simple Descriptor Constructors and other Methods
194 //===----------------------------------------------------------------------===//
195
196 void DIDescriptor::replaceAllUsesWith(LLVMContext &, DIDescriptor D) {
197   assert(DbgNode && "Trying to replace an unverified type!");
198   assert(DbgNode->isTemporary() && "Expected temporary node");
199   TempMDNode Temp(get());
200
201   // Since we use a TrackingVH for the node, its easy for clients to manufacture
202   // legitimate situations where they want to replaceAllUsesWith() on something
203   // which, due to uniquing, has merged with the source. We shield clients from
204   // this detail by allowing a value to be replaced with replaceAllUsesWith()
205   // itself.
206   if (Temp.get() == D.get()) {
207     DbgNode = MDNode::replaceWithUniqued(std::move(Temp));
208     return;
209   }
210
211   Temp->replaceAllUsesWith(D.get());
212   DbgNode = D.get();
213 }
214
215 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
216   assert(DbgNode && "Trying to replace an unverified type!");
217   assert(DbgNode != D && "This replacement should always happen");
218   assert(DbgNode->isTemporary() && "Expected temporary node");
219   TempMDNode Node(get());
220   Node->replaceAllUsesWith(D);
221 }
222
223 bool DICompileUnit::Verify() const { return isCompileUnit(); }
224 bool DIObjCProperty::Verify() const { return isObjCProperty(); }
225
226 #ifndef NDEBUG
227 /// \brief Check if a value can be a reference to a type.
228 static bool isTypeRef(const Metadata *MD) {
229   if (!MD)
230     return true;
231   if (auto *S = dyn_cast<MDString>(MD))
232     return !S->getString().empty();
233   return isa<MDType>(MD);
234 }
235
236 /// \brief Check if a value can be a ScopeRef.
237 static bool isScopeRef(const Metadata *MD) {
238   if (!MD)
239     return true;
240   if (auto *S = dyn_cast<MDString>(MD))
241     return !S->getString().empty();
242   return isa<MDScope>(MD);
243 }
244
245 /// \brief Check if a value can be a DescriptorRef.
246 static bool isDescriptorRef(const Metadata *MD) {
247   if (!MD)
248     return true;
249   if (auto *S = dyn_cast<MDString>(MD))
250     return !S->getString().empty();
251   return isa<MDNode>(MD);
252 }
253 #endif
254
255 bool DIType::Verify() const { return isType(); }
256 bool DIBasicType::Verify() const { return isBasicType(); }
257 bool DIDerivedType::Verify() const { return isDerivedType(); }
258 bool DICompositeType::Verify() const { return isCompositeType(); }
259
260 bool DISubprogram::Verify() const {
261   auto *N = dyn_cast_or_null<MDSubprogram>(DbgNode);
262   if (!N)
263     return false;
264
265   // If a DISubprogram has an llvm::Function*, then scope chains from all
266   // instructions within the function should lead to this DISubprogram.
267   if (auto *F = getFunction()) {
268     for (auto &BB : *F) {
269       for (auto &I : BB) {
270         MDLocation *DL = I.getDebugLoc();
271         if (!DL)
272           continue;
273
274         // walk the inlined-at scopes
275         MDScope *Scope = DL->getInlinedAtScope();
276         if (!Scope)
277           return false;
278         while (!isa<MDSubprogram>(Scope)) {
279           Scope = cast<MDLexicalBlockBase>(Scope)->getScope();
280           if (!Scope)
281             return false;
282         }
283         if (!DISubprogram(Scope).describes(F))
284           return false;
285       }
286     }
287   }
288
289   return true;
290 }
291
292 bool DIGlobalVariable::Verify() const { return isGlobalVariable(); }
293 bool DIVariable::Verify() const { return isVariable(); }
294
295 bool DILocation::Verify() const {
296   return dyn_cast_or_null<MDLocation>(DbgNode);
297 }
298 bool DINameSpace::Verify() const {
299   return dyn_cast_or_null<MDNamespace>(DbgNode);
300 }
301 bool DIFile::Verify() const { return dyn_cast_or_null<MDFile>(DbgNode); }
302 bool DIEnumerator::Verify() const {
303   return dyn_cast_or_null<MDEnumerator>(DbgNode);
304 }
305 bool DISubrange::Verify() const {
306   return dyn_cast_or_null<MDSubrange>(DbgNode);
307 }
308 bool DILexicalBlock::Verify() const {
309   return dyn_cast_or_null<MDLexicalBlock>(DbgNode);
310 }
311 bool DILexicalBlockFile::Verify() const {
312   return dyn_cast_or_null<MDLexicalBlockFile>(DbgNode);
313 }
314 bool DITemplateTypeParameter::Verify() const {
315   return dyn_cast_or_null<MDTemplateTypeParameter>(DbgNode);
316 }
317 bool DITemplateValueParameter::Verify() const {
318   return dyn_cast_or_null<MDTemplateValueParameter>(DbgNode);
319 }
320 bool DIImportedEntity::Verify() const {
321   return dyn_cast_or_null<MDImportedEntity>(DbgNode);
322 }
323
324 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
325   TypedTrackingMDRef<MDCompositeTypeBase> N(get());
326   if (Elements)
327     N->replaceElements(cast<MDTuple>(Elements));
328   if (TParams)
329     N->replaceTemplateParams(cast<MDTuple>(TParams));
330   DbgNode = N;
331 }
332
333 DIScopeRef DIScope::getRef() const {
334   if (!isCompositeType())
335     return DIScopeRef(*this);
336   DICompositeType DTy(DbgNode);
337   if (!DTy.getIdentifier())
338     return DIScopeRef(*this);
339   return DIScopeRef(DTy.getIdentifier());
340 }
341
342 void DICompositeType::setContainingType(DICompositeType ContainingType) {
343   TypedTrackingMDRef<MDCompositeTypeBase> N(get());
344   N->replaceVTableHolder(ContainingType.getRef());
345   DbgNode = N;
346 }
347
348 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
349   assert(CurFn && "Invalid function");
350   if (!getContext().isSubprogram())
351     return false;
352   // This variable is not inlined function argument if its scope
353   // does not describe current function.
354   return !DISubprogram(getContext()).describes(CurFn);
355 }
356
357 Function *DISubprogram::getFunction() const {
358   if (auto *N = get())
359     if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
360       return dyn_cast<Function>(C->getValue());
361   return nullptr;
362 }
363
364 bool DISubprogram::describes(const Function *F) {
365   assert(F && "Invalid function");
366   if (F == getFunction())
367     return true;
368   StringRef Name = getLinkageName();
369   if (Name.empty())
370     Name = getName();
371   if (F->getName() == Name)
372     return true;
373   return false;
374 }
375
376 GlobalVariable *DIGlobalVariable::getGlobal() const {
377   return dyn_cast_or_null<GlobalVariable>(getConstant());
378 }
379
380 DIScopeRef DIScope::getContext() const {
381
382   if (isType())
383     return DIType(DbgNode).getContext();
384
385   if (isSubprogram())
386     return DIScopeRef(DISubprogram(DbgNode).getContext());
387
388   if (isLexicalBlock())
389     return DIScopeRef(DILexicalBlock(DbgNode).getContext());
390
391   if (isLexicalBlockFile())
392     return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
393
394   if (isNameSpace())
395     return DIScopeRef(DINameSpace(DbgNode).getContext());
396
397   assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
398   return DIScopeRef(nullptr);
399 }
400
401 StringRef DIScope::getName() const {
402   if (isType())
403     return DIType(DbgNode).getName();
404   if (isSubprogram())
405     return DISubprogram(DbgNode).getName();
406   if (isNameSpace())
407     return DINameSpace(DbgNode).getName();
408   assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
409           isCompileUnit()) &&
410          "Unhandled type of scope.");
411   return StringRef();
412 }
413
414 StringRef DIScope::getFilename() const {
415   if (auto *N = get())
416     return ::getStringField(dyn_cast_or_null<MDNode>(N->getFile()), 0);
417   return "";
418 }
419
420 StringRef DIScope::getDirectory() const {
421   if (auto *N = get())
422     return ::getStringField(dyn_cast_or_null<MDNode>(N->getFile()), 1);
423   return "";
424 }
425
426 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
427   assert(Verify() && "Expected compile unit");
428   get()->replaceSubprograms(cast_or_null<MDTuple>(Subprograms.get()));
429 }
430
431 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
432   assert(Verify() && "Expected compile unit");
433   get()->replaceGlobalVariables(cast_or_null<MDTuple>(GlobalVariables.get()));
434 }
435
436 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
437                                         DILexicalBlockFile NewScope) {
438   assert(Verify());
439   assert(NewScope && "Expected valid scope");
440
441   const auto *Old = cast<MDLocation>(DbgNode);
442   return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
443                                     NewScope, Old->getInlinedAt()));
444 }
445
446 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
447   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
448   return ++Ctx.pImpl->DiscriminatorTable[Key];
449 }
450
451 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
452                                        LLVMContext &VMContext) {
453   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
454   return cast<MDLocalVariable>(DV)
455       ->withInline(cast_or_null<MDLocation>(InlinedScope));
456 }
457
458 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
459   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
460   return cast<MDLocalVariable>(DV)->withoutInline();
461 }
462
463 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
464   DIDescriptor D(Scope);
465   if (D.isSubprogram())
466     return DISubprogram(Scope);
467
468   if (D.isLexicalBlockFile())
469     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
470
471   if (D.isLexicalBlock())
472     return getDISubprogram(DILexicalBlock(Scope).getContext());
473
474   return DISubprogram();
475 }
476
477 DISubprogram llvm::getDISubprogram(const Function *F) {
478   // We look for the first instr that has a debug annotation leading back to F.
479   for (auto &BB : *F) {
480     auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
481       return Inst.getDebugLoc();
482     });
483     if (Inst == BB.end())
484       continue;
485     DebugLoc DLoc = Inst->getDebugLoc();
486     const MDNode *Scope = DLoc.getInlinedAtScope();
487     DISubprogram Subprogram = getDISubprogram(Scope);
488     return Subprogram.describes(F) ? Subprogram : DISubprogram();
489   }
490
491   return DISubprogram();
492 }
493
494 DICompositeType llvm::getDICompositeType(DIType T) {
495   if (T.isCompositeType())
496     return DICompositeType(T);
497
498   if (T.isDerivedType()) {
499     // This function is currently used by dragonegg and dragonegg does
500     // not generate identifier for types, so using an empty map to resolve
501     // DerivedFrom should be fine.
502     DITypeIdentifierMap EmptyMap;
503     return getDICompositeType(
504         DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
505   }
506
507   return DICompositeType();
508 }
509
510 DITypeIdentifierMap
511 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
512   DITypeIdentifierMap Map;
513   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
514     DICompileUnit CU(CU_Nodes->getOperand(CUi));
515     DIArray Retain = CU.getRetainedTypes();
516     for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
517       if (!Retain.getElement(Ti).isCompositeType())
518         continue;
519       DICompositeType Ty(Retain.getElement(Ti));
520       if (MDString *TypeId = Ty.getIdentifier()) {
521         // Definition has priority over declaration.
522         // Try to insert (TypeId, Ty) to Map.
523         std::pair<DITypeIdentifierMap::iterator, bool> P =
524             Map.insert(std::make_pair(TypeId, Ty));
525         // If TypeId already exists in Map and this is a definition, replace
526         // whatever we had (declaration or definition) with the definition.
527         if (!P.second && !Ty.isForwardDecl())
528           P.first->second = Ty;
529       }
530     }
531   }
532   return Map;
533 }
534
535 //===----------------------------------------------------------------------===//
536 // DebugInfoFinder implementations.
537 //===----------------------------------------------------------------------===//
538
539 void DebugInfoFinder::reset() {
540   CUs.clear();
541   SPs.clear();
542   GVs.clear();
543   TYs.clear();
544   Scopes.clear();
545   NodesSeen.clear();
546   TypeIdentifierMap.clear();
547   TypeMapInitialized = false;
548 }
549
550 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
551   if (!TypeMapInitialized)
552     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
553       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
554       TypeMapInitialized = true;
555     }
556 }
557
558 void DebugInfoFinder::processModule(const Module &M) {
559   InitializeTypeMap(M);
560   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
561     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
562       DICompileUnit CU(CU_Nodes->getOperand(i));
563       addCompileUnit(CU);
564       DIArray GVs = CU.getGlobalVariables();
565       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
566         DIGlobalVariable DIG(GVs.getElement(i));
567         if (addGlobalVariable(DIG)) {
568           processScope(DIG.getContext());
569           processType(DIG.getType().resolve(TypeIdentifierMap));
570         }
571       }
572       DIArray SPs = CU.getSubprograms();
573       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
574         processSubprogram(DISubprogram(SPs.getElement(i)));
575       DIArray EnumTypes = CU.getEnumTypes();
576       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
577         processType(DIType(EnumTypes.getElement(i)));
578       DIArray RetainedTypes = CU.getRetainedTypes();
579       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
580         processType(DIType(RetainedTypes.getElement(i)));
581       DIArray Imports = CU.getImportedEntities();
582       for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
583         DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
584         if (!Import)
585           continue;
586         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
587         if (Entity.isType())
588           processType(DIType(Entity));
589         else if (Entity.isSubprogram())
590           processSubprogram(DISubprogram(Entity));
591         else if (Entity.isNameSpace())
592           processScope(DINameSpace(Entity).getContext());
593       }
594     }
595   }
596 }
597
598 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
599   if (!Loc)
600     return;
601   InitializeTypeMap(M);
602   processScope(Loc.getScope());
603   processLocation(M, Loc.getOrigLocation());
604 }
605
606 void DebugInfoFinder::processType(DIType DT) {
607   if (!addType(DT))
608     return;
609   processScope(DT.getContext().resolve(TypeIdentifierMap));
610   if (DT.isCompositeType()) {
611     DICompositeType DCT(DT);
612     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
613     if (DT.isSubroutineType()) {
614       DITypeArray DTA = DISubroutineType(DT).getTypeArray();
615       for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
616         processType(DTA.getElement(i).resolve(TypeIdentifierMap));
617       return;
618     }
619     DIArray DA = DCT.getElements();
620     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
621       DIDescriptor D = DA.getElement(i);
622       if (D.isType())
623         processType(DIType(D));
624       else if (D.isSubprogram())
625         processSubprogram(DISubprogram(D));
626     }
627   } else if (DT.isDerivedType()) {
628     DIDerivedType DDT(DT);
629     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
630   }
631 }
632
633 void DebugInfoFinder::processScope(DIScope Scope) {
634   if (Scope.isType()) {
635     DIType Ty(Scope);
636     processType(Ty);
637     return;
638   }
639   if (Scope.isCompileUnit()) {
640     addCompileUnit(DICompileUnit(Scope));
641     return;
642   }
643   if (Scope.isSubprogram()) {
644     processSubprogram(DISubprogram(Scope));
645     return;
646   }
647   if (!addScope(Scope))
648     return;
649   if (Scope.isLexicalBlock()) {
650     DILexicalBlock LB(Scope);
651     processScope(LB.getContext());
652   } else if (Scope.isLexicalBlockFile()) {
653     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
654     processScope(LBF.getScope());
655   } else if (Scope.isNameSpace()) {
656     DINameSpace NS(Scope);
657     processScope(NS.getContext());
658   }
659 }
660
661 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
662   if (!addSubprogram(SP))
663     return;
664   processScope(SP.getContext().resolve(TypeIdentifierMap));
665   processType(SP.getType());
666   DIArray TParams = SP.getTemplateParams();
667   for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
668     DIDescriptor Element = TParams.getElement(I);
669     if (Element.isTemplateTypeParameter()) {
670       DITemplateTypeParameter TType(Element);
671       processType(TType.getType().resolve(TypeIdentifierMap));
672     } else if (Element.isTemplateValueParameter()) {
673       DITemplateValueParameter TVal(Element);
674       processType(TVal.getType().resolve(TypeIdentifierMap));
675     }
676   }
677 }
678
679 void DebugInfoFinder::processDeclare(const Module &M,
680                                      const DbgDeclareInst *DDI) {
681   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
682   if (!N)
683     return;
684   InitializeTypeMap(M);
685
686   DIDescriptor DV(N);
687   if (!DV.isVariable())
688     return;
689
690   if (!NodesSeen.insert(DV).second)
691     return;
692   processScope(DIVariable(N).getContext());
693   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
694 }
695
696 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
697   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
698   if (!N)
699     return;
700   InitializeTypeMap(M);
701
702   DIDescriptor DV(N);
703   if (!DV.isVariable())
704     return;
705
706   if (!NodesSeen.insert(DV).second)
707     return;
708   processScope(DIVariable(N).getContext());
709   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
710 }
711
712 bool DebugInfoFinder::addType(DIType DT) {
713   if (!DT)
714     return false;
715
716   if (!NodesSeen.insert(DT).second)
717     return false;
718
719   TYs.push_back(DT);
720   return true;
721 }
722
723 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
724   if (!CU)
725     return false;
726   if (!NodesSeen.insert(CU).second)
727     return false;
728
729   CUs.push_back(CU);
730   return true;
731 }
732
733 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
734   if (!DIG)
735     return false;
736
737   if (!NodesSeen.insert(DIG).second)
738     return false;
739
740   GVs.push_back(DIG);
741   return true;
742 }
743
744 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
745   if (!SP)
746     return false;
747
748   if (!NodesSeen.insert(SP).second)
749     return false;
750
751   SPs.push_back(SP);
752   return true;
753 }
754
755 bool DebugInfoFinder::addScope(DIScope Scope) {
756   if (!Scope)
757     return false;
758   // FIXME: Ocaml binding generates a scope with no content, we treat it
759   // as null for now.
760   if (Scope->getNumOperands() == 0)
761     return false;
762   if (!NodesSeen.insert(Scope).second)
763     return false;
764   Scopes.push_back(Scope);
765   return true;
766 }
767
768 //===----------------------------------------------------------------------===//
769 // DIDescriptor: dump routines for all descriptors.
770 //===----------------------------------------------------------------------===//
771
772 void DIDescriptor::dump() const {
773   print(dbgs());
774   dbgs() << '\n';
775 }
776
777 void DIDescriptor::print(raw_ostream &OS) const {
778   if (!get())
779     return;
780   get()->print(OS);
781 }
782
783 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
784                           const LLVMContext &Ctx) {
785   if (!DL)
786     return;
787
788   DIScope Scope(DL.getScope());
789   assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
790   // Omit the directory, because it's likely to be long and uninteresting.
791   CommentOS << Scope.getFilename();
792   CommentOS << ':' << DL.getLine();
793   if (DL.getCol() != 0)
794     CommentOS << ':' << DL.getCol();
795
796   DebugLoc InlinedAtDL = DL.getInlinedAt();
797   if (!InlinedAtDL)
798     return;
799
800   CommentOS << " @[ ";
801   printDebugLoc(InlinedAtDL, CommentOS, Ctx);
802   CommentOS << " ]";
803 }
804
805 void DIVariable::printExtendedName(raw_ostream &OS) const {
806   const LLVMContext &Ctx = DbgNode->getContext();
807   StringRef Res = getName();
808   if (!Res.empty())
809     OS << Res << "," << getLineNumber();
810   if (auto *InlinedAt = get()->getInlinedAt()) {
811     if (DebugLoc InlinedAtDL = InlinedAt) {
812       OS << " @[";
813       printDebugLoc(InlinedAtDL, OS, Ctx);
814       OS << "]";
815     }
816   }
817 }
818
819 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V) : Val(V) {
820   assert(isDescriptorRef(V) &&
821          "DIDescriptorRef should be a MDString or MDNode");
822 }
823 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
824   assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
825 }
826 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
827   assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
828 }
829
830 template <>
831 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const {
832   return DIDescriptorRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
833 }
834 template <>
835 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
836   return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
837 }
838 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
839   return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
840 }
841
842 bool llvm::stripDebugInfo(Function &F) {
843   bool Changed = false;
844   for (BasicBlock &BB : F) {
845     for (Instruction &I : BB) {
846       if (I.getDebugLoc()) {
847         Changed = true;
848         I.setDebugLoc(DebugLoc());
849       }
850     }
851   }
852   return Changed;
853 }
854
855 bool llvm::StripDebugInfo(Module &M) {
856   bool Changed = false;
857
858   // Remove all of the calls to the debugger intrinsics, and remove them from
859   // the module.
860   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
861     while (!Declare->use_empty()) {
862       CallInst *CI = cast<CallInst>(Declare->user_back());
863       CI->eraseFromParent();
864     }
865     Declare->eraseFromParent();
866     Changed = true;
867   }
868
869   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
870     while (!DbgVal->use_empty()) {
871       CallInst *CI = cast<CallInst>(DbgVal->user_back());
872       CI->eraseFromParent();
873     }
874     DbgVal->eraseFromParent();
875     Changed = true;
876   }
877
878   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
879          NME = M.named_metadata_end(); NMI != NME;) {
880     NamedMDNode *NMD = NMI;
881     ++NMI;
882     if (NMD->getName().startswith("llvm.dbg.")) {
883       NMD->eraseFromParent();
884       Changed = true;
885     }
886   }
887
888   for (Function &F : M)
889     Changed |= stripDebugInfo(F);
890
891   if ( GVMaterializer *Materializer = M.getMaterializer())
892     Materializer->setStripDebugInfo();
893
894   return Changed;
895 }
896
897 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
898   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
899           M.getModuleFlag("Debug Info Version")))
900     return Val->getZExtValue();
901   return 0;
902 }
903
904 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
905 llvm::makeSubprogramMap(const Module &M) {
906   DenseMap<const Function *, DISubprogram> R;
907
908   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
909   if (!CU_Nodes)
910     return R;
911
912   for (MDNode *N : CU_Nodes->operands()) {
913     DICompileUnit CUNode(N);
914     DIArray SPs = CUNode.getSubprograms();
915     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
916       DISubprogram SP(SPs.getElement(i));
917       if (Function *F = SP.getFunction())
918         R.insert(std::make_pair(F, SP));
919     }
920   }
921   return R;
922 }