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