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