76b21d8d09dc771b8abd9dc456372a440acd8561
[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 ///
389 /// We currently allow an empty string and an integer.
390 /// But we don't allow a non-empty string in a MDNode field.
391 static bool fieldIsMDNode(const MDNode *DbgNode, unsigned Elt) {
392   // FIXME: This function should return true, if the field is null or the field
393   // is indeed a MDNode: return !Fld || isa<MDNode>(Fld).
394   Metadata *Fld = getField(DbgNode, Elt);
395   if (Fld && isa<MDString>(Fld) && !cast<MDString>(Fld)->getString().empty())
396     return false;
397   return true;
398 }
399
400 /// \brief Check if a field at position Elt of a MDNode is a MDString.
401 static bool fieldIsMDString(const MDNode *DbgNode, unsigned Elt) {
402   Metadata *Fld = getField(DbgNode, Elt);
403   return !Fld || isa<MDString>(Fld);
404 }
405
406 /// \brief Check if a value can be a reference to a type.
407 static bool isTypeRef(const Metadata *MD) {
408   if (!MD)
409     return true;
410   if (auto *S = dyn_cast<MDString>(MD))
411     return !S->getString().empty();
412   if (auto *N = dyn_cast<MDNode>(MD))
413     return DIType(N).isType();
414   return false;
415 }
416
417 /// \brief Check if referenced field might be a type.
418 static bool fieldIsTypeRef(const MDNode *DbgNode, unsigned Elt) {
419   return isTypeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
420 }
421
422 /// \brief Check if a value can be a ScopeRef.
423 static bool isScopeRef(const Metadata *MD) {
424   if (!MD)
425     return true;
426   if (auto *S = dyn_cast<MDString>(MD))
427     return !S->getString().empty();
428   return isa<MDNode>(MD);
429 }
430
431 /// \brief Check if a field at position Elt of a MDNode can be a ScopeRef.
432 static bool fieldIsScopeRef(const MDNode *DbgNode, unsigned Elt) {
433   return isScopeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
434 }
435
436 bool DIType::Verify() const {
437   if (!isType())
438     return false;
439   // Make sure Context @ field 2 is MDNode.
440   if (!fieldIsScopeRef(DbgNode, 2))
441     return false;
442
443   // FIXME: Sink this into the various subclass verifies.
444   uint16_t Tag = getTag();
445   if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
446       Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
447       Tag != dwarf::DW_TAG_ptr_to_member_type &&
448       Tag != dwarf::DW_TAG_reference_type &&
449       Tag != dwarf::DW_TAG_rvalue_reference_type &&
450       Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
451       Tag != dwarf::DW_TAG_enumeration_type &&
452       Tag != dwarf::DW_TAG_subroutine_type &&
453       Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
454       getFilename().empty())
455     return false;
456
457   // DIType is abstract, it should be a BasicType, a DerivedType or
458   // a CompositeType.
459   if (isBasicType())
460     return DIBasicType(DbgNode).Verify();
461   else if (isCompositeType())
462     return DICompositeType(DbgNode).Verify();
463   else if (isDerivedType())
464     return DIDerivedType(DbgNode).Verify();
465   else
466     return false;
467 }
468
469 bool DIBasicType::Verify() const {
470   return isBasicType() && DbgNode->getNumOperands() == 3 &&
471          getNumHeaderFields() == 8;
472 }
473
474 bool DIDerivedType::Verify() const {
475   // Make sure DerivedFrom @ field 3 is TypeRef.
476   if (!fieldIsTypeRef(DbgNode, 3))
477     return false;
478   if (getTag() == dwarf::DW_TAG_ptr_to_member_type)
479     // Make sure ClassType @ field 4 is a TypeRef.
480     if (!fieldIsTypeRef(DbgNode, 4))
481       return false;
482
483   return isDerivedType() && DbgNode->getNumOperands() >= 4 &&
484          DbgNode->getNumOperands() <= 8 && getNumHeaderFields() >= 7 &&
485          getNumHeaderFields() <= 8;
486 }
487
488 bool DICompositeType::Verify() const {
489   if (!isCompositeType())
490     return false;
491
492   // Make sure DerivedFrom @ field 3 and ContainingType @ field 5 are TypeRef.
493   if (!fieldIsTypeRef(DbgNode, 3))
494     return false;
495   if (!fieldIsTypeRef(DbgNode, 5))
496     return false;
497
498   // Make sure the type identifier at field 7 is MDString, it can be null.
499   if (!fieldIsMDString(DbgNode, 7))
500     return false;
501
502   // A subroutine type can't be both & and &&.
503   if (isLValueReference() && isRValueReference())
504     return false;
505
506   return DbgNode->getNumOperands() == 8 && getNumHeaderFields() == 8;
507 }
508
509 bool DISubprogram::Verify() const {
510   if (!isSubprogram())
511     return false;
512
513   // Make sure context @ field 2 is a ScopeRef and type @ field 3 is a MDNode.
514   if (!fieldIsScopeRef(DbgNode, 2))
515     return false;
516   if (!fieldIsMDNode(DbgNode, 3))
517     return false;
518   // Containing type @ field 4.
519   if (!fieldIsTypeRef(DbgNode, 4))
520     return false;
521
522   // A subprogram can't be both & and &&.
523   if (isLValueReference() && isRValueReference())
524     return false;
525
526   // If a DISubprogram has an llvm::Function*, then scope chains from all
527   // instructions within the function should lead to this DISubprogram.
528   if (auto *F = getFunction()) {
529     for (auto &BB : *F) {
530       for (auto &I : BB) {
531         DebugLoc DL = I.getDebugLoc();
532         if (DL.isUnknown())
533           continue;
534
535         MDNode *Scope = nullptr;
536         MDNode *IA = nullptr;
537         // walk the inlined-at scopes
538         while ((IA = DL.getInlinedAt()))
539           DL = DebugLoc::getFromDILocation(IA);
540         DL.getScopeAndInlinedAt(Scope, IA);
541         if (!Scope)
542           return false;
543         assert(!IA);
544         while (!DIDescriptor(Scope).isSubprogram()) {
545           DILexicalBlockFile D(Scope);
546           Scope = D.isLexicalBlockFile()
547                       ? D.getScope()
548                       : DebugLoc::getFromDILexicalBlock(Scope).getScope();
549           if (!Scope)
550             return false;
551         }
552         if (!DISubprogram(Scope).describes(F))
553           return false;
554       }
555     }
556   }
557   return DbgNode->getNumOperands() == 9 && getNumHeaderFields() == 12;
558 }
559
560 bool DIGlobalVariable::Verify() const {
561   if (!isGlobalVariable())
562     return false;
563
564   if (getDisplayName().empty())
565     return false;
566   // Make sure context @ field 1 is an MDNode.
567   if (!fieldIsMDNode(DbgNode, 1))
568     return false;
569   // Make sure that type @ field 3 is a DITypeRef.
570   if (!fieldIsTypeRef(DbgNode, 3))
571     return false;
572   // Make sure StaticDataMemberDeclaration @ field 5 is MDNode.
573   if (!fieldIsMDNode(DbgNode, 5))
574     return false;
575
576   return DbgNode->getNumOperands() == 6 && getNumHeaderFields() == 7;
577 }
578
579 bool DIVariable::Verify() const {
580   if (!isVariable())
581     return false;
582
583   // Make sure context @ field 1 is an MDNode.
584   if (!fieldIsMDNode(DbgNode, 1))
585     return false;
586   // Make sure that type @ field 3 is a DITypeRef.
587   if (!fieldIsTypeRef(DbgNode, 3))
588     return false;
589
590   // Check the number of header fields, which is common between complex and
591   // simple variables.
592   if (getNumHeaderFields() != 4)
593     return false;
594
595   // Variable without an inline location.
596   if (DbgNode->getNumOperands() == 4)
597     return true;
598
599   // Variable with an inline location.
600   return getInlinedAt() != nullptr && DbgNode->getNumOperands() == 5;
601 }
602
603 bool DIExpression::Verify() const {
604   // Empty DIExpressions may be represented as a nullptr.
605   if (!DbgNode)
606     return true;
607
608   if (!(isExpression() && DbgNode->getNumOperands() == 1))
609     return false;
610
611   for (auto Op : *this)
612     switch (Op) {
613     case DW_OP_bit_piece:
614       // Must be the last element of the expression.
615       return std::distance(Op.getBase(), DIHeaderFieldIterator()) == 3;
616     case DW_OP_plus:
617       if (std::distance(Op.getBase(), DIHeaderFieldIterator()) < 2)
618         return false;
619       break;
620     case DW_OP_deref:
621       break;
622     default:
623       // Other operators are not yet supported by the backend.
624       return false;
625     }
626   return true;
627 }
628
629 bool DILocation::Verify() const {
630   return DbgNode && isa<MDLocation>(DbgNode);
631 }
632
633 bool DINameSpace::Verify() const {
634   if (!isNameSpace())
635     return false;
636   return DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 3;
637 }
638
639 MDNode *DIFile::getFileNode() const { return getNodeField(DbgNode, 1); }
640
641 bool DIFile::Verify() const {
642   return isFile() && DbgNode->getNumOperands() == 2;
643 }
644
645 bool DIEnumerator::Verify() const {
646   return isEnumerator() && DbgNode->getNumOperands() == 1 &&
647          getNumHeaderFields() == 3;
648 }
649
650 bool DISubrange::Verify() const {
651   return isSubrange() && DbgNode->getNumOperands() == 1 &&
652          getNumHeaderFields() == 3;
653 }
654
655 bool DILexicalBlock::Verify() const {
656   return isLexicalBlock() && DbgNode->getNumOperands() == 3 &&
657          getNumHeaderFields() == 4;
658 }
659
660 bool DILexicalBlockFile::Verify() const {
661   return isLexicalBlockFile() && DbgNode->getNumOperands() == 3 &&
662          getNumHeaderFields() == 2;
663 }
664
665 bool DITemplateTypeParameter::Verify() const {
666   return isTemplateTypeParameter() && DbgNode->getNumOperands() == 4 &&
667          getNumHeaderFields() == 4;
668 }
669
670 bool DITemplateValueParameter::Verify() const {
671   return isTemplateValueParameter() && DbgNode->getNumOperands() == 5 &&
672          getNumHeaderFields() == 4;
673 }
674
675 bool DIImportedEntity::Verify() const {
676   return isImportedEntity() && DbgNode->getNumOperands() == 3 &&
677          getNumHeaderFields() == 3;
678 }
679
680 MDNode *DIDerivedType::getObjCProperty() const {
681   return getNodeField(DbgNode, 4);
682 }
683
684 MDString *DICompositeType::getIdentifier() const {
685   return cast_or_null<MDString>(getField(DbgNode, 7));
686 }
687
688 #ifndef NDEBUG
689 static void VerifySubsetOf(const MDNode *LHS, const MDNode *RHS) {
690   for (unsigned i = 0; i != LHS->getNumOperands(); ++i) {
691     // Skip the 'empty' list (that's a single i32 0, rather than truly empty).
692     if (i == 0 && mdconst::hasa<ConstantInt>(LHS->getOperand(i)))
693       continue;
694     const MDNode *E = cast<MDNode>(LHS->getOperand(i));
695     bool found = false;
696     for (unsigned j = 0; !found && j != RHS->getNumOperands(); ++j)
697       found = (E == cast<MDNode>(RHS->getOperand(j)));
698     assert(found && "Losing a member during member list replacement");
699   }
700 }
701 #endif
702
703 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
704   TrackingMDNodeRef N(*this);
705   if (Elements) {
706 #ifndef NDEBUG
707     // Check that the new list of members contains all the old members as well.
708     if (const MDNode *El = cast_or_null<MDNode>(N->getOperand(4)))
709       VerifySubsetOf(El, Elements);
710 #endif
711     N->replaceOperandWith(4, Elements);
712   }
713   if (TParams)
714     N->replaceOperandWith(6, TParams);
715   DbgNode = N;
716 }
717
718 DIScopeRef DIScope::getRef() const {
719   if (!isCompositeType())
720     return DIScopeRef(*this);
721   DICompositeType DTy(DbgNode);
722   if (!DTy.getIdentifier())
723     return DIScopeRef(*this);
724   return DIScopeRef(DTy.getIdentifier());
725 }
726
727 void DICompositeType::setContainingType(DICompositeType ContainingType) {
728   TrackingMDNodeRef N(*this);
729   N->replaceOperandWith(5, ContainingType.getRef());
730   DbgNode = N;
731 }
732
733 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
734   assert(CurFn && "Invalid function");
735   if (!getContext().isSubprogram())
736     return false;
737   // This variable is not inlined function argument if its scope
738   // does not describe current function.
739   return !DISubprogram(getContext()).describes(CurFn);
740 }
741
742 bool DISubprogram::describes(const Function *F) {
743   assert(F && "Invalid function");
744   if (F == getFunction())
745     return true;
746   StringRef Name = getLinkageName();
747   if (Name.empty())
748     Name = getName();
749   if (F->getName() == Name)
750     return true;
751   return false;
752 }
753
754 MDNode *DISubprogram::getVariablesNodes() const {
755   return getNodeField(DbgNode, 8);
756 }
757
758 DIArray DISubprogram::getVariables() const {
759   return DIArray(getNodeField(DbgNode, 8));
760 }
761
762 Metadata *DITemplateValueParameter::getValue() const {
763   return DbgNode->getOperand(3);
764 }
765
766 DIScopeRef DIScope::getContext() const {
767
768   if (isType())
769     return DIType(DbgNode).getContext();
770
771   if (isSubprogram())
772     return DIScopeRef(DISubprogram(DbgNode).getContext());
773
774   if (isLexicalBlock())
775     return DIScopeRef(DILexicalBlock(DbgNode).getContext());
776
777   if (isLexicalBlockFile())
778     return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
779
780   if (isNameSpace())
781     return DIScopeRef(DINameSpace(DbgNode).getContext());
782
783   assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
784   return DIScopeRef(nullptr);
785 }
786
787 StringRef DIScope::getName() const {
788   if (isType())
789     return DIType(DbgNode).getName();
790   if (isSubprogram())
791     return DISubprogram(DbgNode).getName();
792   if (isNameSpace())
793     return DINameSpace(DbgNode).getName();
794   assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
795           isCompileUnit()) &&
796          "Unhandled type of scope.");
797   return StringRef();
798 }
799
800 StringRef DIScope::getFilename() const {
801   if (!DbgNode)
802     return StringRef();
803   return ::getStringField(getNodeField(DbgNode, 1), 0);
804 }
805
806 StringRef DIScope::getDirectory() const {
807   if (!DbgNode)
808     return StringRef();
809   return ::getStringField(getNodeField(DbgNode, 1), 1);
810 }
811
812 DIArray DICompileUnit::getEnumTypes() const {
813   if (!DbgNode || DbgNode->getNumOperands() < 7)
814     return DIArray();
815
816   return DIArray(getNodeField(DbgNode, 2));
817 }
818
819 DIArray DICompileUnit::getRetainedTypes() const {
820   if (!DbgNode || DbgNode->getNumOperands() < 7)
821     return DIArray();
822
823   return DIArray(getNodeField(DbgNode, 3));
824 }
825
826 DIArray DICompileUnit::getSubprograms() const {
827   if (!DbgNode || DbgNode->getNumOperands() < 7)
828     return DIArray();
829
830   return DIArray(getNodeField(DbgNode, 4));
831 }
832
833 DIArray DICompileUnit::getGlobalVariables() const {
834   if (!DbgNode || DbgNode->getNumOperands() < 7)
835     return DIArray();
836
837   return DIArray(getNodeField(DbgNode, 5));
838 }
839
840 DIArray DICompileUnit::getImportedEntities() const {
841   if (!DbgNode || DbgNode->getNumOperands() < 7)
842     return DIArray();
843
844   return DIArray(getNodeField(DbgNode, 6));
845 }
846
847 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
848   assert(Verify() && "Expected compile unit");
849   if (Subprograms == getSubprograms())
850     return;
851
852   const_cast<MDNode *>(DbgNode)->replaceOperandWith(4, Subprograms);
853 }
854
855 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
856   assert(Verify() && "Expected compile unit");
857   if (GlobalVariables == getGlobalVariables())
858     return;
859
860   const_cast<MDNode *>(DbgNode)->replaceOperandWith(5, GlobalVariables);
861 }
862
863 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
864                                         DILexicalBlockFile NewScope) {
865   assert(Verify());
866   assert(NewScope && "Expected valid scope");
867
868   const auto *Old = cast<MDLocation>(DbgNode);
869   return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
870                                     NewScope, Old->getInlinedAt()));
871 }
872
873 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
874   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
875   return ++Ctx.pImpl->DiscriminatorTable[Key];
876 }
877
878 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
879                                        LLVMContext &VMContext) {
880   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
881   if (!InlinedScope)
882     return cleanseInlinedVariable(DV, VMContext);
883
884   // Insert inlined scope.
885   SmallVector<Metadata *, 8> Elts(DV->op_begin(),
886                                   DV->op_begin() + DIVariableInlinedAtIndex);
887   Elts.push_back(InlinedScope);
888
889   DIVariable Inlined(MDNode::get(VMContext, Elts));
890   assert(Inlined.Verify() && "Expected to create a DIVariable");
891   return Inlined;
892 }
893
894 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
895   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
896   if (!DIVariable(DV).getInlinedAt())
897     return DIVariable(DV);
898
899   // Remove inlined scope.
900   SmallVector<Metadata *, 8> Elts(DV->op_begin(),
901                                   DV->op_begin() + DIVariableInlinedAtIndex);
902
903   DIVariable Cleansed(MDNode::get(VMContext, Elts));
904   assert(Cleansed.Verify() && "Expected to create a DIVariable");
905   return Cleansed;
906 }
907
908 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
909   DIDescriptor D(Scope);
910   if (D.isSubprogram())
911     return DISubprogram(Scope);
912
913   if (D.isLexicalBlockFile())
914     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
915
916   if (D.isLexicalBlock())
917     return getDISubprogram(DILexicalBlock(Scope).getContext());
918
919   return DISubprogram();
920 }
921
922 DISubprogram llvm::getDISubprogram(const Function *F) {
923   // We look for the first instr that has a debug annotation leading back to F.
924   for (auto &BB : *F) {
925     auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
926       return !Inst.getDebugLoc().isUnknown();
927     });
928     if (Inst == BB.end())
929       continue;
930     DebugLoc DLoc = Inst->getDebugLoc();
931     const MDNode *Scope = DLoc.getScopeNode();
932     DISubprogram Subprogram = getDISubprogram(Scope);
933     return Subprogram.describes(F) ? Subprogram : DISubprogram();
934   }
935
936   return DISubprogram();
937 }
938
939 DICompositeType llvm::getDICompositeType(DIType T) {
940   if (T.isCompositeType())
941     return DICompositeType(T);
942
943   if (T.isDerivedType()) {
944     // This function is currently used by dragonegg and dragonegg does
945     // not generate identifier for types, so using an empty map to resolve
946     // DerivedFrom should be fine.
947     DITypeIdentifierMap EmptyMap;
948     return getDICompositeType(
949         DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
950   }
951
952   return DICompositeType();
953 }
954
955 DITypeIdentifierMap
956 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
957   DITypeIdentifierMap Map;
958   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
959     DICompileUnit CU(CU_Nodes->getOperand(CUi));
960     DIArray Retain = CU.getRetainedTypes();
961     for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
962       if (!Retain.getElement(Ti).isCompositeType())
963         continue;
964       DICompositeType Ty(Retain.getElement(Ti));
965       if (MDString *TypeId = Ty.getIdentifier()) {
966         // Definition has priority over declaration.
967         // Try to insert (TypeId, Ty) to Map.
968         std::pair<DITypeIdentifierMap::iterator, bool> P =
969             Map.insert(std::make_pair(TypeId, Ty));
970         // If TypeId already exists in Map and this is a definition, replace
971         // whatever we had (declaration or definition) with the definition.
972         if (!P.second && !Ty.isForwardDecl())
973           P.first->second = Ty;
974       }
975     }
976   }
977   return Map;
978 }
979
980 //===----------------------------------------------------------------------===//
981 // DebugInfoFinder implementations.
982 //===----------------------------------------------------------------------===//
983
984 void DebugInfoFinder::reset() {
985   CUs.clear();
986   SPs.clear();
987   GVs.clear();
988   TYs.clear();
989   Scopes.clear();
990   NodesSeen.clear();
991   TypeIdentifierMap.clear();
992   TypeMapInitialized = false;
993 }
994
995 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
996   if (!TypeMapInitialized)
997     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
998       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
999       TypeMapInitialized = true;
1000     }
1001 }
1002
1003 void DebugInfoFinder::processModule(const Module &M) {
1004   InitializeTypeMap(M);
1005   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
1006     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
1007       DICompileUnit CU(CU_Nodes->getOperand(i));
1008       addCompileUnit(CU);
1009       DIArray GVs = CU.getGlobalVariables();
1010       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
1011         DIGlobalVariable DIG(GVs.getElement(i));
1012         if (addGlobalVariable(DIG)) {
1013           processScope(DIG.getContext());
1014           processType(DIG.getType().resolve(TypeIdentifierMap));
1015         }
1016       }
1017       DIArray SPs = CU.getSubprograms();
1018       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
1019         processSubprogram(DISubprogram(SPs.getElement(i)));
1020       DIArray EnumTypes = CU.getEnumTypes();
1021       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
1022         processType(DIType(EnumTypes.getElement(i)));
1023       DIArray RetainedTypes = CU.getRetainedTypes();
1024       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
1025         processType(DIType(RetainedTypes.getElement(i)));
1026       DIArray Imports = CU.getImportedEntities();
1027       for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
1028         DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
1029         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
1030         if (Entity.isType())
1031           processType(DIType(Entity));
1032         else if (Entity.isSubprogram())
1033           processSubprogram(DISubprogram(Entity));
1034         else if (Entity.isNameSpace())
1035           processScope(DINameSpace(Entity).getContext());
1036       }
1037     }
1038   }
1039 }
1040
1041 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
1042   if (!Loc)
1043     return;
1044   InitializeTypeMap(M);
1045   processScope(Loc.getScope());
1046   processLocation(M, Loc.getOrigLocation());
1047 }
1048
1049 void DebugInfoFinder::processType(DIType DT) {
1050   if (!addType(DT))
1051     return;
1052   processScope(DT.getContext().resolve(TypeIdentifierMap));
1053   if (DT.isCompositeType()) {
1054     DICompositeType DCT(DT);
1055     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1056     if (DT.isSubroutineType()) {
1057       DITypeArray DTA = DISubroutineType(DT).getTypeArray();
1058       for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
1059         processType(DTA.getElement(i).resolve(TypeIdentifierMap));
1060       return;
1061     }
1062     DIArray DA = DCT.getElements();
1063     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1064       DIDescriptor D = DA.getElement(i);
1065       if (D.isType())
1066         processType(DIType(D));
1067       else if (D.isSubprogram())
1068         processSubprogram(DISubprogram(D));
1069     }
1070   } else if (DT.isDerivedType()) {
1071     DIDerivedType DDT(DT);
1072     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1073   }
1074 }
1075
1076 void DebugInfoFinder::processScope(DIScope Scope) {
1077   if (Scope.isType()) {
1078     DIType Ty(Scope);
1079     processType(Ty);
1080     return;
1081   }
1082   if (Scope.isCompileUnit()) {
1083     addCompileUnit(DICompileUnit(Scope));
1084     return;
1085   }
1086   if (Scope.isSubprogram()) {
1087     processSubprogram(DISubprogram(Scope));
1088     return;
1089   }
1090   if (!addScope(Scope))
1091     return;
1092   if (Scope.isLexicalBlock()) {
1093     DILexicalBlock LB(Scope);
1094     processScope(LB.getContext());
1095   } else if (Scope.isLexicalBlockFile()) {
1096     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
1097     processScope(LBF.getScope());
1098   } else if (Scope.isNameSpace()) {
1099     DINameSpace NS(Scope);
1100     processScope(NS.getContext());
1101   }
1102 }
1103
1104 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1105   if (!addSubprogram(SP))
1106     return;
1107   processScope(SP.getContext().resolve(TypeIdentifierMap));
1108   processType(SP.getType());
1109   DIArray TParams = SP.getTemplateParams();
1110   for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
1111     DIDescriptor Element = TParams.getElement(I);
1112     if (Element.isTemplateTypeParameter()) {
1113       DITemplateTypeParameter TType(Element);
1114       processScope(TType.getContext().resolve(TypeIdentifierMap));
1115       processType(TType.getType().resolve(TypeIdentifierMap));
1116     } else if (Element.isTemplateValueParameter()) {
1117       DITemplateValueParameter TVal(Element);
1118       processScope(TVal.getContext().resolve(TypeIdentifierMap));
1119       processType(TVal.getType().resolve(TypeIdentifierMap));
1120     }
1121   }
1122 }
1123
1124 void DebugInfoFinder::processDeclare(const Module &M,
1125                                      const DbgDeclareInst *DDI) {
1126   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1127   if (!N)
1128     return;
1129   InitializeTypeMap(M);
1130
1131   DIDescriptor DV(N);
1132   if (!DV.isVariable())
1133     return;
1134
1135   if (!NodesSeen.insert(DV).second)
1136     return;
1137   processScope(DIVariable(N).getContext());
1138   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1139 }
1140
1141 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
1142   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
1143   if (!N)
1144     return;
1145   InitializeTypeMap(M);
1146
1147   DIDescriptor DV(N);
1148   if (!DV.isVariable())
1149     return;
1150
1151   if (!NodesSeen.insert(DV).second)
1152     return;
1153   processScope(DIVariable(N).getContext());
1154   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1155 }
1156
1157 bool DebugInfoFinder::addType(DIType DT) {
1158   if (!DT)
1159     return false;
1160
1161   if (!NodesSeen.insert(DT).second)
1162     return false;
1163
1164   TYs.push_back(DT);
1165   return true;
1166 }
1167
1168 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1169   if (!CU)
1170     return false;
1171   if (!NodesSeen.insert(CU).second)
1172     return false;
1173
1174   CUs.push_back(CU);
1175   return true;
1176 }
1177
1178 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1179   if (!DIG)
1180     return false;
1181
1182   if (!NodesSeen.insert(DIG).second)
1183     return false;
1184
1185   GVs.push_back(DIG);
1186   return true;
1187 }
1188
1189 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1190   if (!SP)
1191     return false;
1192
1193   if (!NodesSeen.insert(SP).second)
1194     return false;
1195
1196   SPs.push_back(SP);
1197   return true;
1198 }
1199
1200 bool DebugInfoFinder::addScope(DIScope Scope) {
1201   if (!Scope)
1202     return false;
1203   // FIXME: Ocaml binding generates a scope with no content, we treat it
1204   // as null for now.
1205   if (Scope->getNumOperands() == 0)
1206     return false;
1207   if (!NodesSeen.insert(Scope).second)
1208     return false;
1209   Scopes.push_back(Scope);
1210   return true;
1211 }
1212
1213 //===----------------------------------------------------------------------===//
1214 // DIDescriptor: dump routines for all descriptors.
1215 //===----------------------------------------------------------------------===//
1216
1217 void DIDescriptor::dump() const {
1218   print(dbgs());
1219   dbgs() << '\n';
1220 }
1221
1222 void DIDescriptor::print(raw_ostream &OS) const {
1223   if (!DbgNode)
1224     return;
1225
1226   if (const char *Tag = dwarf::TagString(getTag()))
1227     OS << "[ " << Tag << " ]";
1228
1229   if (this->isSubrange()) {
1230     DISubrange(DbgNode).printInternal(OS);
1231   } else if (this->isCompileUnit()) {
1232     DICompileUnit(DbgNode).printInternal(OS);
1233   } else if (this->isFile()) {
1234     DIFile(DbgNode).printInternal(OS);
1235   } else if (this->isEnumerator()) {
1236     DIEnumerator(DbgNode).printInternal(OS);
1237   } else if (this->isBasicType()) {
1238     DIType(DbgNode).printInternal(OS);
1239   } else if (this->isDerivedType()) {
1240     DIDerivedType(DbgNode).printInternal(OS);
1241   } else if (this->isCompositeType()) {
1242     DICompositeType(DbgNode).printInternal(OS);
1243   } else if (this->isSubprogram()) {
1244     DISubprogram(DbgNode).printInternal(OS);
1245   } else if (this->isGlobalVariable()) {
1246     DIGlobalVariable(DbgNode).printInternal(OS);
1247   } else if (this->isVariable()) {
1248     DIVariable(DbgNode).printInternal(OS);
1249   } else if (this->isObjCProperty()) {
1250     DIObjCProperty(DbgNode).printInternal(OS);
1251   } else if (this->isNameSpace()) {
1252     DINameSpace(DbgNode).printInternal(OS);
1253   } else if (this->isScope()) {
1254     DIScope(DbgNode).printInternal(OS);
1255   } else if (this->isExpression()) {
1256     DIExpression(DbgNode).printInternal(OS);
1257   }
1258 }
1259
1260 void DISubrange::printInternal(raw_ostream &OS) const {
1261   int64_t Count = getCount();
1262   if (Count != -1)
1263     OS << " [" << getLo() << ", " << Count - 1 << ']';
1264   else
1265     OS << " [unbounded]";
1266 }
1267
1268 void DIScope::printInternal(raw_ostream &OS) const {
1269   OS << " [" << getDirectory() << "/" << getFilename() << ']';
1270 }
1271
1272 void DICompileUnit::printInternal(raw_ostream &OS) const {
1273   DIScope::printInternal(OS);
1274   OS << " [";
1275   unsigned Lang = getLanguage();
1276   if (const char *LangStr = dwarf::LanguageString(Lang))
1277     OS << LangStr;
1278   else
1279     (OS << "lang 0x").write_hex(Lang);
1280   OS << ']';
1281 }
1282
1283 void DIEnumerator::printInternal(raw_ostream &OS) const {
1284   OS << " [" << getName() << " :: " << getEnumValue() << ']';
1285 }
1286
1287 void DIType::printInternal(raw_ostream &OS) const {
1288   if (!DbgNode)
1289     return;
1290
1291   StringRef Res = getName();
1292   if (!Res.empty())
1293     OS << " [" << Res << "]";
1294
1295   // TODO: Print context?
1296
1297   OS << " [line " << getLineNumber() << ", size " << getSizeInBits()
1298      << ", align " << getAlignInBits() << ", offset " << getOffsetInBits();
1299   if (isBasicType())
1300     if (const char *Enc =
1301             dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
1302       OS << ", enc " << Enc;
1303   OS << "]";
1304
1305   if (isPrivate())
1306     OS << " [private]";
1307   else if (isProtected())
1308     OS << " [protected]";
1309   else if (isPublic())
1310     OS << " [public]";
1311
1312   if (isArtificial())
1313     OS << " [artificial]";
1314
1315   if (isForwardDecl())
1316     OS << " [decl]";
1317   else if (getTag() == dwarf::DW_TAG_structure_type ||
1318            getTag() == dwarf::DW_TAG_union_type ||
1319            getTag() == dwarf::DW_TAG_enumeration_type ||
1320            getTag() == dwarf::DW_TAG_class_type)
1321     OS << " [def]";
1322   if (isVector())
1323     OS << " [vector]";
1324   if (isStaticMember())
1325     OS << " [static]";
1326
1327   if (isLValueReference())
1328     OS << " [reference]";
1329
1330   if (isRValueReference())
1331     OS << " [rvalue reference]";
1332 }
1333
1334 void DIDerivedType::printInternal(raw_ostream &OS) const {
1335   DIType::printInternal(OS);
1336   OS << " [from " << getTypeDerivedFrom().getName() << ']';
1337 }
1338
1339 void DICompositeType::printInternal(raw_ostream &OS) const {
1340   DIType::printInternal(OS);
1341   DIArray A = getElements();
1342   OS << " [" << A.getNumElements() << " elements]";
1343 }
1344
1345 void DINameSpace::printInternal(raw_ostream &OS) const {
1346   StringRef Name = getName();
1347   if (!Name.empty())
1348     OS << " [" << Name << ']';
1349
1350   OS << " [line " << getLineNumber() << ']';
1351 }
1352
1353 void DISubprogram::printInternal(raw_ostream &OS) const {
1354   // TODO : Print context
1355   OS << " [line " << getLineNumber() << ']';
1356
1357   if (isLocalToUnit())
1358     OS << " [local]";
1359
1360   if (isDefinition())
1361     OS << " [def]";
1362
1363   if (getScopeLineNumber() != getLineNumber())
1364     OS << " [scope " << getScopeLineNumber() << "]";
1365
1366   if (isPrivate())
1367     OS << " [private]";
1368   else if (isProtected())
1369     OS << " [protected]";
1370   else if (isPublic())
1371     OS << " [public]";
1372
1373   if (isLValueReference())
1374     OS << " [reference]";
1375
1376   if (isRValueReference())
1377     OS << " [rvalue reference]";
1378
1379   StringRef Res = getName();
1380   if (!Res.empty())
1381     OS << " [" << Res << ']';
1382 }
1383
1384 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
1385   StringRef Res = getName();
1386   if (!Res.empty())
1387     OS << " [" << Res << ']';
1388
1389   OS << " [line " << getLineNumber() << ']';
1390
1391   // TODO : Print context
1392
1393   if (isLocalToUnit())
1394     OS << " [local]";
1395
1396   if (isDefinition())
1397     OS << " [def]";
1398 }
1399
1400 void DIVariable::printInternal(raw_ostream &OS) const {
1401   StringRef Res = getName();
1402   if (!Res.empty())
1403     OS << " [" << Res << ']';
1404
1405   OS << " [line " << getLineNumber() << ']';
1406 }
1407
1408 void DIExpression::printInternal(raw_ostream &OS) const {
1409   for (auto Op : *this) {
1410     OS << " [" << OperationEncodingString(Op);
1411     switch (Op) {
1412     case DW_OP_plus: {
1413       OS << " " << Op.getArg(1);
1414       break;
1415     }
1416     case DW_OP_bit_piece: {
1417       OS << " offset=" << Op.getArg(1) << ", size=" << Op.getArg(2);
1418       break;
1419     }
1420     case DW_OP_deref:
1421       // No arguments.
1422       break;
1423     default:
1424       llvm_unreachable("unhandled operation");
1425     }
1426     OS << "]";
1427   }
1428 }
1429
1430 void DIObjCProperty::printInternal(raw_ostream &OS) const {
1431   StringRef Name = getObjCPropertyName();
1432   if (!Name.empty())
1433     OS << " [" << Name << ']';
1434
1435   OS << " [line " << getLineNumber() << ", properties " << getUnsignedField(6)
1436      << ']';
1437 }
1438
1439 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
1440                           const LLVMContext &Ctx) {
1441   if (!DL.isUnknown()) { // Print source line info.
1442     DIScope Scope(DL.getScope(Ctx));
1443     assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
1444     // Omit the directory, because it's likely to be long and uninteresting.
1445     CommentOS << Scope.getFilename();
1446     CommentOS << ':' << DL.getLine();
1447     if (DL.getCol() != 0)
1448       CommentOS << ':' << DL.getCol();
1449     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1450     if (!InlinedAtDL.isUnknown()) {
1451       CommentOS << " @[ ";
1452       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
1453       CommentOS << " ]";
1454     }
1455   }
1456 }
1457
1458 void DIVariable::printExtendedName(raw_ostream &OS) const {
1459   const LLVMContext &Ctx = DbgNode->getContext();
1460   StringRef Res = getName();
1461   if (!Res.empty())
1462     OS << Res << "," << getLineNumber();
1463   if (MDNode *InlinedAt = getInlinedAt()) {
1464     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1465     if (!InlinedAtDL.isUnknown()) {
1466       OS << " @[";
1467       printDebugLoc(InlinedAtDL, OS, Ctx);
1468       OS << "]";
1469     }
1470   }
1471 }
1472
1473 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
1474   assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
1475 }
1476 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
1477   assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
1478 }
1479
1480 template <>
1481 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
1482   return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1483 }
1484 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
1485   return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1486 }
1487
1488 bool llvm::StripDebugInfo(Module &M) {
1489   bool Changed = false;
1490
1491   // Remove all of the calls to the debugger intrinsics, and remove them from
1492   // the module.
1493   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
1494     while (!Declare->use_empty()) {
1495       CallInst *CI = cast<CallInst>(Declare->user_back());
1496       CI->eraseFromParent();
1497     }
1498     Declare->eraseFromParent();
1499     Changed = true;
1500   }
1501
1502   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
1503     while (!DbgVal->use_empty()) {
1504       CallInst *CI = cast<CallInst>(DbgVal->user_back());
1505       CI->eraseFromParent();
1506     }
1507     DbgVal->eraseFromParent();
1508     Changed = true;
1509   }
1510
1511   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
1512          NME = M.named_metadata_end(); NMI != NME;) {
1513     NamedMDNode *NMD = NMI;
1514     ++NMI;
1515     if (NMD->getName().startswith("llvm.dbg.")) {
1516       NMD->eraseFromParent();
1517       Changed = true;
1518     }
1519   }
1520
1521   for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
1522     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
1523          ++FI)
1524       for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
1525            ++BI) {
1526         if (!BI->getDebugLoc().isUnknown()) {
1527           Changed = true;
1528           BI->setDebugLoc(DebugLoc());
1529         }
1530       }
1531
1532   return Changed;
1533 }
1534
1535 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
1536   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
1537           M.getModuleFlag("Debug Info Version")))
1538     return Val->getZExtValue();
1539   return 0;
1540 }
1541
1542 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
1543 llvm::makeSubprogramMap(const Module &M) {
1544   DenseMap<const Function *, DISubprogram> R;
1545
1546   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
1547   if (!CU_Nodes)
1548     return R;
1549
1550   for (MDNode *N : CU_Nodes->operands()) {
1551     DICompileUnit CUNode(N);
1552     DIArray SPs = CUNode.getSubprograms();
1553     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
1554       DISubprogram SP(SPs.getElement(i));
1555       if (Function *F = SP.getFunction())
1556         R.insert(std::make_pair(F, SP));
1557     }
1558   }
1559   return R;
1560 }