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