]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/IR/DebugInfo.cpp
Make DIExpression::Verify() stricter by checking that the number of
[opencl/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 //===----------------------------------------------------------------------===//
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/Module.h"
28 #include "llvm/IR/ValueHandle.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm;
33 using namespace llvm::dwarf;
35 //===----------------------------------------------------------------------===//
36 // DIDescriptor
37 //===----------------------------------------------------------------------===//
39 bool DIDescriptor::Verify() const {
40   return DbgNode &&
41          (DIDerivedType(DbgNode).Verify() ||
42           DICompositeType(DbgNode).Verify() || DIBasicType(DbgNode).Verify() ||
43           DIVariable(DbgNode).Verify() || DISubprogram(DbgNode).Verify() ||
44           DIGlobalVariable(DbgNode).Verify() || DIFile(DbgNode).Verify() ||
45           DICompileUnit(DbgNode).Verify() || DINameSpace(DbgNode).Verify() ||
46           DILexicalBlock(DbgNode).Verify() ||
47           DILexicalBlockFile(DbgNode).Verify() ||
48           DISubrange(DbgNode).Verify() || DIEnumerator(DbgNode).Verify() ||
49           DIObjCProperty(DbgNode).Verify() ||
50           DITemplateTypeParameter(DbgNode).Verify() ||
51           DITemplateValueParameter(DbgNode).Verify() ||
52           DIImportedEntity(DbgNode).Verify() || DIExpression(DbgNode).Verify());
53 }
55 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
56   if (!DbgNode || Elt >= DbgNode->getNumOperands())
57     return nullptr;
58   return DbgNode->getOperand(Elt);
59 }
61 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
62   return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
63 }
65 static StringRef getStringField(const MDNode *DbgNode, unsigned Elt) {
66   if (MDString *MDS = dyn_cast_or_null<MDString>(getField(DbgNode, Elt)))
67     return MDS->getString();
68   return StringRef();
69 }
71 StringRef DIDescriptor::getStringField(unsigned Elt) const {
72   return ::getStringField(DbgNode, Elt);
73 }
75 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
76   if (auto *C = getConstantField(Elt))
77     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
78       return CI->getZExtValue();
80   return 0;
81 }
83 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
84   if (auto *C = getConstantField(Elt))
85     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
86       return CI->getZExtValue();
88   return 0;
89 }
91 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
92   MDNode *Field = getNodeField(DbgNode, Elt);
93   return DIDescriptor(Field);
94 }
96 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
97   return dyn_cast_or_null<GlobalVariable>(getConstantField(Elt));
98 }
100 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
101   if (!DbgNode)
102     return nullptr;
104   if (Elt < DbgNode->getNumOperands())
105     if (auto *C =
106             dyn_cast_or_null<ConstantAsMetadata>(DbgNode->getOperand(Elt)))
107       return C->getValue();
108   return nullptr;
111 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
112   return dyn_cast_or_null<Function>(getConstantField(Elt));
115 void DIDescriptor::replaceFunctionField(unsigned Elt, Function *F) {
116   if (!DbgNode)
117     return;
119   if (Elt < DbgNode->getNumOperands()) {
120     MDNode *Node = const_cast<MDNode *>(DbgNode);
121     Node->replaceOperandWith(Elt, F ? ConstantAsMetadata::get(F) : nullptr);
122   }
125 static unsigned DIVariableInlinedAtIndex = 4;
126 MDNode *DIVariable::getInlinedAt() const {
127   return getNodeField(DbgNode, DIVariableInlinedAtIndex);
130 /// \brief Return the size reported by the variable's type.
131 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
132   DIType Ty = getType().resolve(Map);
133   // Follow derived types until we reach a type that
134   // reports back a size.
135   while (Ty.isDerivedType() && !Ty.getSizeInBits()) {
136     DIDerivedType DT(&*Ty);
137     Ty = DT.getTypeDerivedFrom().resolve(Map);
138   }
139   assert(Ty.getSizeInBits() && "type with size 0");
140   return Ty.getSizeInBits();
143 uint64_t DIExpression::getElement(unsigned Idx) const {
144   unsigned I = Idx + 1;
145   assert(I < getNumHeaderFields() &&
146          "non-existing complex address element requested");
147   return getHeaderFieldAs<int64_t>(I);
150 bool DIExpression::isVariablePiece() const {
151   unsigned N = getNumElements();
152   return N >=3 && getElement(N-3) == dwarf::DW_OP_piece;
155 uint64_t DIExpression::getPieceOffset() const {
156   assert(isVariablePiece() && "not a piece");
157   return getElement(getNumElements()-2);
160 uint64_t DIExpression::getPieceSize() const {
161   assert(isVariablePiece() && "not a piece");
162   return getElement(getNumElements()-1);
165 //===----------------------------------------------------------------------===//
166 // Predicates
167 //===----------------------------------------------------------------------===//
169 bool DIDescriptor::isSubroutineType() const {
170   return DbgNode && getTag() == dwarf::DW_TAG_subroutine_type;
173 bool DIDescriptor::isBasicType() const {
174   if (!DbgNode)
175     return false;
176   switch (getTag()) {
177   case dwarf::DW_TAG_base_type:
178   case dwarf::DW_TAG_unspecified_type:
179     return true;
180   default:
181     return false;
182   }
185 bool DIDescriptor::isDerivedType() const {
186   if (!DbgNode)
187     return false;
188   switch (getTag()) {
189   case dwarf::DW_TAG_typedef:
190   case dwarf::DW_TAG_pointer_type:
191   case dwarf::DW_TAG_ptr_to_member_type:
192   case dwarf::DW_TAG_reference_type:
193   case dwarf::DW_TAG_rvalue_reference_type:
194   case dwarf::DW_TAG_const_type:
195   case dwarf::DW_TAG_volatile_type:
196   case dwarf::DW_TAG_restrict_type:
197   case dwarf::DW_TAG_member:
198   case dwarf::DW_TAG_inheritance:
199   case dwarf::DW_TAG_friend:
200     return true;
201   default:
202     // CompositeTypes are currently modelled as DerivedTypes.
203     return isCompositeType();
204   }
207 bool DIDescriptor::isCompositeType() const {
208   if (!DbgNode)
209     return false;
210   switch (getTag()) {
211   case dwarf::DW_TAG_array_type:
212   case dwarf::DW_TAG_structure_type:
213   case dwarf::DW_TAG_union_type:
214   case dwarf::DW_TAG_enumeration_type:
215   case dwarf::DW_TAG_subroutine_type:
216   case dwarf::DW_TAG_class_type:
217     return true;
218   default:
219     return false;
220   }
223 bool DIDescriptor::isVariable() const {
224   if (!DbgNode)
225     return false;
226   switch (getTag()) {
227   case dwarf::DW_TAG_auto_variable:
228   case dwarf::DW_TAG_arg_variable:
229     return true;
230   default:
231     return false;
232   }
235 bool DIDescriptor::isType() const {
236   return isBasicType() || isCompositeType() || isDerivedType();
239 bool DIDescriptor::isSubprogram() const {
240   return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
243 bool DIDescriptor::isGlobalVariable() const {
244   return DbgNode && (getTag() == dwarf::DW_TAG_variable ||
245                      getTag() == dwarf::DW_TAG_constant);
248 bool DIDescriptor::isScope() const {
249   if (!DbgNode)
250     return false;
251   switch (getTag()) {
252   case dwarf::DW_TAG_compile_unit:
253   case dwarf::DW_TAG_lexical_block:
254   case dwarf::DW_TAG_subprogram:
255   case dwarf::DW_TAG_namespace:
256   case dwarf::DW_TAG_file_type:
257     return true;
258   default:
259     break;
260   }
261   return isType();
264 bool DIDescriptor::isTemplateTypeParameter() const {
265   return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
268 bool DIDescriptor::isTemplateValueParameter() const {
269   return DbgNode && (getTag() == dwarf::DW_TAG_template_value_parameter ||
270                      getTag() == dwarf::DW_TAG_GNU_template_template_param ||
271                      getTag() == dwarf::DW_TAG_GNU_template_parameter_pack);
274 bool DIDescriptor::isCompileUnit() const {
275   return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
278 bool DIDescriptor::isFile() const {
279   return DbgNode && getTag() == dwarf::DW_TAG_file_type;
282 bool DIDescriptor::isNameSpace() const {
283   return DbgNode && getTag() == dwarf::DW_TAG_namespace;
286 bool DIDescriptor::isLexicalBlockFile() const {
287   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
288          DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 2;
291 bool DIDescriptor::isLexicalBlock() const {
292   // FIXME: There are always exactly 4 header fields in DILexicalBlock, but
293   // something relies on this returning true for DILexicalBlockFile.
294   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
295          DbgNode->getNumOperands() == 3 &&
296          (getNumHeaderFields() == 2 || getNumHeaderFields() == 4);
299 bool DIDescriptor::isSubrange() const {
300   return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
303 bool DIDescriptor::isEnumerator() const {
304   return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
307 bool DIDescriptor::isObjCProperty() const {
308   return DbgNode && getTag() == dwarf::DW_TAG_APPLE_property;
311 bool DIDescriptor::isImportedEntity() const {
312   return DbgNode && (getTag() == dwarf::DW_TAG_imported_module ||
313                      getTag() == dwarf::DW_TAG_imported_declaration);
316 bool DIDescriptor::isExpression() const {
317   return DbgNode && (getTag() == dwarf::DW_TAG_expression);
320 //===----------------------------------------------------------------------===//
321 // Simple Descriptor Constructors and other Methods
322 //===----------------------------------------------------------------------===//
324 void DIDescriptor::replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D) {
326   assert(DbgNode && "Trying to replace an unverified type!");
328   // Since we use a TrackingVH for the node, its easy for clients to manufacture
329   // legitimate situations where they want to replaceAllUsesWith() on something
330   // which, due to uniquing, has merged with the source. We shield clients from
331   // this detail by allowing a value to be replaced with replaceAllUsesWith()
332   // itself.
333   const MDNode *DN = D;
334   if (DbgNode == DN) {
335     SmallVector<Metadata *, 10> Ops(DbgNode->getNumOperands());
336     for (size_t i = 0; i != Ops.size(); ++i)
337       Ops[i] = DbgNode->getOperand(i);
338     DN = MDNode::get(VMContext, Ops);
339   }
341   assert(DbgNode->isTemporary() && "Expected temporary node");
342   auto *Node = const_cast<MDNode *>(DbgNode);
343   Node->replaceAllUsesWith(const_cast<MDNode *>(DN));
344   MDNode::deleteTemporary(Node);
345   DbgNode = DN;
348 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
349   assert(DbgNode && "Trying to replace an unverified type!");
350   assert(DbgNode != D && "This replacement should always happen");
351   assert(DbgNode->isTemporary() && "Expected temporary node");
352   auto *Node = const_cast<MDNode *>(DbgNode);
353   Node->replaceAllUsesWith(D);
354   MDNode::deleteTemporary(Node);
357 bool DICompileUnit::Verify() const {
358   if (!isCompileUnit())
359     return false;
361   // Don't bother verifying the compilation directory or producer string
362   // as those could be empty.
363   if (getFilename().empty())
364     return false;
366   return DbgNode->getNumOperands() == 7 && getNumHeaderFields() == 8;
369 bool DIObjCProperty::Verify() const {
370   if (!isObjCProperty())
371     return false;
373   // Don't worry about the rest of the strings for now.
374   return DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 6;
377 /// \brief Check if a field at position Elt of a MDNode is a MDNode.
378 ///
379 /// We currently allow an empty string and an integer.
380 /// But we don't allow a non-empty string in a MDNode field.
381 static bool fieldIsMDNode(const MDNode *DbgNode, unsigned Elt) {
382   // FIXME: This function should return true, if the field is null or the field
383   // is indeed a MDNode: return !Fld || isa<MDNode>(Fld).
384   Metadata *Fld = getField(DbgNode, Elt);
385   if (Fld && isa<MDString>(Fld) && !cast<MDString>(Fld)->getString().empty())
386     return false;
387   return true;
390 /// \brief Check if a field at position Elt of a MDNode is a MDString.
391 static bool fieldIsMDString(const MDNode *DbgNode, unsigned Elt) {
392   Metadata *Fld = getField(DbgNode, Elt);
393   return !Fld || isa<MDString>(Fld);
396 /// \brief Check if a value can be a reference to a type.
397 static bool isTypeRef(const Metadata *MD) {
398   if (!MD)
399     return true;
400   if (auto *S = dyn_cast<MDString>(MD))
401     return !S->getString().empty();
402   if (auto *N = dyn_cast<MDNode>(MD))
403     return DIType(N).isType();
404   return false;
407 /// \brief Check if referenced field might be a type.
408 static bool fieldIsTypeRef(const MDNode *DbgNode, unsigned Elt) {
409   return isTypeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
412 /// \brief Check if a value can be a ScopeRef.
413 static bool isScopeRef(const Metadata *MD) {
414   if (!MD)
415     return true;
416   if (auto *S = dyn_cast<MDString>(MD))
417     return !S->getString().empty();
418   return isa<MDNode>(MD);
421 /// \brief Check if a field at position Elt of a MDNode can be a ScopeRef.
422 static bool fieldIsScopeRef(const MDNode *DbgNode, unsigned Elt) {
423   return isScopeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
426 bool DIType::Verify() const {
427   if (!isType())
428     return false;
429   // Make sure Context @ field 2 is MDNode.
430   if (!fieldIsScopeRef(DbgNode, 2))
431     return false;
433   // FIXME: Sink this into the various subclass verifies.
434   uint16_t Tag = getTag();
435   if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
436       Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
437       Tag != dwarf::DW_TAG_ptr_to_member_type &&
438       Tag != dwarf::DW_TAG_reference_type &&
439       Tag != dwarf::DW_TAG_rvalue_reference_type &&
440       Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
441       Tag != dwarf::DW_TAG_enumeration_type &&
442       Tag != dwarf::DW_TAG_subroutine_type &&
443       Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
444       getFilename().empty())
445     return false;
447   // DIType is abstract, it should be a BasicType, a DerivedType or
448   // a CompositeType.
449   if (isBasicType())
450     return DIBasicType(DbgNode).Verify();
451   else if (isCompositeType())
452     return DICompositeType(DbgNode).Verify();
453   else if (isDerivedType())
454     return DIDerivedType(DbgNode).Verify();
455   else
456     return false;
459 bool DIBasicType::Verify() const {
460   return isBasicType() && DbgNode->getNumOperands() == 3 &&
461          getNumHeaderFields() == 8;
464 bool DIDerivedType::Verify() const {
465   // Make sure DerivedFrom @ field 3 is TypeRef.
466   if (!fieldIsTypeRef(DbgNode, 3))
467     return false;
468   if (getTag() == dwarf::DW_TAG_ptr_to_member_type)
469     // Make sure ClassType @ field 4 is a TypeRef.
470     if (!fieldIsTypeRef(DbgNode, 4))
471       return false;
473   return isDerivedType() && DbgNode->getNumOperands() >= 4 &&
474          DbgNode->getNumOperands() <= 8 && getNumHeaderFields() >= 7 &&
475          getNumHeaderFields() <= 8;
478 bool DICompositeType::Verify() const {
479   if (!isCompositeType())
480     return false;
482   // Make sure DerivedFrom @ field 3 and ContainingType @ field 5 are TypeRef.
483   if (!fieldIsTypeRef(DbgNode, 3))
484     return false;
485   if (!fieldIsTypeRef(DbgNode, 5))
486     return false;
488   // Make sure the type identifier at field 7 is MDString, it can be null.
489   if (!fieldIsMDString(DbgNode, 7))
490     return false;
492   // A subroutine type can't be both & and &&.
493   if (isLValueReference() && isRValueReference())
494     return false;
496   return DbgNode->getNumOperands() == 8 && getNumHeaderFields() == 8;
499 bool DISubprogram::Verify() const {
500   if (!isSubprogram())
501     return false;
503   // Make sure context @ field 2 is a ScopeRef and type @ field 3 is a MDNode.
504   if (!fieldIsScopeRef(DbgNode, 2))
505     return false;
506   if (!fieldIsMDNode(DbgNode, 3))
507     return false;
508   // Containing type @ field 4.
509   if (!fieldIsTypeRef(DbgNode, 4))
510     return false;
512   // A subprogram can't be both & and &&.
513   if (isLValueReference() && isRValueReference())
514     return false;
516   // If a DISubprogram has an llvm::Function*, then scope chains from all
517   // instructions within the function should lead to this DISubprogram.
518   if (auto *F = getFunction()) {
519     for (auto &BB : *F) {
520       for (auto &I : BB) {
521         DebugLoc DL = I.getDebugLoc();
522         if (DL.isUnknown())
523           continue;
525         MDNode *Scope = nullptr;
526         MDNode *IA = nullptr;
527         // walk the inlined-at scopes
528         while ((IA = DL.getInlinedAt()))
529           DL = DebugLoc::getFromDILocation(IA);
530         DL.getScopeAndInlinedAt(Scope, IA);
531         if (!Scope)
532           return false;
533         assert(!IA);
534         while (!DIDescriptor(Scope).isSubprogram()) {
535           DILexicalBlockFile D(Scope);
536           Scope = D.isLexicalBlockFile()
537                       ? D.getScope()
538                       : DebugLoc::getFromDILexicalBlock(Scope).getScope();
539           assert(Scope && "lexical block file has no scope");
540         }
541         if (!DISubprogram(Scope).describes(F))
542           return false;
543       }
544     }
545   }
546   return DbgNode->getNumOperands() == 9 && getNumHeaderFields() == 12;
549 bool DIGlobalVariable::Verify() const {
550   if (!isGlobalVariable())
551     return false;
553   if (getDisplayName().empty())
554     return false;
555   // Make sure context @ field 1 is an MDNode.
556   if (!fieldIsMDNode(DbgNode, 1))
557     return false;
558   // Make sure that type @ field 3 is a DITypeRef.
559   if (!fieldIsTypeRef(DbgNode, 3))
560     return false;
561   // Make sure StaticDataMemberDeclaration @ field 5 is MDNode.
562   if (!fieldIsMDNode(DbgNode, 5))
563     return false;
565   return DbgNode->getNumOperands() == 6 && getNumHeaderFields() == 7;
568 bool DIVariable::Verify() const {
569   if (!isVariable())
570     return false;
572   // Make sure context @ field 1 is an MDNode.
573   if (!fieldIsMDNode(DbgNode, 1))
574     return false;
575   // Make sure that type @ field 3 is a DITypeRef.
576   if (!fieldIsTypeRef(DbgNode, 3))
577     return false;
579   // Check the number of header fields, which is common between complex and
580   // simple variables.
581   if (getNumHeaderFields() != 4)
582     return false;
584   // Variable without an inline location.
585   if (DbgNode->getNumOperands() == 4)
586     return true;
588   // Variable with an inline location.
589   return getInlinedAt() != nullptr && DbgNode->getNumOperands() == 5;
592 bool DIExpression::Verify() const {
593   // Empty DIExpressions may be represented as a nullptr.
594   if (!DbgNode)
595     return true;
597   unsigned N = getNumElements();
598   for (unsigned I = 0; I < N; ++I)
599     switch (getElement(I)) {
600     case DW_OP_piece:
601       // DW_OP_piece has to be the last element in the expression and take two
602       // arguments.
603       if (getElement(I) == DW_OP_piece && !isVariablePiece())
604         return false;
605       I += 2;
606       break;
607     case DW_OP_plus:
608       // Takes one argument.
609       if (I+1 == N)
610         return false;
611       I += 1;
612       break;
613     default: break;
614   }
615   return isExpression() && DbgNode->getNumOperands() == 1;
618 bool DILocation::Verify() const {
619   return DbgNode && isa<MDLocation>(DbgNode);
622 bool DINameSpace::Verify() const {
623   if (!isNameSpace())
624     return false;
625   return DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 3;
628 MDNode *DIFile::getFileNode() const { return getNodeField(DbgNode, 1); }
630 bool DIFile::Verify() const {
631   return isFile() && DbgNode->getNumOperands() == 2;
634 bool DIEnumerator::Verify() const {
635   return isEnumerator() && DbgNode->getNumOperands() == 1 &&
636          getNumHeaderFields() == 3;
639 bool DISubrange::Verify() const {
640   return isSubrange() && DbgNode->getNumOperands() == 1 &&
641          getNumHeaderFields() == 3;
644 bool DILexicalBlock::Verify() const {
645   return isLexicalBlock() && DbgNode->getNumOperands() == 3 &&
646          getNumHeaderFields() == 4;
649 bool DILexicalBlockFile::Verify() const {
650   return isLexicalBlockFile() && DbgNode->getNumOperands() == 3 &&
651          getNumHeaderFields() == 2;
654 bool DITemplateTypeParameter::Verify() const {
655   return isTemplateTypeParameter() && DbgNode->getNumOperands() == 4 &&
656          getNumHeaderFields() == 4;
659 bool DITemplateValueParameter::Verify() const {
660   return isTemplateValueParameter() && DbgNode->getNumOperands() == 5 &&
661          getNumHeaderFields() == 4;
664 bool DIImportedEntity::Verify() const {
665   return isImportedEntity() && DbgNode->getNumOperands() == 3 &&
666          getNumHeaderFields() == 3;
669 MDNode *DIDerivedType::getObjCProperty() const {
670   return getNodeField(DbgNode, 4);
673 MDString *DICompositeType::getIdentifier() const {
674   return cast_or_null<MDString>(getField(DbgNode, 7));
677 #ifndef NDEBUG
678 static void VerifySubsetOf(const MDNode *LHS, const MDNode *RHS) {
679   for (unsigned i = 0; i != LHS->getNumOperands(); ++i) {
680     // Skip the 'empty' list (that's a single i32 0, rather than truly empty).
681     if (i == 0 && mdconst::hasa<ConstantInt>(LHS->getOperand(i)))
682       continue;
683     const MDNode *E = cast<MDNode>(LHS->getOperand(i));
684     bool found = false;
685     for (unsigned j = 0; !found && j != RHS->getNumOperands(); ++j)
686       found = (E == cast<MDNode>(RHS->getOperand(j)));
687     assert(found && "Losing a member during member list replacement");
688   }
690 #endif
692 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
693   TrackingMDNodeRef N(*this);
694   if (Elements) {
695 #ifndef NDEBUG
696     // Check that the new list of members contains all the old members as well.
697     if (const MDNode *El = cast_or_null<MDNode>(N->getOperand(4)))
698       VerifySubsetOf(El, Elements);
699 #endif
700     N->replaceOperandWith(4, Elements);
701   }
702   if (TParams)
703     N->replaceOperandWith(6, TParams);
704   DbgNode = N;
707 DIScopeRef DIScope::getRef() const {
708   if (!isCompositeType())
709     return DIScopeRef(*this);
710   DICompositeType DTy(DbgNode);
711   if (!DTy.getIdentifier())
712     return DIScopeRef(*this);
713   return DIScopeRef(DTy.getIdentifier());
716 void DICompositeType::setContainingType(DICompositeType ContainingType) {
717   TrackingMDNodeRef N(*this);
718   N->replaceOperandWith(5, ContainingType.getRef());
719   DbgNode = N;
722 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
723   assert(CurFn && "Invalid function");
724   if (!getContext().isSubprogram())
725     return false;
726   // This variable is not inlined function argument if its scope
727   // does not describe current function.
728   return !DISubprogram(getContext()).describes(CurFn);
731 bool DISubprogram::describes(const Function *F) {
732   assert(F && "Invalid function");
733   if (F == getFunction())
734     return true;
735   StringRef Name = getLinkageName();
736   if (Name.empty())
737     Name = getName();
738   if (F->getName() == Name)
739     return true;
740   return false;
743 MDNode *DISubprogram::getVariablesNodes() const {
744   return getNodeField(DbgNode, 8);
747 DIArray DISubprogram::getVariables() const {
748   return DIArray(getNodeField(DbgNode, 8));
751 Metadata *DITemplateValueParameter::getValue() const {
752   return DbgNode->getOperand(3);
755 DIScopeRef DIScope::getContext() const {
757   if (isType())
758     return DIType(DbgNode).getContext();
760   if (isSubprogram())
761     return DIScopeRef(DISubprogram(DbgNode).getContext());
763   if (isLexicalBlock())
764     return DIScopeRef(DILexicalBlock(DbgNode).getContext());
766   if (isLexicalBlockFile())
767     return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
769   if (isNameSpace())
770     return DIScopeRef(DINameSpace(DbgNode).getContext());
772   assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
773   return DIScopeRef(nullptr);
776 StringRef DIScope::getName() const {
777   if (isType())
778     return DIType(DbgNode).getName();
779   if (isSubprogram())
780     return DISubprogram(DbgNode).getName();
781   if (isNameSpace())
782     return DINameSpace(DbgNode).getName();
783   assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
784           isCompileUnit()) &&
785          "Unhandled type of scope.");
786   return StringRef();
789 StringRef DIScope::getFilename() const {
790   if (!DbgNode)
791     return StringRef();
792   return ::getStringField(getNodeField(DbgNode, 1), 0);
795 StringRef DIScope::getDirectory() const {
796   if (!DbgNode)
797     return StringRef();
798   return ::getStringField(getNodeField(DbgNode, 1), 1);
801 DIArray DICompileUnit::getEnumTypes() const {
802   if (!DbgNode || DbgNode->getNumOperands() < 7)
803     return DIArray();
805   return DIArray(getNodeField(DbgNode, 2));
808 DIArray DICompileUnit::getRetainedTypes() const {
809   if (!DbgNode || DbgNode->getNumOperands() < 7)
810     return DIArray();
812   return DIArray(getNodeField(DbgNode, 3));
815 DIArray DICompileUnit::getSubprograms() const {
816   if (!DbgNode || DbgNode->getNumOperands() < 7)
817     return DIArray();
819   return DIArray(getNodeField(DbgNode, 4));
822 DIArray DICompileUnit::getGlobalVariables() const {
823   if (!DbgNode || DbgNode->getNumOperands() < 7)
824     return DIArray();
826   return DIArray(getNodeField(DbgNode, 5));
829 DIArray DICompileUnit::getImportedEntities() const {
830   if (!DbgNode || DbgNode->getNumOperands() < 7)
831     return DIArray();
833   return DIArray(getNodeField(DbgNode, 6));
836 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
837   assert(Verify() && "Expected compile unit");
838   if (Subprograms == getSubprograms())
839     return;
841   const_cast<MDNode *>(DbgNode)->replaceOperandWith(4, Subprograms);
844 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
845   assert(Verify() && "Expected compile unit");
846   if (GlobalVariables == getGlobalVariables())
847     return;
849   const_cast<MDNode *>(DbgNode)->replaceOperandWith(5, GlobalVariables);
852 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
853                                         DILexicalBlockFile NewScope) {
854   assert(Verify());
855   assert(NewScope && "Expected valid scope");
857   const auto *Old = cast<MDLocation>(DbgNode);
858   return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
859                                     NewScope, Old->getInlinedAt()));
862 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
863   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
864   return ++Ctx.pImpl->DiscriminatorTable[Key];
867 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
868                                        LLVMContext &VMContext) {
869   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
870   if (!InlinedScope)
871     return cleanseInlinedVariable(DV, VMContext);
873   // Insert inlined scope.
874   SmallVector<Metadata *, 8> Elts;
875   for (unsigned I = 0, E = DIVariableInlinedAtIndex; I != E; ++I)
876     Elts.push_back(DV->getOperand(I));
877   Elts.push_back(InlinedScope);
879   DIVariable Inlined(MDNode::get(VMContext, Elts));
880   assert(Inlined.Verify() && "Expected to create a DIVariable");
881   return Inlined;
884 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
885   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
886   if (!DIVariable(DV).getInlinedAt())
887     return DIVariable(DV);
889   // Remove inlined scope.
890   SmallVector<Metadata *, 8> Elts;
891   for (unsigned I = 0, E = DIVariableInlinedAtIndex; I != E; ++I)
892     Elts.push_back(DV->getOperand(I));
894   DIVariable Cleansed(MDNode::get(VMContext, Elts));
895   assert(Cleansed.Verify() && "Expected to create a DIVariable");
896   return Cleansed;
899 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
900   DIDescriptor D(Scope);
901   if (D.isSubprogram())
902     return DISubprogram(Scope);
904   if (D.isLexicalBlockFile())
905     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
907   if (D.isLexicalBlock())
908     return getDISubprogram(DILexicalBlock(Scope).getContext());
910   return DISubprogram();
913 DISubprogram llvm::getDISubprogram(const Function *F) {
914   // We look for the first instr that has a debug annotation leading back to F.
915   for (auto &BB : *F) {
916     auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
917       return !Inst.getDebugLoc().isUnknown();
918     });
919     if (Inst == BB.end())
920       continue;
921     DebugLoc DLoc = Inst->getDebugLoc();
922     const MDNode *Scope = DLoc.getScopeNode();
923     DISubprogram Subprogram = getDISubprogram(Scope);
924     return Subprogram.describes(F) ? Subprogram : DISubprogram();
925   }
927   return DISubprogram();
930 DICompositeType llvm::getDICompositeType(DIType T) {
931   if (T.isCompositeType())
932     return DICompositeType(T);
934   if (T.isDerivedType()) {
935     // This function is currently used by dragonegg and dragonegg does
936     // not generate identifier for types, so using an empty map to resolve
937     // DerivedFrom should be fine.
938     DITypeIdentifierMap EmptyMap;
939     return getDICompositeType(
940         DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
941   }
943   return DICompositeType();
946 DITypeIdentifierMap
947 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
948   DITypeIdentifierMap Map;
949   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
950     DICompileUnit CU(CU_Nodes->getOperand(CUi));
951     DIArray Retain = CU.getRetainedTypes();
952     for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
953       if (!Retain.getElement(Ti).isCompositeType())
954         continue;
955       DICompositeType Ty(Retain.getElement(Ti));
956       if (MDString *TypeId = Ty.getIdentifier()) {
957         // Definition has priority over declaration.
958         // Try to insert (TypeId, Ty) to Map.
959         std::pair<DITypeIdentifierMap::iterator, bool> P =
960             Map.insert(std::make_pair(TypeId, Ty));
961         // If TypeId already exists in Map and this is a definition, replace
962         // whatever we had (declaration or definition) with the definition.
963         if (!P.second && !Ty.isForwardDecl())
964           P.first->second = Ty;
965       }
966     }
967   }
968   return Map;
971 //===----------------------------------------------------------------------===//
972 // DebugInfoFinder implementations.
973 //===----------------------------------------------------------------------===//
975 void DebugInfoFinder::reset() {
976   CUs.clear();
977   SPs.clear();
978   GVs.clear();
979   TYs.clear();
980   Scopes.clear();
981   NodesSeen.clear();
982   TypeIdentifierMap.clear();
983   TypeMapInitialized = false;
986 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
987   if (!TypeMapInitialized)
988     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
989       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
990       TypeMapInitialized = true;
991     }
994 void DebugInfoFinder::processModule(const Module &M) {
995   InitializeTypeMap(M);
996   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
997     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
998       DICompileUnit CU(CU_Nodes->getOperand(i));
999       addCompileUnit(CU);
1000       DIArray GVs = CU.getGlobalVariables();
1001       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
1002         DIGlobalVariable DIG(GVs.getElement(i));
1003         if (addGlobalVariable(DIG)) {
1004           processScope(DIG.getContext());
1005           processType(DIG.getType().resolve(TypeIdentifierMap));
1006         }
1007       }
1008       DIArray SPs = CU.getSubprograms();
1009       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
1010         processSubprogram(DISubprogram(SPs.getElement(i)));
1011       DIArray EnumTypes = CU.getEnumTypes();
1012       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
1013         processType(DIType(EnumTypes.getElement(i)));
1014       DIArray RetainedTypes = CU.getRetainedTypes();
1015       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
1016         processType(DIType(RetainedTypes.getElement(i)));
1017       DIArray Imports = CU.getImportedEntities();
1018       for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
1019         DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
1020         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
1021         if (Entity.isType())
1022           processType(DIType(Entity));
1023         else if (Entity.isSubprogram())
1024           processSubprogram(DISubprogram(Entity));
1025         else if (Entity.isNameSpace())
1026           processScope(DINameSpace(Entity).getContext());
1027       }
1028     }
1029   }
1032 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
1033   if (!Loc)
1034     return;
1035   InitializeTypeMap(M);
1036   processScope(Loc.getScope());
1037   processLocation(M, Loc.getOrigLocation());
1040 void DebugInfoFinder::processType(DIType DT) {
1041   if (!addType(DT))
1042     return;
1043   processScope(DT.getContext().resolve(TypeIdentifierMap));
1044   if (DT.isCompositeType()) {
1045     DICompositeType DCT(DT);
1046     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1047     if (DT.isSubroutineType()) {
1048       DITypeArray DTA = DISubroutineType(DT).getTypeArray();
1049       for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
1050         processType(DTA.getElement(i).resolve(TypeIdentifierMap));
1051       return;
1052     }
1053     DIArray DA = DCT.getElements();
1054     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1055       DIDescriptor D = DA.getElement(i);
1056       if (D.isType())
1057         processType(DIType(D));
1058       else if (D.isSubprogram())
1059         processSubprogram(DISubprogram(D));
1060     }
1061   } else if (DT.isDerivedType()) {
1062     DIDerivedType DDT(DT);
1063     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1064   }
1067 void DebugInfoFinder::processScope(DIScope Scope) {
1068   if (Scope.isType()) {
1069     DIType Ty(Scope);
1070     processType(Ty);
1071     return;
1072   }
1073   if (Scope.isCompileUnit()) {
1074     addCompileUnit(DICompileUnit(Scope));
1075     return;
1076   }
1077   if (Scope.isSubprogram()) {
1078     processSubprogram(DISubprogram(Scope));
1079     return;
1080   }
1081   if (!addScope(Scope))
1082     return;
1083   if (Scope.isLexicalBlock()) {
1084     DILexicalBlock LB(Scope);
1085     processScope(LB.getContext());
1086   } else if (Scope.isLexicalBlockFile()) {
1087     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
1088     processScope(LBF.getScope());
1089   } else if (Scope.isNameSpace()) {
1090     DINameSpace NS(Scope);
1091     processScope(NS.getContext());
1092   }
1095 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1096   if (!addSubprogram(SP))
1097     return;
1098   processScope(SP.getContext().resolve(TypeIdentifierMap));
1099   processType(SP.getType());
1100   DIArray TParams = SP.getTemplateParams();
1101   for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
1102     DIDescriptor Element = TParams.getElement(I);
1103     if (Element.isTemplateTypeParameter()) {
1104       DITemplateTypeParameter TType(Element);
1105       processScope(TType.getContext().resolve(TypeIdentifierMap));
1106       processType(TType.getType().resolve(TypeIdentifierMap));
1107     } else if (Element.isTemplateValueParameter()) {
1108       DITemplateValueParameter TVal(Element);
1109       processScope(TVal.getContext().resolve(TypeIdentifierMap));
1110       processType(TVal.getType().resolve(TypeIdentifierMap));
1111     }
1112   }
1115 void DebugInfoFinder::processDeclare(const Module &M,
1116                                      const DbgDeclareInst *DDI) {
1117   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1118   if (!N)
1119     return;
1120   InitializeTypeMap(M);
1122   DIDescriptor DV(N);
1123   if (!DV.isVariable())
1124     return;
1126   if (!NodesSeen.insert(DV).second)
1127     return;
1128   processScope(DIVariable(N).getContext());
1129   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1132 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
1133   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
1134   if (!N)
1135     return;
1136   InitializeTypeMap(M);
1138   DIDescriptor DV(N);
1139   if (!DV.isVariable())
1140     return;
1142   if (!NodesSeen.insert(DV).second)
1143     return;
1144   processScope(DIVariable(N).getContext());
1145   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1148 bool DebugInfoFinder::addType(DIType DT) {
1149   if (!DT)
1150     return false;
1152   if (!NodesSeen.insert(DT).second)
1153     return false;
1155   TYs.push_back(DT);
1156   return true;
1159 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1160   if (!CU)
1161     return false;
1162   if (!NodesSeen.insert(CU).second)
1163     return false;
1165   CUs.push_back(CU);
1166   return true;
1169 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1170   if (!DIG)
1171     return false;
1173   if (!NodesSeen.insert(DIG).second)
1174     return false;
1176   GVs.push_back(DIG);
1177   return true;
1180 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1181   if (!SP)
1182     return false;
1184   if (!NodesSeen.insert(SP).second)
1185     return false;
1187   SPs.push_back(SP);
1188   return true;
1191 bool DebugInfoFinder::addScope(DIScope Scope) {
1192   if (!Scope)
1193     return false;
1194   // FIXME: Ocaml binding generates a scope with no content, we treat it
1195   // as null for now.
1196   if (Scope->getNumOperands() == 0)
1197     return false;
1198   if (!NodesSeen.insert(Scope).second)
1199     return false;
1200   Scopes.push_back(Scope);
1201   return true;
1204 //===----------------------------------------------------------------------===//
1205 // DIDescriptor: dump routines for all descriptors.
1206 //===----------------------------------------------------------------------===//
1208 void DIDescriptor::dump() const {
1209   print(dbgs());
1210   dbgs() << '\n';
1213 void DIDescriptor::print(raw_ostream &OS) const {
1214   if (!DbgNode)
1215     return;
1217   if (const char *Tag = dwarf::TagString(getTag()))
1218     OS << "[ " << Tag << " ]";
1220   if (this->isSubrange()) {
1221     DISubrange(DbgNode).printInternal(OS);
1222   } else if (this->isCompileUnit()) {
1223     DICompileUnit(DbgNode).printInternal(OS);
1224   } else if (this->isFile()) {
1225     DIFile(DbgNode).printInternal(OS);
1226   } else if (this->isEnumerator()) {
1227     DIEnumerator(DbgNode).printInternal(OS);
1228   } else if (this->isBasicType()) {
1229     DIType(DbgNode).printInternal(OS);
1230   } else if (this->isDerivedType()) {
1231     DIDerivedType(DbgNode).printInternal(OS);
1232   } else if (this->isCompositeType()) {
1233     DICompositeType(DbgNode).printInternal(OS);
1234   } else if (this->isSubprogram()) {
1235     DISubprogram(DbgNode).printInternal(OS);
1236   } else if (this->isGlobalVariable()) {
1237     DIGlobalVariable(DbgNode).printInternal(OS);
1238   } else if (this->isVariable()) {
1239     DIVariable(DbgNode).printInternal(OS);
1240   } else if (this->isObjCProperty()) {
1241     DIObjCProperty(DbgNode).printInternal(OS);
1242   } else if (this->isNameSpace()) {
1243     DINameSpace(DbgNode).printInternal(OS);
1244   } else if (this->isScope()) {
1245     DIScope(DbgNode).printInternal(OS);
1246   } else if (this->isExpression()) {
1247     DIExpression(DbgNode).printInternal(OS);
1248   }
1251 void DISubrange::printInternal(raw_ostream &OS) const {
1252   int64_t Count = getCount();
1253   if (Count != -1)
1254     OS << " [" << getLo() << ", " << Count - 1 << ']';
1255   else
1256     OS << " [unbounded]";
1259 void DIScope::printInternal(raw_ostream &OS) const {
1260   OS << " [" << getDirectory() << "/" << getFilename() << ']';
1263 void DICompileUnit::printInternal(raw_ostream &OS) const {
1264   DIScope::printInternal(OS);
1265   OS << " [";
1266   unsigned Lang = getLanguage();
1267   if (const char *LangStr = dwarf::LanguageString(Lang))
1268     OS << LangStr;
1269   else
1270     (OS << "lang 0x").write_hex(Lang);
1271   OS << ']';
1274 void DIEnumerator::printInternal(raw_ostream &OS) const {
1275   OS << " [" << getName() << " :: " << getEnumValue() << ']';
1278 void DIType::printInternal(raw_ostream &OS) const {
1279   if (!DbgNode)
1280     return;
1282   StringRef Res = getName();
1283   if (!Res.empty())
1284     OS << " [" << Res << "]";
1286   // TODO: Print context?
1288   OS << " [line " << getLineNumber() << ", size " << getSizeInBits()
1289      << ", align " << getAlignInBits() << ", offset " << getOffsetInBits();
1290   if (isBasicType())
1291     if (const char *Enc =
1292             dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
1293       OS << ", enc " << Enc;
1294   OS << "]";
1296   if (isPrivate())
1297     OS << " [private]";
1298   else if (isProtected())
1299     OS << " [protected]";
1300   else if (isPublic())
1301     OS << " [public]";
1303   if (isArtificial())
1304     OS << " [artificial]";
1306   if (isForwardDecl())
1307     OS << " [decl]";
1308   else if (getTag() == dwarf::DW_TAG_structure_type ||
1309            getTag() == dwarf::DW_TAG_union_type ||
1310            getTag() == dwarf::DW_TAG_enumeration_type ||
1311            getTag() == dwarf::DW_TAG_class_type)
1312     OS << " [def]";
1313   if (isVector())
1314     OS << " [vector]";
1315   if (isStaticMember())
1316     OS << " [static]";
1318   if (isLValueReference())
1319     OS << " [reference]";
1321   if (isRValueReference())
1322     OS << " [rvalue reference]";
1325 void DIDerivedType::printInternal(raw_ostream &OS) const {
1326   DIType::printInternal(OS);
1327   OS << " [from " << getTypeDerivedFrom().getName() << ']';
1330 void DICompositeType::printInternal(raw_ostream &OS) const {
1331   DIType::printInternal(OS);
1332   DIArray A = getElements();
1333   OS << " [" << A.getNumElements() << " elements]";
1336 void DINameSpace::printInternal(raw_ostream &OS) const {
1337   StringRef Name = getName();
1338   if (!Name.empty())
1339     OS << " [" << Name << ']';
1341   OS << " [line " << getLineNumber() << ']';
1344 void DISubprogram::printInternal(raw_ostream &OS) const {
1345   // TODO : Print context
1346   OS << " [line " << getLineNumber() << ']';
1348   if (isLocalToUnit())
1349     OS << " [local]";
1351   if (isDefinition())
1352     OS << " [def]";
1354   if (getScopeLineNumber() != getLineNumber())
1355     OS << " [scope " << getScopeLineNumber() << "]";
1357   if (isPrivate())
1358     OS << " [private]";
1359   else if (isProtected())
1360     OS << " [protected]";
1361   else if (isPublic())
1362     OS << " [public]";
1364   if (isLValueReference())
1365     OS << " [reference]";
1367   if (isRValueReference())
1368     OS << " [rvalue reference]";
1370   StringRef Res = getName();
1371   if (!Res.empty())
1372     OS << " [" << Res << ']';
1375 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
1376   StringRef Res = getName();
1377   if (!Res.empty())
1378     OS << " [" << Res << ']';
1380   OS << " [line " << getLineNumber() << ']';
1382   // TODO : Print context
1384   if (isLocalToUnit())
1385     OS << " [local]";
1387   if (isDefinition())
1388     OS << " [def]";
1391 void DIVariable::printInternal(raw_ostream &OS) const {
1392   StringRef Res = getName();
1393   if (!Res.empty())
1394     OS << " [" << Res << ']';
1396   OS << " [line " << getLineNumber() << ']';
1399 void DIExpression::printInternal(raw_ostream &OS) const {
1400   for (unsigned I = 0; I < getNumElements(); ++I) {
1401     uint64_t OpCode = getElement(I);
1402     OS << " [" << OperationEncodingString(OpCode);
1403     switch (OpCode) {
1404     case DW_OP_plus: {
1405       OS << " " << getElement(++I);
1406       break;
1407     }
1408     case DW_OP_piece: {
1409       unsigned Offset = getElement(++I);
1410       unsigned Size = getElement(++I);
1411       OS << " offset=" << Offset << ", size=" << Size;
1412       break;
1413     }
1414     case DW_OP_deref:
1415       // No arguments.
1416       break;
1417     default:
1418       // Else bail out early. This may be a line table entry.
1419       OS << "Unknown]";
1420       return;
1421     }
1422     OS << "]";
1423   }
1426 void DIObjCProperty::printInternal(raw_ostream &OS) const {
1427   StringRef Name = getObjCPropertyName();
1428   if (!Name.empty())
1429     OS << " [" << Name << ']';
1431   OS << " [line " << getLineNumber() << ", properties " << getUnsignedField(6)
1432      << ']';
1435 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
1436                           const LLVMContext &Ctx) {
1437   if (!DL.isUnknown()) { // Print source line info.
1438     DIScope Scope(DL.getScope(Ctx));
1439     assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
1440     // Omit the directory, because it's likely to be long and uninteresting.
1441     CommentOS << Scope.getFilename();
1442     CommentOS << ':' << DL.getLine();
1443     if (DL.getCol() != 0)
1444       CommentOS << ':' << DL.getCol();
1445     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1446     if (!InlinedAtDL.isUnknown()) {
1447       CommentOS << " @[ ";
1448       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
1449       CommentOS << " ]";
1450     }
1451   }
1454 void DIVariable::printExtendedName(raw_ostream &OS) const {
1455   const LLVMContext &Ctx = DbgNode->getContext();
1456   StringRef Res = getName();
1457   if (!Res.empty())
1458     OS << Res << "," << getLineNumber();
1459   if (MDNode *InlinedAt = getInlinedAt()) {
1460     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1461     if (!InlinedAtDL.isUnknown()) {
1462       OS << " @[";
1463       printDebugLoc(InlinedAtDL, OS, Ctx);
1464       OS << "]";
1465     }
1466   }
1469 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
1470   assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
1472 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
1473   assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
1476 template <>
1477 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
1478   return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1480 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
1481   return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1484 bool llvm::StripDebugInfo(Module &M) {
1485   bool Changed = false;
1487   // Remove all of the calls to the debugger intrinsics, and remove them from
1488   // the module.
1489   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
1490     while (!Declare->use_empty()) {
1491       CallInst *CI = cast<CallInst>(Declare->user_back());
1492       CI->eraseFromParent();
1493     }
1494     Declare->eraseFromParent();
1495     Changed = true;
1496   }
1498   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
1499     while (!DbgVal->use_empty()) {
1500       CallInst *CI = cast<CallInst>(DbgVal->user_back());
1501       CI->eraseFromParent();
1502     }
1503     DbgVal->eraseFromParent();
1504     Changed = true;
1505   }
1507   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
1508          NME = M.named_metadata_end(); NMI != NME;) {
1509     NamedMDNode *NMD = NMI;
1510     ++NMI;
1511     if (NMD->getName().startswith("llvm.dbg.")) {
1512       NMD->eraseFromParent();
1513       Changed = true;
1514     }
1515   }
1517   for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
1518     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
1519          ++FI)
1520       for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
1521            ++BI) {
1522         if (!BI->getDebugLoc().isUnknown()) {
1523           Changed = true;
1524           BI->setDebugLoc(DebugLoc());
1525         }
1526       }
1528   return Changed;
1531 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
1532   if (auto *Val = mdconst::extract_or_null<ConstantInt>(
1533           M.getModuleFlag("Debug Info Version")))
1534     return Val->getZExtValue();
1535   return 0;
1538 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
1539 llvm::makeSubprogramMap(const Module &M) {
1540   DenseMap<const Function *, DISubprogram> R;
1542   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
1543   if (!CU_Nodes)
1544     return R;
1546   for (MDNode *N : CU_Nodes->operands()) {
1547     DICompileUnit CUNode(N);
1548     DIArray SPs = CUNode.getSubprograms();
1549     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
1550       DISubprogram SP(SPs.getElement(i));
1551       if (Function *F = SP.getFunction())
1552         R.insert(std::make_pair(F, SP));
1553     }
1554   }
1555   return R;