IR: Drop the scope in DI template parameters
[oota-llvm.git] / lib / IR / DebugInfo.cpp
1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/IR/DebugInfo.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DIBuilder.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/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;
34
35 //===----------------------------------------------------------------------===//
36 // DIDescriptor
37 //===----------------------------------------------------------------------===//
38
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 }
54
55 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
56   if (!DbgNode || Elt >= DbgNode->getNumOperands())
57     return nullptr;
58   return DbgNode->getOperand(Elt);
59 }
60
61 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
62   return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
63 }
64
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 }
70
71 StringRef DIDescriptor::getStringField(unsigned Elt) const {
72   return ::getStringField(DbgNode, Elt);
73 }
74
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();
79
80   return 0;
81 }
82
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();
87
88   return 0;
89 }
90
91 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
92   MDNode *Field = getNodeField(DbgNode, Elt);
93   return DIDescriptor(Field);
94 }
95
96 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
97   return dyn_cast_or_null<GlobalVariable>(getConstantField(Elt));
98 }
99
100 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
101   if (!DbgNode)
102     return nullptr;
103
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;
109 }
110
111 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
112   return dyn_cast_or_null<Function>(getConstantField(Elt));
113 }
114
115 void DIDescriptor::replaceFunctionField(unsigned Elt, Function *F) {
116   if (!DbgNode)
117     return;
118
119   if (Elt < DbgNode->getNumOperands()) {
120     MDNode *Node = const_cast<MDNode *>(DbgNode);
121     Node->replaceOperandWith(Elt, F ? ConstantAsMetadata::get(F) : nullptr);
122   }
123 }
124
125 static unsigned DIVariableInlinedAtIndex = 4;
126 MDNode *DIVariable::getInlinedAt() const {
127   return getNodeField(DbgNode, DIVariableInlinedAtIndex);
128 }
129
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();
141 }
142
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);
148 }
149
150 bool DIExpression::isBitPiece() const {
151   unsigned N = getNumElements();
152   return N >=3 && getElement(N-3) == dwarf::DW_OP_bit_piece;
153 }
154
155 uint64_t DIExpression::getBitPieceOffset() const {
156   assert(isBitPiece() && "not a piece");
157   return getElement(getNumElements()-2);
158 }
159
160 uint64_t DIExpression::getBitPieceSize() const {
161   assert(isBitPiece() && "not a piece");
162   return getElement(getNumElements()-1);
163 }
164
165 DIExpression::iterator DIExpression::begin() const {
166  return DIExpression::iterator(*this);
167 }
168
169 DIExpression::iterator DIExpression::end() const {
170  return DIExpression::iterator();
171 }
172
173 DIExpression::Operand DIExpression::Operand::getNext() const {
174   iterator it(I);
175   return *(++it);
176 }
177
178 //===----------------------------------------------------------------------===//
179 // Predicates
180 //===----------------------------------------------------------------------===//
181
182 bool DIDescriptor::isSubroutineType() const {
183   return DbgNode && getTag() == dwarf::DW_TAG_subroutine_type;
184 }
185
186 bool DIDescriptor::isBasicType() const {
187   if (!DbgNode)
188     return false;
189   switch (getTag()) {
190   case dwarf::DW_TAG_base_type:
191   case dwarf::DW_TAG_unspecified_type:
192     return true;
193   default:
194     return false;
195   }
196 }
197
198 bool DIDescriptor::isDerivedType() const {
199   if (!DbgNode)
200     return false;
201   switch (getTag()) {
202   case dwarf::DW_TAG_typedef:
203   case dwarf::DW_TAG_pointer_type:
204   case dwarf::DW_TAG_ptr_to_member_type:
205   case dwarf::DW_TAG_reference_type:
206   case dwarf::DW_TAG_rvalue_reference_type:
207   case dwarf::DW_TAG_const_type:
208   case dwarf::DW_TAG_volatile_type:
209   case dwarf::DW_TAG_restrict_type:
210   case dwarf::DW_TAG_member:
211   case dwarf::DW_TAG_inheritance:
212   case dwarf::DW_TAG_friend:
213     return true;
214   default:
215     // CompositeTypes are currently modelled as DerivedTypes.
216     return isCompositeType();
217   }
218 }
219
220 bool DIDescriptor::isCompositeType() const {
221   if (!DbgNode)
222     return false;
223   switch (getTag()) {
224   case dwarf::DW_TAG_array_type:
225   case dwarf::DW_TAG_structure_type:
226   case dwarf::DW_TAG_union_type:
227   case dwarf::DW_TAG_enumeration_type:
228   case dwarf::DW_TAG_subroutine_type:
229   case dwarf::DW_TAG_class_type:
230     return true;
231   default:
232     return false;
233   }
234 }
235
236 bool DIDescriptor::isVariable() const {
237   if (!DbgNode)
238     return false;
239   switch (getTag()) {
240   case dwarf::DW_TAG_auto_variable:
241   case dwarf::DW_TAG_arg_variable:
242     return true;
243   default:
244     return false;
245   }
246 }
247
248 bool DIDescriptor::isType() const {
249   return isBasicType() || isCompositeType() || isDerivedType();
250 }
251
252 bool DIDescriptor::isSubprogram() const {
253   return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
254 }
255
256 bool DIDescriptor::isGlobalVariable() const {
257   return DbgNode && getTag() == dwarf::DW_TAG_variable;
258 }
259
260 bool DIDescriptor::isScope() const {
261   if (!DbgNode)
262     return false;
263   switch (getTag()) {
264   case dwarf::DW_TAG_compile_unit:
265   case dwarf::DW_TAG_lexical_block:
266   case dwarf::DW_TAG_subprogram:
267   case dwarf::DW_TAG_namespace:
268   case dwarf::DW_TAG_file_type:
269     return true;
270   default:
271     break;
272   }
273   return isType();
274 }
275
276 bool DIDescriptor::isTemplateTypeParameter() const {
277   return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
278 }
279
280 bool DIDescriptor::isTemplateValueParameter() const {
281   return DbgNode && (getTag() == dwarf::DW_TAG_template_value_parameter ||
282                      getTag() == dwarf::DW_TAG_GNU_template_template_param ||
283                      getTag() == dwarf::DW_TAG_GNU_template_parameter_pack);
284 }
285
286 bool DIDescriptor::isCompileUnit() const {
287   return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
288 }
289
290 bool DIDescriptor::isFile() const {
291   return DbgNode && getTag() == dwarf::DW_TAG_file_type;
292 }
293
294 bool DIDescriptor::isNameSpace() const {
295   return DbgNode && getTag() == dwarf::DW_TAG_namespace;
296 }
297
298 bool DIDescriptor::isLexicalBlockFile() const {
299   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
300          DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 2;
301 }
302
303 bool DIDescriptor::isLexicalBlock() const {
304   // FIXME: There are always exactly 4 header fields in DILexicalBlock, but
305   // something relies on this returning true for DILexicalBlockFile.
306   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
307          DbgNode->getNumOperands() == 3 &&
308          (getNumHeaderFields() == 2 || getNumHeaderFields() == 4);
309 }
310
311 bool DIDescriptor::isSubrange() const {
312   return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
313 }
314
315 bool DIDescriptor::isEnumerator() const {
316   return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
317 }
318
319 bool DIDescriptor::isObjCProperty() const {
320   return DbgNode && getTag() == dwarf::DW_TAG_APPLE_property;
321 }
322
323 bool DIDescriptor::isImportedEntity() const {
324   return DbgNode && (getTag() == dwarf::DW_TAG_imported_module ||
325                      getTag() == dwarf::DW_TAG_imported_declaration);
326 }
327
328 bool DIDescriptor::isExpression() const {
329   return DbgNode && (getTag() == dwarf::DW_TAG_expression);
330 }
331
332 //===----------------------------------------------------------------------===//
333 // Simple Descriptor Constructors and other Methods
334 //===----------------------------------------------------------------------===//
335
336 void DIDescriptor::replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D) {
337
338   assert(DbgNode && "Trying to replace an unverified type!");
339
340   // Since we use a TrackingVH for the node, its easy for clients to manufacture
341   // legitimate situations where they want to replaceAllUsesWith() on something
342   // which, due to uniquing, has merged with the source. We shield clients from
343   // this detail by allowing a value to be replaced with replaceAllUsesWith()
344   // itself.
345   const MDNode *DN = D;
346   if (DbgNode == DN) {
347     SmallVector<Metadata *, 10> Ops(DbgNode->op_begin(), DbgNode->op_end());
348     DN = MDNode::get(VMContext, Ops);
349   }
350
351   assert(DbgNode->isTemporary() && "Expected temporary node");
352   auto *Node = const_cast<MDNode *>(DbgNode);
353   Node->replaceAllUsesWith(const_cast<MDNode *>(DN));
354   MDNode::deleteTemporary(Node);
355   DbgNode = DN;
356 }
357
358 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
359   assert(DbgNode && "Trying to replace an unverified type!");
360   assert(DbgNode != D && "This replacement should always happen");
361   assert(DbgNode->isTemporary() && "Expected temporary node");
362   auto *Node = const_cast<MDNode *>(DbgNode);
363   Node->replaceAllUsesWith(D);
364   MDNode::deleteTemporary(Node);
365 }
366
367 bool DICompileUnit::Verify() const {
368   if (!isCompileUnit())
369     return false;
370
371   // Don't bother verifying the compilation directory or producer string
372   // as those could be empty.
373   if (getFilename().empty())
374     return false;
375
376   return DbgNode->getNumOperands() == 7 && getNumHeaderFields() == 8;
377 }
378
379 bool DIObjCProperty::Verify() const {
380   if (!isObjCProperty())
381     return false;
382
383   // Don't worry about the rest of the strings for now.
384   return DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 6;
385 }
386
387 /// \brief Check if a field at position Elt of a MDNode is a MDNode.
388 static bool fieldIsMDNode(const MDNode *DbgNode, unsigned Elt) {
389   Metadata *Fld = getField(DbgNode, Elt);
390   return !Fld || isa<MDNode>(Fld);
391 }
392
393 /// \brief Check if a field at position Elt of a MDNode is a MDString.
394 static bool fieldIsMDString(const MDNode *DbgNode, unsigned Elt) {
395   Metadata *Fld = getField(DbgNode, Elt);
396   return !Fld || isa<MDString>(Fld);
397 }
398
399 /// \brief Check if a value can be a reference to a type.
400 static bool isTypeRef(const Metadata *MD) {
401   if (!MD)
402     return true;
403   if (auto *S = dyn_cast<MDString>(MD))
404     return !S->getString().empty();
405   if (auto *N = dyn_cast<MDNode>(MD))
406     return DIType(N).isType();
407   return false;
408 }
409
410 /// \brief Check if referenced field might be a type.
411 static bool fieldIsTypeRef(const MDNode *DbgNode, unsigned Elt) {
412   return isTypeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
413 }
414
415 /// \brief Check if a value can be a ScopeRef.
416 static bool isScopeRef(const Metadata *MD) {
417   if (!MD)
418     return true;
419   if (auto *S = dyn_cast<MDString>(MD))
420     return !S->getString().empty();
421   if (auto *N = dyn_cast<MDNode>(MD))
422     return DIScope(N).isScope();
423   return false;
424 }
425
426 /// \brief Check if a field at position Elt of a MDNode can be a ScopeRef.
427 static bool fieldIsScopeRef(const MDNode *DbgNode, unsigned Elt) {
428   return isScopeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
429 }
430
431 #ifndef NDEBUG
432 /// \brief Check if a value can be a DescriptorRef.
433 static bool isDescriptorRef(const Metadata *MD) {
434   if (!MD)
435     return true;
436   if (auto *S = dyn_cast<MDString>(MD))
437     return !S->getString().empty();
438   return isa<MDNode>(MD);
439 }
440 #endif
441
442 bool DIType::Verify() const {
443   if (!isType())
444     return false;
445   // Make sure Context @ field 2 is MDNode.
446   if (!fieldIsScopeRef(DbgNode, 2))
447     return false;
448
449   // FIXME: Sink this into the various subclass verifies.
450   uint16_t Tag = getTag();
451   if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
452       Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
453       Tag != dwarf::DW_TAG_ptr_to_member_type &&
454       Tag != dwarf::DW_TAG_reference_type &&
455       Tag != dwarf::DW_TAG_rvalue_reference_type &&
456       Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
457       Tag != dwarf::DW_TAG_enumeration_type &&
458       Tag != dwarf::DW_TAG_subroutine_type &&
459       Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
460       getFilename().empty())
461     return false;
462
463   // DIType is abstract, it should be a BasicType, a DerivedType or
464   // a CompositeType.
465   if (isBasicType())
466     return DIBasicType(DbgNode).Verify();
467   else if (isCompositeType())
468     return DICompositeType(DbgNode).Verify();
469   else if (isDerivedType())
470     return DIDerivedType(DbgNode).Verify();
471   else
472     return false;
473 }
474
475 bool DIBasicType::Verify() const {
476   return isBasicType() && DbgNode->getNumOperands() == 3 &&
477          getNumHeaderFields() == 8;
478 }
479
480 bool DIDerivedType::Verify() const {
481   // Make sure DerivedFrom @ field 3 is TypeRef.
482   if (!fieldIsTypeRef(DbgNode, 3))
483     return false;
484   if (getTag() == dwarf::DW_TAG_ptr_to_member_type)
485     // Make sure ClassType @ field 4 is a TypeRef.
486     if (!fieldIsTypeRef(DbgNode, 4))
487       return false;
488
489   return isDerivedType() && DbgNode->getNumOperands() >= 4 &&
490          DbgNode->getNumOperands() <= 8 && getNumHeaderFields() >= 7 &&
491          getNumHeaderFields() <= 8;
492 }
493
494 bool DICompositeType::Verify() const {
495   if (!isCompositeType())
496     return false;
497
498   // Make sure DerivedFrom @ field 3 and ContainingType @ field 5 are TypeRef.
499   if (!fieldIsTypeRef(DbgNode, 3))
500     return false;
501   if (!fieldIsTypeRef(DbgNode, 5))
502     return false;
503
504   // Make sure the type identifier at field 7 is MDString, it can be null.
505   if (!fieldIsMDString(DbgNode, 7))
506     return false;
507
508   // A subroutine type can't be both & and &&.
509   if (isLValueReference() && isRValueReference())
510     return false;
511
512   return DbgNode->getNumOperands() == 8 && getNumHeaderFields() == 8;
513 }
514
515 bool DISubprogram::Verify() const {
516   if (!isSubprogram())
517     return false;
518
519   // Make sure context @ field 2 is a ScopeRef and type @ field 3 is a MDNode.
520   if (!fieldIsScopeRef(DbgNode, 2))
521     return false;
522   if (!fieldIsMDNode(DbgNode, 3))
523     return false;
524   // Containing type @ field 4.
525   if (!fieldIsTypeRef(DbgNode, 4))
526     return false;
527
528   // A subprogram can't be both & and &&.
529   if (isLValueReference() && isRValueReference())
530     return false;
531
532   // If a DISubprogram has an llvm::Function*, then scope chains from all
533   // instructions within the function should lead to this DISubprogram.
534   if (auto *F = getFunction()) {
535     for (auto &BB : *F) {
536       for (auto &I : BB) {
537         DebugLoc DL = I.getDebugLoc();
538         if (DL.isUnknown())
539           continue;
540
541         MDNode *Scope = nullptr;
542         MDNode *IA = nullptr;
543         // walk the inlined-at scopes
544         while ((IA = DL.getInlinedAt()))
545           DL = DebugLoc::getFromDILocation(IA);
546         DL.getScopeAndInlinedAt(Scope, IA);
547         if (!Scope)
548           return false;
549         assert(!IA);
550         while (!DIDescriptor(Scope).isSubprogram()) {
551           DILexicalBlockFile D(Scope);
552           Scope = D.isLexicalBlockFile()
553                       ? D.getScope()
554                       : DebugLoc::getFromDILexicalBlock(Scope).getScope();
555           if (!Scope)
556             return false;
557         }
558         if (!DISubprogram(Scope).describes(F))
559           return false;
560       }
561     }
562   }
563   return DbgNode->getNumOperands() == 9 && getNumHeaderFields() == 12;
564 }
565
566 bool DIGlobalVariable::Verify() const {
567   if (!isGlobalVariable())
568     return false;
569
570   if (getDisplayName().empty())
571     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;
578   // Make sure StaticDataMemberDeclaration @ field 5 is MDNode.
579   if (!fieldIsMDNode(DbgNode, 5))
580     return false;
581
582   return DbgNode->getNumOperands() == 6 && getNumHeaderFields() == 7;
583 }
584
585 bool DIVariable::Verify() const {
586   if (!isVariable())
587     return false;
588
589   // Make sure context @ field 1 is an MDNode.
590   if (!fieldIsMDNode(DbgNode, 1))
591     return false;
592   // Make sure that type @ field 3 is a DITypeRef.
593   if (!fieldIsTypeRef(DbgNode, 3))
594     return false;
595
596   // Check the number of header fields, which is common between complex and
597   // simple variables.
598   if (getNumHeaderFields() != 4)
599     return false;
600
601   // Variable without an inline location.
602   if (DbgNode->getNumOperands() == 4)
603     return true;
604
605   // Variable with an inline location.
606   return getInlinedAt() != nullptr && DbgNode->getNumOperands() == 5;
607 }
608
609 bool DIExpression::Verify() const {
610   // Empty DIExpressions may be represented as a nullptr.
611   if (!DbgNode)
612     return true;
613
614   if (!(isExpression() && DbgNode->getNumOperands() == 1))
615     return false;
616
617   for (auto Op : *this)
618     switch (Op) {
619     case DW_OP_bit_piece:
620       // Must be the last element of the expression.
621       return std::distance(Op.getBase(), DIHeaderFieldIterator()) == 3;
622     case DW_OP_plus:
623       if (std::distance(Op.getBase(), DIHeaderFieldIterator()) < 2)
624         return false;
625       break;
626     case DW_OP_deref:
627       break;
628     default:
629       // Other operators are not yet supported by the backend.
630       return false;
631     }
632   return true;
633 }
634
635 bool DILocation::Verify() const {
636   return DbgNode && isa<MDLocation>(DbgNode);
637 }
638
639 bool DINameSpace::Verify() const {
640   if (!isNameSpace())
641     return false;
642   return DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 3;
643 }
644
645 MDNode *DIFile::getFileNode() const { return getNodeField(DbgNode, 1); }
646
647 bool DIFile::Verify() const {
648   return isFile() && DbgNode->getNumOperands() == 2;
649 }
650
651 bool DIEnumerator::Verify() const {
652   return isEnumerator() && DbgNode->getNumOperands() == 1 &&
653          getNumHeaderFields() == 3;
654 }
655
656 bool DISubrange::Verify() const {
657   return isSubrange() && DbgNode->getNumOperands() == 1 &&
658          getNumHeaderFields() == 3;
659 }
660
661 bool DILexicalBlock::Verify() const {
662   return isLexicalBlock() && DbgNode->getNumOperands() == 3 &&
663          getNumHeaderFields() == 4;
664 }
665
666 bool DILexicalBlockFile::Verify() const {
667   return isLexicalBlockFile() && DbgNode->getNumOperands() == 3 &&
668          getNumHeaderFields() == 2;
669 }
670
671 bool DITemplateTypeParameter::Verify() const {
672   return isTemplateTypeParameter() && DbgNode->getNumOperands() == 4 &&
673          getNumHeaderFields() == 4;
674 }
675
676 bool DITemplateValueParameter::Verify() const {
677   return isTemplateValueParameter() && DbgNode->getNumOperands() == 5 &&
678          getNumHeaderFields() == 4;
679 }
680
681 bool DIImportedEntity::Verify() const {
682   return isImportedEntity() && DbgNode->getNumOperands() == 3 &&
683          getNumHeaderFields() == 3;
684 }
685
686 MDNode *DIDerivedType::getObjCProperty() const {
687   return getNodeField(DbgNode, 4);
688 }
689
690 MDString *DICompositeType::getIdentifier() const {
691   return cast_or_null<MDString>(getField(DbgNode, 7));
692 }
693
694 #ifndef NDEBUG
695 static void VerifySubsetOf(const MDNode *LHS, const MDNode *RHS) {
696   for (unsigned i = 0; i != LHS->getNumOperands(); ++i) {
697     // Skip the 'empty' list (that's a single i32 0, rather than truly empty).
698     if (i == 0 && mdconst::hasa<ConstantInt>(LHS->getOperand(i)))
699       continue;
700     const MDNode *E = cast<MDNode>(LHS->getOperand(i));
701     bool found = false;
702     for (unsigned j = 0; !found && j != RHS->getNumOperands(); ++j)
703       found = (E == cast<MDNode>(RHS->getOperand(j)));
704     assert(found && "Losing a member during member list replacement");
705   }
706 }
707 #endif
708
709 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
710   TrackingMDNodeRef N(*this);
711   if (Elements) {
712 #ifndef NDEBUG
713     // Check that the new list of members contains all the old members as well.
714     if (const MDNode *El = cast_or_null<MDNode>(N->getOperand(4)))
715       VerifySubsetOf(El, Elements);
716 #endif
717     N->replaceOperandWith(4, Elements);
718   }
719   if (TParams)
720     N->replaceOperandWith(6, TParams);
721   DbgNode = N;
722 }
723
724 DIScopeRef DIScope::getRef() const {
725   if (!isCompositeType())
726     return DIScopeRef(*this);
727   DICompositeType DTy(DbgNode);
728   if (!DTy.getIdentifier())
729     return DIScopeRef(*this);
730   return DIScopeRef(DTy.getIdentifier());
731 }
732
733 void DICompositeType::setContainingType(DICompositeType ContainingType) {
734   TrackingMDNodeRef N(*this);
735   N->replaceOperandWith(5, ContainingType.getRef());
736   DbgNode = N;
737 }
738
739 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
740   assert(CurFn && "Invalid function");
741   if (!getContext().isSubprogram())
742     return false;
743   // This variable is not inlined function argument if its scope
744   // does not describe current function.
745   return !DISubprogram(getContext()).describes(CurFn);
746 }
747
748 bool DISubprogram::describes(const Function *F) {
749   assert(F && "Invalid function");
750   if (F == getFunction())
751     return true;
752   StringRef Name = getLinkageName();
753   if (Name.empty())
754     Name = getName();
755   if (F->getName() == Name)
756     return true;
757   return false;
758 }
759
760 MDNode *DISubprogram::getVariablesNodes() const {
761   return getNodeField(DbgNode, 8);
762 }
763
764 DIArray DISubprogram::getVariables() const {
765   return DIArray(getNodeField(DbgNode, 8));
766 }
767
768 Metadata *DITemplateValueParameter::getValue() const {
769   return DbgNode->getOperand(3);
770 }
771
772 DIScopeRef DIScope::getContext() const {
773
774   if (isType())
775     return DIType(DbgNode).getContext();
776
777   if (isSubprogram())
778     return DIScopeRef(DISubprogram(DbgNode).getContext());
779
780   if (isLexicalBlock())
781     return DIScopeRef(DILexicalBlock(DbgNode).getContext());
782
783   if (isLexicalBlockFile())
784     return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
785
786   if (isNameSpace())
787     return DIScopeRef(DINameSpace(DbgNode).getContext());
788
789   assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
790   return DIScopeRef(nullptr);
791 }
792
793 StringRef DIScope::getName() const {
794   if (isType())
795     return DIType(DbgNode).getName();
796   if (isSubprogram())
797     return DISubprogram(DbgNode).getName();
798   if (isNameSpace())
799     return DINameSpace(DbgNode).getName();
800   assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
801           isCompileUnit()) &&
802          "Unhandled type of scope.");
803   return StringRef();
804 }
805
806 StringRef DIScope::getFilename() const {
807   if (!DbgNode)
808     return StringRef();
809   return ::getStringField(getNodeField(DbgNode, 1), 0);
810 }
811
812 StringRef DIScope::getDirectory() const {
813   if (!DbgNode)
814     return StringRef();
815   return ::getStringField(getNodeField(DbgNode, 1), 1);
816 }
817
818 DIArray DICompileUnit::getEnumTypes() const {
819   if (!DbgNode || DbgNode->getNumOperands() < 7)
820     return DIArray();
821
822   return DIArray(getNodeField(DbgNode, 2));
823 }
824
825 DIArray DICompileUnit::getRetainedTypes() const {
826   if (!DbgNode || DbgNode->getNumOperands() < 7)
827     return DIArray();
828
829   return DIArray(getNodeField(DbgNode, 3));
830 }
831
832 DIArray DICompileUnit::getSubprograms() const {
833   if (!DbgNode || DbgNode->getNumOperands() < 7)
834     return DIArray();
835
836   return DIArray(getNodeField(DbgNode, 4));
837 }
838
839 DIArray DICompileUnit::getGlobalVariables() const {
840   if (!DbgNode || DbgNode->getNumOperands() < 7)
841     return DIArray();
842
843   return DIArray(getNodeField(DbgNode, 5));
844 }
845
846 DIArray DICompileUnit::getImportedEntities() const {
847   if (!DbgNode || DbgNode->getNumOperands() < 7)
848     return DIArray();
849
850   return DIArray(getNodeField(DbgNode, 6));
851 }
852
853 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
854   assert(Verify() && "Expected compile unit");
855   if (Subprograms == getSubprograms())
856     return;
857
858   const_cast<MDNode *>(DbgNode)->replaceOperandWith(4, Subprograms);
859 }
860
861 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
862   assert(Verify() && "Expected compile unit");
863   if (GlobalVariables == getGlobalVariables())
864     return;
865
866   const_cast<MDNode *>(DbgNode)->replaceOperandWith(5, GlobalVariables);
867 }
868
869 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
870                                         DILexicalBlockFile NewScope) {
871   assert(Verify());
872   assert(NewScope && "Expected valid scope");
873
874   const auto *Old = cast<MDLocation>(DbgNode);
875   return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
876                                     NewScope, Old->getInlinedAt()));
877 }
878
879 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
880   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
881   return ++Ctx.pImpl->DiscriminatorTable[Key];
882 }
883
884 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
885                                        LLVMContext &VMContext) {
886   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
887   if (!InlinedScope)
888     return cleanseInlinedVariable(DV, VMContext);
889
890   // Insert inlined scope.
891   SmallVector<Metadata *, 8> Elts(DV->op_begin(),
892                                   DV->op_begin() + DIVariableInlinedAtIndex);
893   Elts.push_back(InlinedScope);
894
895   DIVariable Inlined(MDNode::get(VMContext, Elts));
896   assert(Inlined.Verify() && "Expected to create a DIVariable");
897   return Inlined;
898 }
899
900 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
901   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
902   if (!DIVariable(DV).getInlinedAt())
903     return DIVariable(DV);
904
905   // Remove inlined scope.
906   SmallVector<Metadata *, 8> Elts(DV->op_begin(),
907                                   DV->op_begin() + DIVariableInlinedAtIndex);
908
909   DIVariable Cleansed(MDNode::get(VMContext, Elts));
910   assert(Cleansed.Verify() && "Expected to create a DIVariable");
911   return Cleansed;
912 }
913
914 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
915   DIDescriptor D(Scope);
916   if (D.isSubprogram())
917     return DISubprogram(Scope);
918
919   if (D.isLexicalBlockFile())
920     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
921
922   if (D.isLexicalBlock())
923     return getDISubprogram(DILexicalBlock(Scope).getContext());
924
925   return DISubprogram();
926 }
927
928 DISubprogram llvm::getDISubprogram(const Function *F) {
929   // We look for the first instr that has a debug annotation leading back to F.
930   for (auto &BB : *F) {
931     auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
932       return !Inst.getDebugLoc().isUnknown();
933     });
934     if (Inst == BB.end())
935       continue;
936     DebugLoc DLoc = Inst->getDebugLoc();
937     const MDNode *Scope = DLoc.getScopeNode();
938     DISubprogram Subprogram = getDISubprogram(Scope);
939     return Subprogram.describes(F) ? Subprogram : DISubprogram();
940   }
941
942   return DISubprogram();
943 }
944
945 DICompositeType llvm::getDICompositeType(DIType T) {
946   if (T.isCompositeType())
947     return DICompositeType(T);
948
949   if (T.isDerivedType()) {
950     // This function is currently used by dragonegg and dragonegg does
951     // not generate identifier for types, so using an empty map to resolve
952     // DerivedFrom should be fine.
953     DITypeIdentifierMap EmptyMap;
954     return getDICompositeType(
955         DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
956   }
957
958   return DICompositeType();
959 }
960
961 DITypeIdentifierMap
962 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
963   DITypeIdentifierMap Map;
964   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
965     DICompileUnit CU(CU_Nodes->getOperand(CUi));
966     DIArray Retain = CU.getRetainedTypes();
967     for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
968       if (!Retain.getElement(Ti).isCompositeType())
969         continue;
970       DICompositeType Ty(Retain.getElement(Ti));
971       if (MDString *TypeId = Ty.getIdentifier()) {
972         // Definition has priority over declaration.
973         // Try to insert (TypeId, Ty) to Map.
974         std::pair<DITypeIdentifierMap::iterator, bool> P =
975             Map.insert(std::make_pair(TypeId, Ty));
976         // If TypeId already exists in Map and this is a definition, replace
977         // whatever we had (declaration or definition) with the definition.
978         if (!P.second && !Ty.isForwardDecl())
979           P.first->second = Ty;
980       }
981     }
982   }
983   return Map;
984 }
985
986 //===----------------------------------------------------------------------===//
987 // DebugInfoFinder implementations.
988 //===----------------------------------------------------------------------===//
989
990 void DebugInfoFinder::reset() {
991   CUs.clear();
992   SPs.clear();
993   GVs.clear();
994   TYs.clear();
995   Scopes.clear();
996   NodesSeen.clear();
997   TypeIdentifierMap.clear();
998   TypeMapInitialized = false;
999 }
1000
1001 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
1002   if (!TypeMapInitialized)
1003     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
1004       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
1005       TypeMapInitialized = true;
1006     }
1007 }
1008
1009 void DebugInfoFinder::processModule(const Module &M) {
1010   InitializeTypeMap(M);
1011   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
1012     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
1013       DICompileUnit CU(CU_Nodes->getOperand(i));
1014       addCompileUnit(CU);
1015       DIArray GVs = CU.getGlobalVariables();
1016       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
1017         DIGlobalVariable DIG(GVs.getElement(i));
1018         if (addGlobalVariable(DIG)) {
1019           processScope(DIG.getContext());
1020           processType(DIG.getType().resolve(TypeIdentifierMap));
1021         }
1022       }
1023       DIArray SPs = CU.getSubprograms();
1024       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
1025         processSubprogram(DISubprogram(SPs.getElement(i)));
1026       DIArray EnumTypes = CU.getEnumTypes();
1027       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
1028         processType(DIType(EnumTypes.getElement(i)));
1029       DIArray RetainedTypes = CU.getRetainedTypes();
1030       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
1031         processType(DIType(RetainedTypes.getElement(i)));
1032       DIArray Imports = CU.getImportedEntities();
1033       for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
1034         DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
1035         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
1036         if (Entity.isType())
1037           processType(DIType(Entity));
1038         else if (Entity.isSubprogram())
1039           processSubprogram(DISubprogram(Entity));
1040         else if (Entity.isNameSpace())
1041           processScope(DINameSpace(Entity).getContext());
1042       }
1043     }
1044   }
1045 }
1046
1047 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
1048   if (!Loc)
1049     return;
1050   InitializeTypeMap(M);
1051   processScope(Loc.getScope());
1052   processLocation(M, Loc.getOrigLocation());
1053 }
1054
1055 void DebugInfoFinder::processType(DIType DT) {
1056   if (!addType(DT))
1057     return;
1058   processScope(DT.getContext().resolve(TypeIdentifierMap));
1059   if (DT.isCompositeType()) {
1060     DICompositeType DCT(DT);
1061     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1062     if (DT.isSubroutineType()) {
1063       DITypeArray DTA = DISubroutineType(DT).getTypeArray();
1064       for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
1065         processType(DTA.getElement(i).resolve(TypeIdentifierMap));
1066       return;
1067     }
1068     DIArray DA = DCT.getElements();
1069     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1070       DIDescriptor D = DA.getElement(i);
1071       if (D.isType())
1072         processType(DIType(D));
1073       else if (D.isSubprogram())
1074         processSubprogram(DISubprogram(D));
1075     }
1076   } else if (DT.isDerivedType()) {
1077     DIDerivedType DDT(DT);
1078     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1079   }
1080 }
1081
1082 void DebugInfoFinder::processScope(DIScope Scope) {
1083   if (Scope.isType()) {
1084     DIType Ty(Scope);
1085     processType(Ty);
1086     return;
1087   }
1088   if (Scope.isCompileUnit()) {
1089     addCompileUnit(DICompileUnit(Scope));
1090     return;
1091   }
1092   if (Scope.isSubprogram()) {
1093     processSubprogram(DISubprogram(Scope));
1094     return;
1095   }
1096   if (!addScope(Scope))
1097     return;
1098   if (Scope.isLexicalBlock()) {
1099     DILexicalBlock LB(Scope);
1100     processScope(LB.getContext());
1101   } else if (Scope.isLexicalBlockFile()) {
1102     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
1103     processScope(LBF.getScope());
1104   } else if (Scope.isNameSpace()) {
1105     DINameSpace NS(Scope);
1106     processScope(NS.getContext());
1107   }
1108 }
1109
1110 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1111   if (!addSubprogram(SP))
1112     return;
1113   processScope(SP.getContext().resolve(TypeIdentifierMap));
1114   processType(SP.getType());
1115   DIArray TParams = SP.getTemplateParams();
1116   for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
1117     DIDescriptor Element = TParams.getElement(I);
1118     if (Element.isTemplateTypeParameter()) {
1119       DITemplateTypeParameter TType(Element);
1120       processType(TType.getType().resolve(TypeIdentifierMap));
1121     } else if (Element.isTemplateValueParameter()) {
1122       DITemplateValueParameter TVal(Element);
1123       processType(TVal.getType().resolve(TypeIdentifierMap));
1124     }
1125   }
1126 }
1127
1128 void DebugInfoFinder::processDeclare(const Module &M,
1129                                      const DbgDeclareInst *DDI) {
1130   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1131   if (!N)
1132     return;
1133   InitializeTypeMap(M);
1134
1135   DIDescriptor DV(N);
1136   if (!DV.isVariable())
1137     return;
1138
1139   if (!NodesSeen.insert(DV).second)
1140     return;
1141   processScope(DIVariable(N).getContext());
1142   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1143 }
1144
1145 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
1146   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
1147   if (!N)
1148     return;
1149   InitializeTypeMap(M);
1150
1151   DIDescriptor DV(N);
1152   if (!DV.isVariable())
1153     return;
1154
1155   if (!NodesSeen.insert(DV).second)
1156     return;
1157   processScope(DIVariable(N).getContext());
1158   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1159 }
1160
1161 bool DebugInfoFinder::addType(DIType DT) {
1162   if (!DT)
1163     return false;
1164
1165   if (!NodesSeen.insert(DT).second)
1166     return false;
1167
1168   TYs.push_back(DT);
1169   return true;
1170 }
1171
1172 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1173   if (!CU)
1174     return false;
1175   if (!NodesSeen.insert(CU).second)
1176     return false;
1177
1178   CUs.push_back(CU);
1179   return true;
1180 }
1181
1182 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1183   if (!DIG)
1184     return false;
1185
1186   if (!NodesSeen.insert(DIG).second)
1187     return false;
1188
1189   GVs.push_back(DIG);
1190   return true;
1191 }
1192
1193 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1194   if (!SP)
1195     return false;
1196
1197   if (!NodesSeen.insert(SP).second)
1198     return false;
1199
1200   SPs.push_back(SP);
1201   return true;
1202 }
1203
1204 bool DebugInfoFinder::addScope(DIScope Scope) {
1205   if (!Scope)
1206     return false;
1207   // FIXME: Ocaml binding generates a scope with no content, we treat it
1208   // as null for now.
1209   if (Scope->getNumOperands() == 0)
1210     return false;
1211   if (!NodesSeen.insert(Scope).second)
1212     return false;
1213   Scopes.push_back(Scope);
1214   return true;
1215 }
1216
1217 //===----------------------------------------------------------------------===//
1218 // DIDescriptor: dump routines for all descriptors.
1219 //===----------------------------------------------------------------------===//
1220
1221 void DIDescriptor::dump() const {
1222   print(dbgs());
1223   dbgs() << '\n';
1224 }
1225
1226 void DIDescriptor::print(raw_ostream &OS) const {
1227   if (!DbgNode)
1228     return;
1229
1230   if (const char *Tag = dwarf::TagString(getTag()))
1231     OS << "[ " << Tag << " ]";
1232
1233   if (this->isSubrange()) {
1234     DISubrange(DbgNode).printInternal(OS);
1235   } else if (this->isCompileUnit()) {
1236     DICompileUnit(DbgNode).printInternal(OS);
1237   } else if (this->isFile()) {
1238     DIFile(DbgNode).printInternal(OS);
1239   } else if (this->isEnumerator()) {
1240     DIEnumerator(DbgNode).printInternal(OS);
1241   } else if (this->isBasicType()) {
1242     DIType(DbgNode).printInternal(OS);
1243   } else if (this->isDerivedType()) {
1244     DIDerivedType(DbgNode).printInternal(OS);
1245   } else if (this->isCompositeType()) {
1246     DICompositeType(DbgNode).printInternal(OS);
1247   } else if (this->isSubprogram()) {
1248     DISubprogram(DbgNode).printInternal(OS);
1249   } else if (this->isGlobalVariable()) {
1250     DIGlobalVariable(DbgNode).printInternal(OS);
1251   } else if (this->isVariable()) {
1252     DIVariable(DbgNode).printInternal(OS);
1253   } else if (this->isObjCProperty()) {
1254     DIObjCProperty(DbgNode).printInternal(OS);
1255   } else if (this->isNameSpace()) {
1256     DINameSpace(DbgNode).printInternal(OS);
1257   } else if (this->isScope()) {
1258     DIScope(DbgNode).printInternal(OS);
1259   } else if (this->isExpression()) {
1260     DIExpression(DbgNode).printInternal(OS);
1261   }
1262 }
1263
1264 void DISubrange::printInternal(raw_ostream &OS) const {
1265   int64_t Count = getCount();
1266   if (Count != -1)
1267     OS << " [" << getLo() << ", " << Count - 1 << ']';
1268   else
1269     OS << " [unbounded]";
1270 }
1271
1272 void DIScope::printInternal(raw_ostream &OS) const {
1273   OS << " [" << getDirectory() << "/" << getFilename() << ']';
1274 }
1275
1276 void DICompileUnit::printInternal(raw_ostream &OS) const {
1277   DIScope::printInternal(OS);
1278   OS << " [";
1279   unsigned Lang = getLanguage();
1280   if (const char *LangStr = dwarf::LanguageString(Lang))
1281     OS << LangStr;
1282   else
1283     (OS << "lang 0x").write_hex(Lang);
1284   OS << ']';
1285 }
1286
1287 void DIEnumerator::printInternal(raw_ostream &OS) const {
1288   OS << " [" << getName() << " :: " << getEnumValue() << ']';
1289 }
1290
1291 void DIType::printInternal(raw_ostream &OS) const {
1292   if (!DbgNode)
1293     return;
1294
1295   StringRef Res = getName();
1296   if (!Res.empty())
1297     OS << " [" << Res << "]";
1298
1299   // TODO: Print context?
1300
1301   OS << " [line " << getLineNumber() << ", size " << getSizeInBits()
1302      << ", align " << getAlignInBits() << ", offset " << getOffsetInBits();
1303   if (isBasicType())
1304     if (const char *Enc =
1305             dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
1306       OS << ", enc " << Enc;
1307   OS << "]";
1308
1309   if (isPrivate())
1310     OS << " [private]";
1311   else if (isProtected())
1312     OS << " [protected]";
1313   else if (isPublic())
1314     OS << " [public]";
1315
1316   if (isArtificial())
1317     OS << " [artificial]";
1318
1319   if (isForwardDecl())
1320     OS << " [decl]";
1321   else if (getTag() == dwarf::DW_TAG_structure_type ||
1322            getTag() == dwarf::DW_TAG_union_type ||
1323            getTag() == dwarf::DW_TAG_enumeration_type ||
1324            getTag() == dwarf::DW_TAG_class_type)
1325     OS << " [def]";
1326   if (isVector())
1327     OS << " [vector]";
1328   if (isStaticMember())
1329     OS << " [static]";
1330
1331   if (isLValueReference())
1332     OS << " [reference]";
1333
1334   if (isRValueReference())
1335     OS << " [rvalue reference]";
1336 }
1337
1338 void DIDerivedType::printInternal(raw_ostream &OS) const {
1339   DIType::printInternal(OS);
1340   OS << " [from " << getTypeDerivedFrom().getName() << ']';
1341 }
1342
1343 void DICompositeType::printInternal(raw_ostream &OS) const {
1344   DIType::printInternal(OS);
1345   DIArray A = getElements();
1346   OS << " [" << A.getNumElements() << " elements]";
1347 }
1348
1349 void DINameSpace::printInternal(raw_ostream &OS) const {
1350   StringRef Name = getName();
1351   if (!Name.empty())
1352     OS << " [" << Name << ']';
1353
1354   OS << " [line " << getLineNumber() << ']';
1355 }
1356
1357 void DISubprogram::printInternal(raw_ostream &OS) const {
1358   // TODO : Print context
1359   OS << " [line " << getLineNumber() << ']';
1360
1361   if (isLocalToUnit())
1362     OS << " [local]";
1363
1364   if (isDefinition())
1365     OS << " [def]";
1366
1367   if (getScopeLineNumber() != getLineNumber())
1368     OS << " [scope " << getScopeLineNumber() << "]";
1369
1370   if (isPrivate())
1371     OS << " [private]";
1372   else if (isProtected())
1373     OS << " [protected]";
1374   else if (isPublic())
1375     OS << " [public]";
1376
1377   if (isLValueReference())
1378     OS << " [reference]";
1379
1380   if (isRValueReference())
1381     OS << " [rvalue reference]";
1382
1383   StringRef Res = getName();
1384   if (!Res.empty())
1385     OS << " [" << Res << ']';
1386 }
1387
1388 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
1389   StringRef Res = getName();
1390   if (!Res.empty())
1391     OS << " [" << Res << ']';
1392
1393   OS << " [line " << getLineNumber() << ']';
1394
1395   // TODO : Print context
1396
1397   if (isLocalToUnit())
1398     OS << " [local]";
1399
1400   if (isDefinition())
1401     OS << " [def]";
1402 }
1403
1404 void DIVariable::printInternal(raw_ostream &OS) const {
1405   StringRef Res = getName();
1406   if (!Res.empty())
1407     OS << " [" << Res << ']';
1408
1409   OS << " [line " << getLineNumber() << ']';
1410 }
1411
1412 void DIExpression::printInternal(raw_ostream &OS) const {
1413   for (auto Op : *this) {
1414     OS << " [" << OperationEncodingString(Op);
1415     switch (Op) {
1416     case DW_OP_plus: {
1417       OS << " " << Op.getArg(1);
1418       break;
1419     }
1420     case DW_OP_bit_piece: {
1421       OS << " offset=" << Op.getArg(1) << ", size=" << Op.getArg(2);
1422       break;
1423     }
1424     case DW_OP_deref:
1425       // No arguments.
1426       break;
1427     default:
1428       llvm_unreachable("unhandled operation");
1429     }
1430     OS << "]";
1431   }
1432 }
1433
1434 void DIObjCProperty::printInternal(raw_ostream &OS) const {
1435   StringRef Name = getObjCPropertyName();
1436   if (!Name.empty())
1437     OS << " [" << Name << ']';
1438
1439   OS << " [line " << getLineNumber() << ", properties " << getUnsignedField(6)
1440      << ']';
1441 }
1442
1443 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
1444                           const LLVMContext &Ctx) {
1445   if (!DL.isUnknown()) { // Print source line info.
1446     DIScope Scope(DL.getScope(Ctx));
1447     assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
1448     // Omit the directory, because it's likely to be long and uninteresting.
1449     CommentOS << Scope.getFilename();
1450     CommentOS << ':' << DL.getLine();
1451     if (DL.getCol() != 0)
1452       CommentOS << ':' << DL.getCol();
1453     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1454     if (!InlinedAtDL.isUnknown()) {
1455       CommentOS << " @[ ";
1456       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
1457       CommentOS << " ]";
1458     }
1459   }
1460 }
1461
1462 void DIVariable::printExtendedName(raw_ostream &OS) const {
1463   const LLVMContext &Ctx = DbgNode->getContext();
1464   StringRef Res = getName();
1465   if (!Res.empty())
1466     OS << Res << "," << getLineNumber();
1467   if (MDNode *InlinedAt = getInlinedAt()) {
1468     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1469     if (!InlinedAtDL.isUnknown()) {
1470       OS << " @[";
1471       printDebugLoc(InlinedAtDL, OS, Ctx);
1472       OS << "]";
1473     }
1474   }
1475 }
1476
1477 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V) : Val(V) {
1478   assert(isDescriptorRef(V) &&
1479          "DIDescriptorRef should be a MDString or MDNode");
1480 }
1481 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
1482   assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
1483 }
1484 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
1485   assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
1486 }
1487
1488 template <>
1489 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const {
1490   return DIDescriptorRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1491 }
1492 template <>
1493 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
1494   return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1495 }
1496 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
1497   return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1498 }
1499
1500 bool llvm::StripDebugInfo(Module &M) {
1501   bool Changed = false;
1502
1503   // Remove all of the calls to the debugger intrinsics, and remove them from
1504   // the module.
1505   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
1506     while (!Declare->use_empty()) {
1507       CallInst *CI = cast<CallInst>(Declare->user_back());
1508       CI->eraseFromParent();
1509     }
1510     Declare->eraseFromParent();
1511     Changed = true;
1512   }
1513
1514   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
1515     while (!DbgVal->use_empty()) {
1516       CallInst *CI = cast<CallInst>(DbgVal->user_back());
1517       CI->eraseFromParent();
1518     }
1519     DbgVal->eraseFromParent();
1520     Changed = true;
1521   }
1522
1523   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
1524          NME = M.named_metadata_end(); NMI != NME;) {
1525     NamedMDNode *NMD = NMI;
1526     ++NMI;
1527     if (NMD->getName().startswith("llvm.dbg.")) {
1528       NMD->eraseFromParent();
1529       Changed = true;
1530     }
1531   }
1532
1533   for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
1534     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
1535          ++FI)
1536       for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
1537            ++BI) {
1538         if (!BI->getDebugLoc().isUnknown()) {
1539           Changed = true;
1540           BI->setDebugLoc(DebugLoc());
1541         }
1542       }
1543
1544   return Changed;
1545 }
1546
1547 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
1548   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
1549           M.getModuleFlag("Debug Info Version")))
1550     return Val->getZExtValue();
1551   return 0;
1552 }
1553
1554 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
1555 llvm::makeSubprogramMap(const Module &M) {
1556   DenseMap<const Function *, DISubprogram> R;
1557
1558   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
1559   if (!CU_Nodes)
1560     return R;
1561
1562   for (MDNode *N : CU_Nodes->operands()) {
1563     DICompileUnit CUNode(N);
1564     DIArray SPs = CUNode.getSubprograms();
1565     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
1566       DISubprogram SP(SPs.getElement(i));
1567       if (Function *F = SP.getFunction())
1568         R.insert(std::make_pair(F, SP));
1569     }
1570   }
1571   return R;
1572 }