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