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