Add asserts to DIBuilder & fix DINameSpace::Verify to allow unnamed namespaces.
[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/DebugInfo.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/raw_ostream.h"
29 using namespace llvm;
30 using namespace llvm::dwarf;
31
32 //===----------------------------------------------------------------------===//
33 // DIDescriptor
34 //===----------------------------------------------------------------------===//
35
36 DIDescriptor::DIDescriptor(const DIFile F) : DbgNode(F.DbgNode) {
37 }
38
39 DIDescriptor::DIDescriptor(const DISubprogram F) : DbgNode(F.DbgNode) {
40 }
41
42 DIDescriptor::DIDescriptor(const DILexicalBlockFile F) : DbgNode(F.DbgNode) {
43 }
44
45 DIDescriptor::DIDescriptor(const DILexicalBlock F) : DbgNode(F.DbgNode) {
46 }
47
48 DIDescriptor::DIDescriptor(const DIVariable F) : DbgNode(F.DbgNode) {
49 }
50
51 DIDescriptor::DIDescriptor(const DIType F) : DbgNode(F.DbgNode) {
52 }
53
54 StringRef
55 DIDescriptor::getStringField(unsigned Elt) const {
56   if (DbgNode == 0)
57     return StringRef();
58
59   if (Elt < DbgNode->getNumOperands())
60     if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getOperand(Elt)))
61       return MDS->getString();
62
63   return StringRef();
64 }
65
66 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
67   if (DbgNode == 0)
68     return 0;
69
70   if (Elt < DbgNode->getNumOperands())
71     if (ConstantInt *CI
72         = dyn_cast_or_null<ConstantInt>(DbgNode->getOperand(Elt)))
73       return CI->getZExtValue();
74
75   return 0;
76 }
77
78 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
79   if (DbgNode == 0)
80     return 0;
81
82   if (Elt < DbgNode->getNumOperands())
83     if (ConstantInt *CI
84         = dyn_cast_or_null<ConstantInt>(DbgNode->getOperand(Elt)))
85       return CI->getSExtValue();
86
87   return 0;
88 }
89
90 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
91   if (DbgNode == 0)
92     return DIDescriptor();
93
94   if (Elt < DbgNode->getNumOperands())
95     return
96       DIDescriptor(dyn_cast_or_null<const MDNode>(DbgNode->getOperand(Elt)));
97   return DIDescriptor();
98 }
99
100 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
101   if (DbgNode == 0)
102     return 0;
103
104   if (Elt < DbgNode->getNumOperands())
105       return dyn_cast_or_null<GlobalVariable>(DbgNode->getOperand(Elt));
106   return 0;
107 }
108
109 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
110   if (DbgNode == 0)
111     return 0;
112
113   if (Elt < DbgNode->getNumOperands())
114       return dyn_cast_or_null<Constant>(DbgNode->getOperand(Elt));
115   return 0;
116 }
117
118 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
119   if (DbgNode == 0)
120     return 0;
121
122   if (Elt < DbgNode->getNumOperands())
123       return dyn_cast_or_null<Function>(DbgNode->getOperand(Elt));
124   return 0;
125 }
126
127 void DIDescriptor::replaceFunctionField(unsigned Elt, Function *F) {
128   if (DbgNode == 0)
129     return;
130
131   if (Elt < DbgNode->getNumOperands()) {
132     MDNode *Node = const_cast<MDNode*>(DbgNode);
133     Node->replaceOperandWith(Elt, F);
134   }
135 }
136
137 unsigned DIVariable::getNumAddrElements() const {
138   if (getVersion() <= LLVMDebugVersion8)
139     return DbgNode->getNumOperands()-6;
140   if (getVersion() == LLVMDebugVersion9)
141     return DbgNode->getNumOperands()-7;
142   return DbgNode->getNumOperands()-8;
143 }
144
145 /// getInlinedAt - If this variable is inlined then return inline location.
146 MDNode *DIVariable::getInlinedAt() const {
147   if (getVersion() <= LLVMDebugVersion9)
148     return NULL;
149   return dyn_cast_or_null<MDNode>(DbgNode->getOperand(7));
150 }
151
152 //===----------------------------------------------------------------------===//
153 // Predicates
154 //===----------------------------------------------------------------------===//
155
156 /// isBasicType - Return true if the specified tag is legal for
157 /// DIBasicType.
158 bool DIDescriptor::isBasicType() const {
159   if (!DbgNode) return false;
160   switch (getTag()) {
161   case dwarf::DW_TAG_base_type:
162   case dwarf::DW_TAG_unspecified_type:
163     return true;
164   default:
165     return false;
166   }
167 }
168
169 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
170 bool DIDescriptor::isDerivedType() const {
171   if (!DbgNode) return false;
172   switch (getTag()) {
173   case dwarf::DW_TAG_typedef:
174   case dwarf::DW_TAG_pointer_type:
175   case dwarf::DW_TAG_ptr_to_member_type:
176   case dwarf::DW_TAG_reference_type:
177   case dwarf::DW_TAG_rvalue_reference_type:
178   case dwarf::DW_TAG_const_type:
179   case dwarf::DW_TAG_volatile_type:
180   case dwarf::DW_TAG_restrict_type:
181   case dwarf::DW_TAG_member:
182   case dwarf::DW_TAG_inheritance:
183   case dwarf::DW_TAG_friend:
184     return true;
185   default:
186     // CompositeTypes are currently modelled as DerivedTypes.
187     return isCompositeType();
188   }
189 }
190
191 /// isCompositeType - Return true if the specified tag is legal for
192 /// DICompositeType.
193 bool DIDescriptor::isCompositeType() const {
194   if (!DbgNode) return false;
195   switch (getTag()) {
196   case dwarf::DW_TAG_array_type:
197   case dwarf::DW_TAG_structure_type:
198   case dwarf::DW_TAG_union_type:
199   case dwarf::DW_TAG_enumeration_type:
200   case dwarf::DW_TAG_subroutine_type:
201   case dwarf::DW_TAG_class_type:
202     return true;
203   default:
204     return false;
205   }
206 }
207
208 /// isVariable - Return true if the specified tag is legal for DIVariable.
209 bool DIDescriptor::isVariable() const {
210   if (!DbgNode) return false;
211   switch (getTag()) {
212   case dwarf::DW_TAG_auto_variable:
213   case dwarf::DW_TAG_arg_variable:
214     return true;
215   default:
216     return false;
217   }
218 }
219
220 /// isType - Return true if the specified tag is legal for DIType.
221 bool DIDescriptor::isType() const {
222   return isBasicType() || isCompositeType() || isDerivedType();
223 }
224
225 /// isSubprogram - Return true if the specified tag is legal for
226 /// DISubprogram.
227 bool DIDescriptor::isSubprogram() const {
228   return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
229 }
230
231 /// isGlobalVariable - Return true if the specified tag is legal for
232 /// DIGlobalVariable.
233 bool DIDescriptor::isGlobalVariable() const {
234   return DbgNode && (getTag() == dwarf::DW_TAG_variable ||
235                      getTag() == dwarf::DW_TAG_constant);
236 }
237
238 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
239 bool DIDescriptor::isGlobal() const {
240   return isGlobalVariable();
241 }
242
243 /// isUnspecifiedParmeter - Return true if the specified tag is
244 /// DW_TAG_unspecified_parameters.
245 bool DIDescriptor::isUnspecifiedParameter() const {
246   return DbgNode && getTag() == dwarf::DW_TAG_unspecified_parameters;
247 }
248
249 /// isScope - Return true if the specified tag is one of the scope
250 /// related tag.
251 bool DIDescriptor::isScope() const {
252   if (!DbgNode) return false;
253   switch (getTag()) {
254   case dwarf::DW_TAG_compile_unit:
255   case dwarf::DW_TAG_lexical_block:
256   case dwarf::DW_TAG_subprogram:
257   case dwarf::DW_TAG_namespace:
258     return true;
259   default:
260     break;
261   }
262   return false;
263 }
264
265 /// isTemplateTypeParameter - Return true if the specified tag is
266 /// DW_TAG_template_type_parameter.
267 bool DIDescriptor::isTemplateTypeParameter() const {
268   return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
269 }
270
271 /// isTemplateValueParameter - Return true if the specified tag is
272 /// DW_TAG_template_value_parameter.
273 bool DIDescriptor::isTemplateValueParameter() const {
274   return DbgNode && getTag() == dwarf::DW_TAG_template_value_parameter;
275 }
276
277 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
278 bool DIDescriptor::isCompileUnit() const {
279   return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
280 }
281
282 /// isFile - Return true if the specified tag is DW_TAG_file_type.
283 bool DIDescriptor::isFile() const {
284   return DbgNode && getTag() == dwarf::DW_TAG_file_type;
285 }
286
287 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
288 bool DIDescriptor::isNameSpace() const {
289   return DbgNode && getTag() == dwarf::DW_TAG_namespace;
290 }
291
292 /// isLexicalBlockFile - Return true if the specified descriptor is a
293 /// lexical block with an extra file.
294 bool DIDescriptor::isLexicalBlockFile() const {
295   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
296     (DbgNode->getNumOperands() == 3);
297 }
298
299 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
300 bool DIDescriptor::isLexicalBlock() const {
301   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
302     (DbgNode->getNumOperands() > 3);
303 }
304
305 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
306 bool DIDescriptor::isSubrange() const {
307   return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
308 }
309
310 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
311 bool DIDescriptor::isEnumerator() const {
312   return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
313 }
314
315 /// isObjCProperty - Return true if the specified tag is DW_TAG
316 bool DIDescriptor::isObjCProperty() const {
317   return DbgNode && getTag() == dwarf::DW_TAG_APPLE_property;
318 }
319 //===----------------------------------------------------------------------===//
320 // Simple Descriptor Constructors and other Methods
321 //===----------------------------------------------------------------------===//
322
323 DIType::DIType(const MDNode *N) : DIScope(N) {
324   if (!N) return;
325   if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
326     DbgNode = 0;
327   }
328 }
329
330 unsigned DIArray::getNumElements() const {
331   if (!DbgNode)
332     return 0;
333   return DbgNode->getNumOperands();
334 }
335
336 /// replaceAllUsesWith - Replace all uses of debug info referenced by
337 /// this descriptor.
338 void DIType::replaceAllUsesWith(DIDescriptor &D) {
339   if (!DbgNode)
340     return;
341
342   // Since we use a TrackingVH for the node, its easy for clients to manufacture
343   // legitimate situations where they want to replaceAllUsesWith() on something
344   // which, due to uniquing, has merged with the source. We shield clients from
345   // this detail by allowing a value to be replaced with replaceAllUsesWith()
346   // itself.
347   if (DbgNode != D) {
348     MDNode *Node = const_cast<MDNode*>(DbgNode);
349     const MDNode *DN = D;
350     const Value *V = cast_or_null<Value>(DN);
351     Node->replaceAllUsesWith(const_cast<Value*>(V));
352     MDNode::deleteTemporary(Node);
353   }
354 }
355
356 /// replaceAllUsesWith - Replace all uses of debug info referenced by
357 /// this descriptor.
358 void DIType::replaceAllUsesWith(MDNode *D) {
359   if (!DbgNode)
360     return;
361
362   // Since we use a TrackingVH for the node, its easy for clients to manufacture
363   // legitimate situations where they want to replaceAllUsesWith() on something
364   // which, due to uniquing, has merged with the source. We shield clients from
365   // this detail by allowing a value to be replaced with replaceAllUsesWith()
366   // itself.
367   if (DbgNode != D) {
368     MDNode *Node = const_cast<MDNode*>(DbgNode);
369     const MDNode *DN = D;
370     const Value *V = cast_or_null<Value>(DN);
371     Node->replaceAllUsesWith(const_cast<Value*>(V));
372     MDNode::deleteTemporary(Node);
373   }
374 }
375
376 /// isUnsignedDIType - Return true if type encoding is unsigned.
377 bool DIType::isUnsignedDIType() {
378   DIDerivedType DTy(DbgNode);
379   if (DTy.Verify())
380     return DTy.getTypeDerivedFrom().isUnsignedDIType();
381
382   DIBasicType BTy(DbgNode);
383   if (BTy.Verify()) {
384     unsigned Encoding = BTy.getEncoding();
385     if (Encoding == dwarf::DW_ATE_unsigned ||
386         Encoding == dwarf::DW_ATE_unsigned_char ||
387         Encoding == dwarf::DW_ATE_boolean)
388       return true;
389   }
390   return false;
391 }
392
393 /// Verify - Verify that a compile unit is well formed.
394 bool DICompileUnit::Verify() const {
395   if (!DbgNode)
396     return false;
397   StringRef N = getFilename();
398   if (N.empty())
399     return false;
400   // It is possible that directory and produce string is empty.
401   return true;
402 }
403
404 /// Verify - Verify that an ObjC property is well formed.
405 bool DIObjCProperty::Verify() const {
406   if (!DbgNode)
407     return false;
408   unsigned Tag = getTag();
409   if (Tag != dwarf::DW_TAG_APPLE_property) return false;
410   DIType Ty = getType();
411   if (!Ty.Verify()) return false;
412
413   // Don't worry about the rest of the strings for now.
414   return true;
415 }
416
417 /// Verify - Verify that a type descriptor is well formed.
418 bool DIType::Verify() const {
419   if (!DbgNode)
420     return false;
421   if (getContext() && !getContext().Verify())
422     return false;
423   unsigned Tag = getTag();
424   if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
425       Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
426       Tag != dwarf::DW_TAG_ptr_to_member_type &&
427       Tag != dwarf::DW_TAG_reference_type &&
428       Tag != dwarf::DW_TAG_rvalue_reference_type &&
429       Tag != dwarf::DW_TAG_restrict_type &&
430       Tag != dwarf::DW_TAG_array_type &&
431       Tag != dwarf::DW_TAG_enumeration_type &&
432       Tag != dwarf::DW_TAG_subroutine_type &&
433       getFilename().empty())
434     return false;
435   return true;
436 }
437
438 /// Verify - Verify that a basic type descriptor is well formed.
439 bool DIBasicType::Verify() const {
440   return isBasicType();
441 }
442
443 /// Verify - Verify that a derived type descriptor is well formed.
444 bool DIDerivedType::Verify() const {
445   return isDerivedType();
446 }
447
448 /// Verify - Verify that a composite type descriptor is well formed.
449 bool DICompositeType::Verify() const {
450   if (!DbgNode)
451     return false;
452   if (getContext() && !getContext().Verify())
453     return false;
454
455   return true;
456 }
457
458 /// Verify - Verify that a subprogram descriptor is well formed.
459 bool DISubprogram::Verify() const {
460   if (!DbgNode)
461     return false;
462
463   if (getContext() && !getContext().Verify())
464     return false;
465
466   DICompositeType Ty = getType();
467   if (!Ty.Verify())
468     return false;
469   return true;
470 }
471
472 /// Verify - Verify that a global variable descriptor is well formed.
473 bool DIGlobalVariable::Verify() const {
474   if (!DbgNode)
475     return false;
476
477   if (getDisplayName().empty())
478     return false;
479
480   if (getContext() && !getContext().Verify())
481     return false;
482
483   DIType Ty = getType();
484   if (!Ty.Verify())
485     return false;
486
487   if (!getGlobal() && !getConstant())
488     return false;
489
490   return true;
491 }
492
493 /// Verify - Verify that a variable descriptor is well formed.
494 bool DIVariable::Verify() const {
495   if (!DbgNode)
496     return false;
497
498   if (getContext() && !getContext().Verify())
499     return false;
500
501   DIType Ty = getType();
502   if (!Ty.Verify())
503     return false;
504
505   return true;
506 }
507
508 /// Verify - Verify that a location descriptor is well formed.
509 bool DILocation::Verify() const {
510   if (!DbgNode)
511     return false;
512
513   return DbgNode->getNumOperands() == 4;
514 }
515
516 /// Verify - Verify that a namespace descriptor is well formed.
517 bool DINameSpace::Verify() const {
518   if (!DbgNode)
519     return false;
520   return true;
521 }
522
523 /// getOriginalTypeSize - If this type is derived from a base type then
524 /// return base type size.
525 uint64_t DIDerivedType::getOriginalTypeSize() const {
526   unsigned Tag = getTag();
527
528   if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
529       Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
530       Tag != dwarf::DW_TAG_restrict_type)
531     return getSizeInBits();
532
533   DIType BaseType = getTypeDerivedFrom();
534
535   // If this type is not derived from any type then take conservative approach.
536   if (!BaseType.isValid())
537     return getSizeInBits();
538
539   // If this is a derived type, go ahead and get the base type, unless it's a
540   // reference then it's just the size of the field. Pointer types have no need
541   // of this since they're a different type of qualification on the type.
542   if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
543       BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
544     return getSizeInBits();
545
546   if (BaseType.isDerivedType())
547     return DIDerivedType(BaseType).getOriginalTypeSize();
548
549   return BaseType.getSizeInBits();
550 }
551
552 /// getObjCProperty - Return property node, if this ivar is associated with one.
553 MDNode *DIDerivedType::getObjCProperty() const {
554   if (getVersion() <= LLVMDebugVersion11 || DbgNode->getNumOperands() <= 10)
555     return NULL;
556   return dyn_cast_or_null<MDNode>(DbgNode->getOperand(10));
557 }
558
559 /// isInlinedFnArgument - Return true if this variable provides debugging
560 /// information for an inlined function arguments.
561 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
562   assert(CurFn && "Invalid function");
563   if (!getContext().isSubprogram())
564     return false;
565   // This variable is not inlined function argument if its scope
566   // does not describe current function.
567   return !DISubprogram(getContext()).describes(CurFn);
568 }
569
570 /// describes - Return true if this subprogram provides debugging
571 /// information for the function F.
572 bool DISubprogram::describes(const Function *F) {
573   assert(F && "Invalid function");
574   if (F == getFunction())
575     return true;
576   StringRef Name = getLinkageName();
577   if (Name.empty())
578     Name = getName();
579   if (F->getName() == Name)
580     return true;
581   return false;
582 }
583
584 unsigned DISubprogram::isOptimized() const {
585   assert (DbgNode && "Invalid subprogram descriptor!");
586   if (DbgNode->getNumOperands() == 16)
587     return getUnsignedField(15);
588   return 0;
589 }
590
591 MDNode *DISubprogram::getVariablesNodes() const {
592   if (!DbgNode || DbgNode->getNumOperands() <= 19)
593     return NULL;
594   return dyn_cast_or_null<MDNode>(DbgNode->getOperand(19));
595 }
596
597 DIArray DISubprogram::getVariables() const {
598   if (!DbgNode || DbgNode->getNumOperands() <= 19)
599     return DIArray();
600   if (MDNode *T = dyn_cast_or_null<MDNode>(DbgNode->getOperand(19)))
601     return DIArray(T);
602   return DIArray();
603 }
604
605 StringRef DIScope::getFilename() const {
606   if (!DbgNode)
607     return StringRef();
608   if (isLexicalBlockFile())
609     return DILexicalBlockFile(DbgNode).getFilename();
610   if (isLexicalBlock())
611     return DILexicalBlock(DbgNode).getFilename();
612   if (isSubprogram())
613     return DISubprogram(DbgNode).getFilename();
614   if (isCompileUnit())
615     return DICompileUnit(DbgNode).getFilename();
616   if (isNameSpace())
617     return DINameSpace(DbgNode).getFilename();
618   if (isType())
619     return DIType(DbgNode).getFilename();
620   if (isFile())
621     return DIFile(DbgNode).getFilename();
622   llvm_unreachable("Invalid DIScope!");
623 }
624
625 StringRef DIScope::getDirectory() const {
626   if (!DbgNode)
627     return StringRef();
628   if (isLexicalBlockFile())
629     return DILexicalBlockFile(DbgNode).getDirectory();
630   if (isLexicalBlock())
631     return DILexicalBlock(DbgNode).getDirectory();
632   if (isSubprogram())
633     return DISubprogram(DbgNode).getDirectory();
634   if (isCompileUnit())
635     return DICompileUnit(DbgNode).getDirectory();
636   if (isNameSpace())
637     return DINameSpace(DbgNode).getDirectory();
638   if (isType())
639     return DIType(DbgNode).getDirectory();
640   if (isFile())
641     return DIFile(DbgNode).getDirectory();
642   llvm_unreachable("Invalid DIScope!");
643 }
644
645 DIArray DICompileUnit::getEnumTypes() const {
646   if (!DbgNode || DbgNode->getNumOperands() < 14)
647     return DIArray();
648
649   if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(10)))
650     return DIArray(N);
651   return DIArray();
652 }
653
654 DIArray DICompileUnit::getRetainedTypes() const {
655   if (!DbgNode || DbgNode->getNumOperands() < 14)
656     return DIArray();
657
658   if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(11)))
659     return DIArray(N);
660   return DIArray();
661 }
662
663 DIArray DICompileUnit::getSubprograms() const {
664   if (!DbgNode || DbgNode->getNumOperands() < 14)
665     return DIArray();
666
667   if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(12)))
668     return DIArray(N);
669   return DIArray();
670 }
671
672
673 DIArray DICompileUnit::getGlobalVariables() const {
674   if (!DbgNode || DbgNode->getNumOperands() < 14)
675     return DIArray();
676
677   if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(13)))
678     return DIArray(N);
679   return DIArray();
680 }
681
682 /// fixupObjcLikeName - Replace contains special characters used
683 /// in a typical Objective-C names with '.' in a given string.
684 static void fixupObjcLikeName(StringRef Str, SmallVectorImpl<char> &Out) {
685   bool isObjCLike = false;
686   for (size_t i = 0, e = Str.size(); i < e; ++i) {
687     char C = Str[i];
688     if (C == '[')
689       isObjCLike = true;
690
691     if (isObjCLike && (C == '[' || C == ']' || C == ' ' || C == ':' ||
692                        C == '+' || C == '(' || C == ')'))
693       Out.push_back('.');
694     else
695       Out.push_back(C);
696   }
697 }
698
699 /// getFnSpecificMDNode - Return a NameMDNode, if available, that is
700 /// suitable to hold function specific information.
701 NamedMDNode *llvm::getFnSpecificMDNode(const Module &M, DISubprogram Fn) {
702   SmallString<32> Name = StringRef("llvm.dbg.lv.");
703   StringRef FName = "fn";
704   if (Fn.getFunction())
705     FName = Fn.getFunction()->getName();
706   else
707     FName = Fn.getName();
708   char One = '\1';
709   if (FName.startswith(StringRef(&One, 1)))
710     FName = FName.substr(1);
711   fixupObjcLikeName(FName, Name);
712   return M.getNamedMetadata(Name.str());
713 }
714
715 /// getOrInsertFnSpecificMDNode - Return a NameMDNode that is suitable
716 /// to hold function specific information.
717 NamedMDNode *llvm::getOrInsertFnSpecificMDNode(Module &M, DISubprogram Fn) {
718   SmallString<32> Name = StringRef("llvm.dbg.lv.");
719   StringRef FName = "fn";
720   if (Fn.getFunction())
721     FName = Fn.getFunction()->getName();
722   else
723     FName = Fn.getName();
724   char One = '\1';
725   if (FName.startswith(StringRef(&One, 1)))
726     FName = FName.substr(1);
727   fixupObjcLikeName(FName, Name);
728
729   return M.getOrInsertNamedMetadata(Name.str());
730 }
731
732 /// createInlinedVariable - Create a new inlined variable based on current
733 /// variable.
734 /// @param DV            Current Variable.
735 /// @param InlinedScope  Location at current variable is inlined.
736 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
737                                        LLVMContext &VMContext) {
738   SmallVector<Value *, 16> Elts;
739   // Insert inlined scope as 7th element.
740   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
741     i == 7 ? Elts.push_back(InlinedScope) :
742              Elts.push_back(DV->getOperand(i));
743   return DIVariable(MDNode::get(VMContext, Elts));
744 }
745
746 /// cleanseInlinedVariable - Remove inlined scope from the variable.
747 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
748   SmallVector<Value *, 16> Elts;
749   // Insert inlined scope as 7th element.
750   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
751     i == 7 ?
752       Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext))):
753       Elts.push_back(DV->getOperand(i));
754   return DIVariable(MDNode::get(VMContext, Elts));
755 }
756
757 /// getDISubprogram - Find subprogram that is enclosing this scope.
758 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
759   DIDescriptor D(Scope);
760   if (D.isSubprogram())
761     return DISubprogram(Scope);
762
763   if (D.isLexicalBlockFile())
764     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
765
766   if (D.isLexicalBlock())
767     return getDISubprogram(DILexicalBlock(Scope).getContext());
768
769   return DISubprogram();
770 }
771
772 /// getDICompositeType - Find underlying composite type.
773 DICompositeType llvm::getDICompositeType(DIType T) {
774   if (T.isCompositeType())
775     return DICompositeType(T);
776
777   if (T.isDerivedType())
778     return getDICompositeType(DIDerivedType(T).getTypeDerivedFrom());
779
780   return DICompositeType();
781 }
782
783 /// isSubprogramContext - Return true if Context is either a subprogram
784 /// or another context nested inside a subprogram.
785 bool llvm::isSubprogramContext(const MDNode *Context) {
786   if (!Context)
787     return false;
788   DIDescriptor D(Context);
789   if (D.isSubprogram())
790     return true;
791   if (D.isType())
792     return isSubprogramContext(DIType(Context).getContext());
793   return false;
794 }
795
796 //===----------------------------------------------------------------------===//
797 // DebugInfoFinder implementations.
798 //===----------------------------------------------------------------------===//
799
800 /// processModule - Process entire module and collect debug info.
801 void DebugInfoFinder::processModule(const Module &M) {
802   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
803     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
804       DICompileUnit CU(CU_Nodes->getOperand(i));
805       addCompileUnit(CU);
806       if (CU.getVersion() > LLVMDebugVersion10) {
807         DIArray GVs = CU.getGlobalVariables();
808         for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
809           DIGlobalVariable DIG(GVs.getElement(i));
810           if (addGlobalVariable(DIG))
811             processType(DIG.getType());
812         }
813         DIArray SPs = CU.getSubprograms();
814         for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
815           processSubprogram(DISubprogram(SPs.getElement(i)));
816         DIArray EnumTypes = CU.getEnumTypes();
817         for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
818           processType(DIType(EnumTypes.getElement(i)));
819         DIArray RetainedTypes = CU.getRetainedTypes();
820         for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
821           processType(DIType(RetainedTypes.getElement(i)));
822         return;
823       }
824     }
825   }
826
827   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
828     for (Function::const_iterator FI = (*I).begin(), FE = (*I).end();
829          FI != FE; ++FI)
830       for (BasicBlock::const_iterator BI = (*FI).begin(), BE = (*FI).end();
831            BI != BE; ++BI) {
832         if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
833           processDeclare(DDI);
834
835         DebugLoc Loc = BI->getDebugLoc();
836         if (Loc.isUnknown())
837           continue;
838
839         LLVMContext &Ctx = BI->getContext();
840         DIDescriptor Scope(Loc.getScope(Ctx));
841
842         if (Scope.isCompileUnit())
843           addCompileUnit(DICompileUnit(Scope));
844         else if (Scope.isSubprogram())
845           processSubprogram(DISubprogram(Scope));
846         else if (Scope.isLexicalBlockFile()) {
847           DILexicalBlockFile DBF = DILexicalBlockFile(Scope);
848           processLexicalBlock(DILexicalBlock(DBF.getScope()));
849         }
850         else if (Scope.isLexicalBlock())
851           processLexicalBlock(DILexicalBlock(Scope));
852
853         if (MDNode *IA = Loc.getInlinedAt(Ctx))
854           processLocation(DILocation(IA));
855       }
856
857   if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv")) {
858     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
859       DIGlobalVariable DIG(cast<MDNode>(NMD->getOperand(i)));
860       if (addGlobalVariable(DIG)) {
861         if (DIG.getVersion() <= LLVMDebugVersion10)
862           addCompileUnit(DIG.getCompileUnit());
863         processType(DIG.getType());
864       }
865     }
866   }
867
868   if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
869     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
870       processSubprogram(DISubprogram(NMD->getOperand(i)));
871 }
872
873 /// processLocation - Process DILocation.
874 void DebugInfoFinder::processLocation(DILocation Loc) {
875   if (!Loc.Verify()) return;
876   DIDescriptor S(Loc.getScope());
877   if (S.isCompileUnit())
878     addCompileUnit(DICompileUnit(S));
879   else if (S.isSubprogram())
880     processSubprogram(DISubprogram(S));
881   else if (S.isLexicalBlock())
882     processLexicalBlock(DILexicalBlock(S));
883   else if (S.isLexicalBlockFile()) {
884     DILexicalBlockFile DBF = DILexicalBlockFile(S);
885     processLexicalBlock(DILexicalBlock(DBF.getScope()));
886   }
887   processLocation(Loc.getOrigLocation());
888 }
889
890 /// processType - Process DIType.
891 void DebugInfoFinder::processType(DIType DT) {
892   if (!addType(DT))
893     return;
894   if (DT.getVersion() <= LLVMDebugVersion10)
895     addCompileUnit(DT.getCompileUnit());
896   if (DT.isCompositeType()) {
897     DICompositeType DCT(DT);
898     processType(DCT.getTypeDerivedFrom());
899     DIArray DA = DCT.getTypeArray();
900     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
901       DIDescriptor D = DA.getElement(i);
902       if (D.isType())
903         processType(DIType(D));
904       else if (D.isSubprogram())
905         processSubprogram(DISubprogram(D));
906     }
907   } else if (DT.isDerivedType()) {
908     DIDerivedType DDT(DT);
909     processType(DDT.getTypeDerivedFrom());
910   }
911 }
912
913 /// processLexicalBlock
914 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
915   DIScope Context = LB.getContext();
916   if (Context.isLexicalBlock())
917     return processLexicalBlock(DILexicalBlock(Context));
918   else if (Context.isLexicalBlockFile()) {
919     DILexicalBlockFile DBF = DILexicalBlockFile(Context);
920     return processLexicalBlock(DILexicalBlock(DBF.getScope()));
921   }
922   else
923     return processSubprogram(DISubprogram(Context));
924 }
925
926 /// processSubprogram - Process DISubprogram.
927 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
928   if (!addSubprogram(SP))
929     return;
930   if (SP.getVersion() <= LLVMDebugVersion10)
931     addCompileUnit(SP.getCompileUnit());
932   processType(SP.getType());
933 }
934
935 /// processDeclare - Process DbgDeclareInst.
936 void DebugInfoFinder::processDeclare(const DbgDeclareInst *DDI) {
937   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
938   if (!N) return;
939
940   DIDescriptor DV(N);
941   if (!DV.isVariable())
942     return;
943
944   if (!NodesSeen.insert(DV))
945     return;
946   if (DIVariable(N).getVersion() <= LLVMDebugVersion10)
947     addCompileUnit(DIVariable(N).getCompileUnit());
948   processType(DIVariable(N).getType());
949 }
950
951 /// addType - Add type into Tys.
952 bool DebugInfoFinder::addType(DIType DT) {
953   if (!DT.isValid())
954     return false;
955
956   if (!NodesSeen.insert(DT))
957     return false;
958
959   TYs.push_back(DT);
960   return true;
961 }
962
963 /// addCompileUnit - Add compile unit into CUs.
964 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
965   if (!CU.Verify())
966     return false;
967
968   if (!NodesSeen.insert(CU))
969     return false;
970
971   CUs.push_back(CU);
972   return true;
973 }
974
975 /// addGlobalVariable - Add global variable into GVs.
976 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
977   if (!DIDescriptor(DIG).isGlobalVariable())
978     return false;
979
980   if (!NodesSeen.insert(DIG))
981     return false;
982
983   GVs.push_back(DIG);
984   return true;
985 }
986
987 // addSubprogram - Add subprgoram into SPs.
988 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
989   if (!DIDescriptor(SP).isSubprogram())
990     return false;
991
992   if (!NodesSeen.insert(SP))
993     return false;
994
995   SPs.push_back(SP);
996   return true;
997 }
998
999 //===----------------------------------------------------------------------===//
1000 // DIDescriptor: dump routines for all descriptors.
1001 //===----------------------------------------------------------------------===//
1002
1003 /// dump - Print descriptor to dbgs() with a newline.
1004 void DIDescriptor::dump() const {
1005   print(dbgs()); dbgs() << '\n';
1006 }
1007
1008 /// print - Print descriptor.
1009 void DIDescriptor::print(raw_ostream &OS) const {
1010   if (!DbgNode) return;
1011
1012   if (const char *Tag = dwarf::TagString(getTag()))
1013     OS << "[ " << Tag << " ]";
1014
1015   if (this->isSubrange()) {
1016     DISubrange(DbgNode).printInternal(OS);
1017   } else if (this->isCompileUnit()) {
1018     DICompileUnit(DbgNode).printInternal(OS);
1019   } else if (this->isFile()) {
1020     DIFile(DbgNode).printInternal(OS);
1021   } else if (this->isEnumerator()) {
1022     DIEnumerator(DbgNode).printInternal(OS);
1023   } else if (this->isBasicType()) {
1024     DIType(DbgNode).printInternal(OS);
1025   } else if (this->isDerivedType()) {
1026     DIDerivedType(DbgNode).printInternal(OS);
1027   } else if (this->isCompositeType()) {
1028     DICompositeType(DbgNode).printInternal(OS);
1029   } else if (this->isSubprogram()) {
1030     DISubprogram(DbgNode).printInternal(OS);
1031   } else if (this->isGlobalVariable()) {
1032     DIGlobalVariable(DbgNode).printInternal(OS);
1033   } else if (this->isVariable()) {
1034     DIVariable(DbgNode).printInternal(OS);
1035   } else if (this->isObjCProperty()) {
1036     DIObjCProperty(DbgNode).printInternal(OS);
1037   } else if (this->isScope()) {
1038     DIScope(DbgNode).printInternal(OS);
1039   }
1040 }
1041
1042 void DISubrange::printInternal(raw_ostream &OS) const {
1043   int64_t Count = getCount();
1044   if (Count != -1)
1045     OS << " [" << getLo() << ", " << Count - 1 << ']';
1046   else
1047     OS << " [unbounded]";
1048 }
1049
1050 void DIScope::printInternal(raw_ostream &OS) const {
1051   OS << " [" << getDirectory() << "/" << getFilename() << ']';
1052 }
1053
1054 void DICompileUnit::printInternal(raw_ostream &OS) const {
1055   DIScope::printInternal(OS);
1056   if (const char *Lang = dwarf::LanguageString(getLanguage()))
1057     OS << " [" << Lang << ']';
1058 }
1059
1060 void DIEnumerator::printInternal(raw_ostream &OS) const {
1061   OS << " [" << getName() << " :: " << getEnumValue() << ']';
1062 }
1063
1064 void DIType::printInternal(raw_ostream &OS) const {
1065   if (!DbgNode) return;
1066
1067   StringRef Res = getName();
1068   if (!Res.empty())
1069     OS << " [" << Res << "]";
1070
1071   // TODO: Print context?
1072
1073   OS << " [line " << getLineNumber()
1074      << ", size " << getSizeInBits()
1075      << ", align " << getAlignInBits()
1076      << ", offset " << getOffsetInBits();
1077   if (isBasicType())
1078     if (const char *Enc =
1079         dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
1080       OS << ", enc " << Enc;
1081   OS << "]";
1082
1083   if (isPrivate())
1084     OS << " [private]";
1085   else if (isProtected())
1086     OS << " [protected]";
1087
1088   if (isArtificial())
1089     OS << " [artificial]";
1090
1091   if (isForwardDecl())
1092     OS << " [fwd]";
1093   if (isVector())
1094     OS << " [vector]";
1095   if (isStaticMember())
1096     OS << " [static]";
1097 }
1098
1099 void DIDerivedType::printInternal(raw_ostream &OS) const {
1100   DIType::printInternal(OS);
1101   OS << " [from " << getTypeDerivedFrom().getName() << ']';
1102 }
1103
1104 void DICompositeType::printInternal(raw_ostream &OS) const {
1105   DIType::printInternal(OS);
1106   DIArray A = getTypeArray();
1107   OS << " [" << A.getNumElements() << " elements]";
1108 }
1109
1110 void DISubprogram::printInternal(raw_ostream &OS) const {
1111   // TODO : Print context
1112   OS << " [line " << getLineNumber() << ']';
1113
1114   if (isLocalToUnit())
1115     OS << " [local]";
1116
1117   if (isDefinition())
1118     OS << " [def]";
1119
1120   if (getScopeLineNumber() != getLineNumber())
1121     OS << " [scope " << getScopeLineNumber() << "]";
1122
1123   if (isPrivate())
1124     OS << " [private]";
1125   else if (isProtected())
1126     OS << " [protected]";
1127
1128   StringRef Res = getName();
1129   if (!Res.empty())
1130     OS << " [" << Res << ']';
1131 }
1132
1133 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
1134   StringRef Res = getName();
1135   if (!Res.empty())
1136     OS << " [" << Res << ']';
1137
1138   OS << " [line " << getLineNumber() << ']';
1139
1140   // TODO : Print context
1141
1142   if (isLocalToUnit())
1143     OS << " [local]";
1144
1145   if (isDefinition())
1146     OS << " [def]";
1147 }
1148
1149 void DIVariable::printInternal(raw_ostream &OS) const {
1150   StringRef Res = getName();
1151   if (!Res.empty())
1152     OS << " [" << Res << ']';
1153
1154   OS << " [line " << getLineNumber() << ']';
1155 }
1156
1157 void DIObjCProperty::printInternal(raw_ostream &OS) const {
1158   StringRef Name = getObjCPropertyName();
1159   if (!Name.empty())
1160     OS << " [" << Name << ']';
1161
1162   OS << " [line " << getLineNumber()
1163      << ", properties " << getUnsignedField(6) << ']';
1164 }
1165
1166 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
1167                           const LLVMContext &Ctx) {
1168   if (!DL.isUnknown()) {          // Print source line info.
1169     DIScope Scope(DL.getScope(Ctx));
1170     // Omit the directory, because it's likely to be long and uninteresting.
1171     if (Scope.Verify())
1172       CommentOS << Scope.getFilename();
1173     else
1174       CommentOS << "<unknown>";
1175     CommentOS << ':' << DL.getLine();
1176     if (DL.getCol() != 0)
1177       CommentOS << ':' << DL.getCol();
1178     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1179     if (!InlinedAtDL.isUnknown()) {
1180       CommentOS << " @[ ";
1181       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
1182       CommentOS << " ]";
1183     }
1184   }
1185 }
1186
1187 void DIVariable::printExtendedName(raw_ostream &OS) const {
1188   const LLVMContext &Ctx = DbgNode->getContext();
1189   StringRef Res = getName();
1190   if (!Res.empty())
1191     OS << Res << "," << getLineNumber();
1192   if (MDNode *InlinedAt = getInlinedAt()) {
1193     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1194     if (!InlinedAtDL.isUnknown()) {
1195       OS << " @[";
1196       printDebugLoc(InlinedAtDL, OS, Ctx);
1197       OS << "]";
1198     }
1199   }
1200 }