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