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