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