717c7fb5143029eb699ea643443bf0ff6701091e
[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/Target/TargetMachine.h"  // FIXME: LAYERING VIOLATION!
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Intrinsics.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace llvm;
29 using namespace llvm::dwarf;
30
31 //===----------------------------------------------------------------------===//
32 // DIDescriptor
33 //===----------------------------------------------------------------------===//
34
35 StringRef 
36 DIDescriptor::getStringField(unsigned Elt) const {
37   if (DbgNode == 0)
38     return StringRef();
39
40   if (Elt < DbgNode->getNumOperands())
41     if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getOperand(Elt)))
42       return MDS->getString();
43
44   return StringRef();
45 }
46
47 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
48   if (DbgNode == 0)
49     return 0;
50
51   if (Elt < DbgNode->getNumOperands())
52     if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getOperand(Elt)))
53       return CI->getZExtValue();
54
55   return 0;
56 }
57
58 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
59   if (DbgNode == 0)
60     return DIDescriptor();
61
62   if (Elt < DbgNode->getNumOperands())
63     return DIDescriptor(dyn_cast_or_null<const MDNode>(DbgNode->getOperand(Elt)));
64   return DIDescriptor();
65 }
66
67 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
68   if (DbgNode == 0)
69     return 0;
70
71   if (Elt < DbgNode->getNumOperands())
72       return dyn_cast_or_null<GlobalVariable>(DbgNode->getOperand(Elt));
73   return 0;
74 }
75
76 unsigned DIVariable::getNumAddrElements() const {
77   return DbgNode->getNumOperands()-6;
78 }
79
80
81 //===----------------------------------------------------------------------===//
82 // Predicates
83 //===----------------------------------------------------------------------===//
84
85 /// isBasicType - Return true if the specified tag is legal for
86 /// DIBasicType.
87 bool DIDescriptor::isBasicType() const {
88   return DbgNode && getTag() == dwarf::DW_TAG_base_type;
89 }
90
91 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
92 bool DIDescriptor::isDerivedType() const {
93   if (!DbgNode) return false;
94   switch (getTag()) {
95   case dwarf::DW_TAG_typedef:
96   case dwarf::DW_TAG_pointer_type:
97   case dwarf::DW_TAG_reference_type:
98   case dwarf::DW_TAG_const_type:
99   case dwarf::DW_TAG_volatile_type:
100   case dwarf::DW_TAG_restrict_type:
101   case dwarf::DW_TAG_member:
102   case dwarf::DW_TAG_inheritance:
103     return true;
104   default:
105     // CompositeTypes are currently modelled as DerivedTypes.
106     return isCompositeType();
107   }
108 }
109
110 /// isCompositeType - Return true if the specified tag is legal for
111 /// DICompositeType.
112 bool DIDescriptor::isCompositeType() const {
113   if (!DbgNode) return false;
114   switch (getTag()) {
115   case dwarf::DW_TAG_array_type:
116   case dwarf::DW_TAG_structure_type:
117   case dwarf::DW_TAG_union_type:
118   case dwarf::DW_TAG_enumeration_type:
119   case dwarf::DW_TAG_vector_type:
120   case dwarf::DW_TAG_subroutine_type:
121   case dwarf::DW_TAG_class_type:
122     return true;
123   default:
124     return false;
125   }
126 }
127
128 /// isVariable - Return true if the specified tag is legal for DIVariable.
129 bool DIDescriptor::isVariable() const {
130   if (!DbgNode) return false;
131   switch (getTag()) {
132   case dwarf::DW_TAG_auto_variable:
133   case dwarf::DW_TAG_arg_variable:
134   case dwarf::DW_TAG_return_variable:
135     return true;
136   default:
137     return false;
138   }
139 }
140
141 /// isType - Return true if the specified tag is legal for DIType.
142 bool DIDescriptor::isType() const {
143   return isBasicType() || isCompositeType() || isDerivedType();
144 }
145
146 /// isSubprogram - Return true if the specified tag is legal for
147 /// DISubprogram.
148 bool DIDescriptor::isSubprogram() const {
149   return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
150 }
151
152 /// isGlobalVariable - Return true if the specified tag is legal for
153 /// DIGlobalVariable.
154 bool DIDescriptor::isGlobalVariable() const {
155   return DbgNode && getTag() == dwarf::DW_TAG_variable;
156 }
157
158 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
159 bool DIDescriptor::isGlobal() const {
160   return isGlobalVariable();
161 }
162
163 /// isScope - Return true if the specified tag is one of the scope
164 /// related tag.
165 bool DIDescriptor::isScope() const {
166   if (!DbgNode) return false;
167   switch (getTag()) {
168   case dwarf::DW_TAG_compile_unit:
169   case dwarf::DW_TAG_lexical_block:
170   case dwarf::DW_TAG_subprogram:
171   case dwarf::DW_TAG_namespace:
172     return true;
173   default:
174     break;
175   }
176   return false;
177 }
178
179 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
180 bool DIDescriptor::isCompileUnit() const {
181   return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
182 }
183
184 /// isFile - Return true if the specified tag is DW_TAG_file_type.
185 bool DIDescriptor::isFile() const {
186   return DbgNode && getTag() == dwarf::DW_TAG_file_type;
187 }
188
189 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
190 bool DIDescriptor::isNameSpace() const {
191   return DbgNode && getTag() == dwarf::DW_TAG_namespace;
192 }
193
194 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
195 bool DIDescriptor::isLexicalBlock() const {
196   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block;
197 }
198
199 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
200 bool DIDescriptor::isSubrange() const {
201   return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
202 }
203
204 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
205 bool DIDescriptor::isEnumerator() const {
206   return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
207 }
208
209 //===----------------------------------------------------------------------===//
210 // Simple Descriptor Constructors and other Methods
211 //===----------------------------------------------------------------------===//
212
213 DIType::DIType(const MDNode *N) : DIScope(N) {
214   if (!N) return;
215   if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
216     DbgNode = 0;
217   }
218 }
219
220 unsigned DIArray::getNumElements() const {
221   if (!DbgNode)
222     return 0;
223   return DbgNode->getNumOperands();
224 }
225
226 /// replaceAllUsesWith - Replace all uses of debug info referenced by
227 /// this descriptor. After this completes, the current debug info value
228 /// is erased.
229 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
230   if (!DbgNode)
231     return;
232
233   // Since we use a TrackingVH for the node, its easy for clients to manufacture
234   // legitimate situations where they want to replaceAllUsesWith() on something
235   // which, due to uniquing, has merged with the source. We shield clients from
236   // this detail by allowing a value to be replaced with replaceAllUsesWith()
237   // itself.
238   if (DbgNode != D) {
239     MDNode *Node = const_cast<MDNode*>(DbgNode);
240     const MDNode *DN = D;
241     const Value *V = cast_or_null<Value>(DN);
242     Node->replaceAllUsesWith(const_cast<Value*>(V));
243     Node->destroy();
244   }
245 }
246
247 /// Verify - Verify that a compile unit is well formed.
248 bool DICompileUnit::Verify() const {
249   if (!DbgNode)
250     return false;
251   StringRef N = getFilename();
252   if (N.empty())
253     return false;
254   // It is possible that directory and produce string is empty.
255   return true;
256 }
257
258 /// Verify - Verify that a type descriptor is well formed.
259 bool DIType::Verify() const {
260   if (!DbgNode)
261     return false;
262   if (!getContext().Verify())
263     return false;
264
265   DICompileUnit CU = getCompileUnit();
266   if (!CU.Verify())
267     return false;
268   return true;
269 }
270
271 /// Verify - Verify that a composite type descriptor is well formed.
272 bool DICompositeType::Verify() const {
273   if (!DbgNode)
274     return false;
275   if (!getContext().Verify())
276     return false;
277
278   DICompileUnit CU = getCompileUnit();
279   if (!CU.Verify())
280     return false;
281   return true;
282 }
283
284 /// Verify - Verify that a subprogram descriptor is well formed.
285 bool DISubprogram::Verify() const {
286   if (!DbgNode)
287     return false;
288
289   if (!getContext().Verify())
290     return false;
291
292   DICompileUnit CU = getCompileUnit();
293   if (!CU.Verify())
294     return false;
295
296   DICompositeType Ty = getType();
297   if (!Ty.Verify())
298     return false;
299   return true;
300 }
301
302 /// Verify - Verify that a global variable descriptor is well formed.
303 bool DIGlobalVariable::Verify() const {
304   if (!DbgNode)
305     return false;
306
307   if (getDisplayName().empty())
308     return false;
309
310   if (!getContext().Verify())
311     return false;
312
313   DICompileUnit CU = getCompileUnit();
314   if (!CU.Verify())
315     return false;
316
317   DIType Ty = getType();
318   if (!Ty.Verify())
319     return false;
320
321   if (!getGlobal())
322     return false;
323
324   return true;
325 }
326
327 /// Verify - Verify that a variable descriptor is well formed.
328 bool DIVariable::Verify() const {
329   if (!DbgNode)
330     return false;
331
332   if (!getContext().Verify())
333     return false;
334
335   if (!getCompileUnit().Verify())
336     return false;
337
338   DIType Ty = getType();
339   if (!Ty.Verify())
340     return false;
341
342   return true;
343 }
344
345 /// Verify - Verify that a location descriptor is well formed.
346 bool DILocation::Verify() const {
347   if (!DbgNode)
348     return false;
349   
350   return DbgNode->getNumOperands() == 4;
351 }
352
353 /// Verify - Verify that a namespace descriptor is well formed.
354 bool DINameSpace::Verify() const {
355   if (!DbgNode)
356     return false;
357   if (getName().empty())
358     return false;
359   if (!getCompileUnit().Verify())
360     return false;
361   return true;
362 }
363
364 /// getOriginalTypeSize - If this type is derived from a base type then
365 /// return base type size.
366 uint64_t DIDerivedType::getOriginalTypeSize() const {
367   unsigned Tag = getTag();
368   if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef ||
369       Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
370       Tag == dwarf::DW_TAG_restrict_type) {
371     DIType BaseType = getTypeDerivedFrom();
372     // If this type is not derived from any type then take conservative 
373     // approach.
374     if (!BaseType.isValid())
375       return getSizeInBits();
376     if (BaseType.isDerivedType())
377       return DIDerivedType(BaseType).getOriginalTypeSize();
378     else
379       return BaseType.getSizeInBits();
380   }
381     
382   return getSizeInBits();
383 }
384
385 /// isInlinedFnArgument - Return trule if this variable provides debugging
386 /// information for an inlined function arguments.
387 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
388   assert(CurFn && "Invalid function");
389   if (!getContext().isSubprogram())
390     return false;
391   // This variable is not inlined function argument if its scope 
392   // does not describe current function.
393   return !(DISubprogram(getContext()).describes(CurFn));
394 }
395
396 /// describes - Return true if this subprogram provides debugging
397 /// information for the function F.
398 bool DISubprogram::describes(const Function *F) {
399   assert(F && "Invalid function");
400   StringRef Name = getLinkageName();
401   if (Name.empty())
402     Name = getName();
403   if (F->getName() == Name)
404     return true;
405   return false;
406 }
407
408 unsigned DISubprogram::isOptimized() const     {
409   assert (DbgNode && "Invalid subprogram descriptor!");
410   if (DbgNode->getNumOperands() == 16)
411     return getUnsignedField(15);
412   return 0;
413 }
414
415 StringRef DIScope::getFilename() const {
416   if (!DbgNode)
417     return StringRef();
418   if (isLexicalBlock()) 
419     return DILexicalBlock(DbgNode).getFilename();
420   if (isSubprogram())
421     return DISubprogram(DbgNode).getFilename();
422   if (isCompileUnit())
423     return DICompileUnit(DbgNode).getFilename();
424   if (isNameSpace())
425     return DINameSpace(DbgNode).getFilename();
426   if (isType())
427     return DIType(DbgNode).getFilename();
428   if (isFile())
429     return DIFile(DbgNode).getFilename();
430   assert(0 && "Invalid DIScope!");
431   return StringRef();
432 }
433
434 StringRef DIScope::getDirectory() const {
435   if (!DbgNode)
436     return StringRef();
437   if (isLexicalBlock()) 
438     return DILexicalBlock(DbgNode).getDirectory();
439   if (isSubprogram())
440     return DISubprogram(DbgNode).getDirectory();
441   if (isCompileUnit())
442     return DICompileUnit(DbgNode).getDirectory();
443   if (isNameSpace())
444     return DINameSpace(DbgNode).getDirectory();
445   if (isType())
446     return DIType(DbgNode).getDirectory();
447   if (isFile())
448     return DIFile(DbgNode).getDirectory();
449   assert(0 && "Invalid DIScope!");
450   return StringRef();
451 }
452
453 //===----------------------------------------------------------------------===//
454 // DIDescriptor: dump routines for all descriptors.
455 //===----------------------------------------------------------------------===//
456
457
458 /// print - Print descriptor.
459 void DIDescriptor::print(raw_ostream &OS) const {
460   OS << "[" << dwarf::TagString(getTag()) << "] ";
461   OS.write_hex((intptr_t) &*DbgNode) << ']';
462 }
463
464 /// print - Print compile unit.
465 void DICompileUnit::print(raw_ostream &OS) const {
466   if (getLanguage())
467     OS << " [" << dwarf::LanguageString(getLanguage()) << "] ";
468
469   OS << " [" << getDirectory() << "/" << getFilename() << " ]";
470 }
471
472 /// print - Print type.
473 void DIType::print(raw_ostream &OS) const {
474   if (!DbgNode) return;
475
476   StringRef Res = getName();
477   if (!Res.empty())
478     OS << " [" << Res << "] ";
479
480   unsigned Tag = getTag();
481   OS << " [" << dwarf::TagString(Tag) << "] ";
482
483   // TODO : Print context
484   getCompileUnit().print(OS);
485   OS << " ["
486          << "line " << getLineNumber() << ", "
487          << getSizeInBits() << " bits, "
488          << getAlignInBits() << " bit alignment, "
489          << getOffsetInBits() << " bit offset"
490          << "] ";
491
492   if (isPrivate())
493     OS << " [private] ";
494   else if (isProtected())
495     OS << " [protected] ";
496
497   if (isForwardDecl())
498     OS << " [fwd] ";
499
500   if (isBasicType())
501     DIBasicType(DbgNode).print(OS);
502   else if (isDerivedType())
503     DIDerivedType(DbgNode).print(OS);
504   else if (isCompositeType())
505     DICompositeType(DbgNode).print(OS);
506   else {
507     OS << "Invalid DIType\n";
508     return;
509   }
510
511   OS << "\n";
512 }
513
514 /// print - Print basic type.
515 void DIBasicType::print(raw_ostream &OS) const {
516   OS << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
517 }
518
519 /// print - Print derived type.
520 void DIDerivedType::print(raw_ostream &OS) const {
521   OS << "\n\t Derived From: "; getTypeDerivedFrom().print(OS);
522 }
523
524 /// print - Print composite type.
525 void DICompositeType::print(raw_ostream &OS) const {
526   DIArray A = getTypeArray();
527   OS << " [" << A.getNumElements() << " elements]";
528 }
529
530 /// print - Print subprogram.
531 void DISubprogram::print(raw_ostream &OS) const {
532   StringRef Res = getName();
533   if (!Res.empty())
534     OS << " [" << Res << "] ";
535
536   unsigned Tag = getTag();
537   OS << " [" << dwarf::TagString(Tag) << "] ";
538
539   // TODO : Print context
540   getCompileUnit().print(OS);
541   OS << " [" << getLineNumber() << "] ";
542
543   if (isLocalToUnit())
544     OS << " [local] ";
545
546   if (isDefinition())
547     OS << " [def] ";
548
549   OS << "\n";
550 }
551
552 /// print - Print global variable.
553 void DIGlobalVariable::print(raw_ostream &OS) const {
554   OS << " [";
555   StringRef Res = getName();
556   if (!Res.empty())
557     OS << " [" << Res << "] ";
558
559   unsigned Tag = getTag();
560   OS << " [" << dwarf::TagString(Tag) << "] ";
561
562   // TODO : Print context
563   getCompileUnit().print(OS);
564   OS << " [" << getLineNumber() << "] ";
565
566   if (isLocalToUnit())
567     OS << " [local] ";
568
569   if (isDefinition())
570     OS << " [def] ";
571
572   if (isGlobalVariable())
573     DIGlobalVariable(DbgNode).print(OS);
574   OS << "]\n";
575 }
576
577 /// print - Print variable.
578 void DIVariable::print(raw_ostream &OS) const {
579   StringRef Res = getName();
580   if (!Res.empty())
581     OS << " [" << Res << "] ";
582
583   getCompileUnit().print(OS);
584   OS << " [" << getLineNumber() << "] ";
585   getType().print(OS);
586   OS << "\n";
587
588   // FIXME: Dump complex addresses
589 }
590
591 /// dump - Print descriptor to dbgs() with a newline.
592 void DIDescriptor::dump() const {
593   print(dbgs()); dbgs() << '\n';
594 }
595
596 /// dump - Print compile unit to dbgs() with a newline.
597 void DICompileUnit::dump() const {
598   print(dbgs()); dbgs() << '\n';
599 }
600
601 /// dump - Print type to dbgs() with a newline.
602 void DIType::dump() const {
603   print(dbgs()); dbgs() << '\n';
604 }
605
606 /// dump - Print basic type to dbgs() with a newline.
607 void DIBasicType::dump() const {
608   print(dbgs()); dbgs() << '\n';
609 }
610
611 /// dump - Print derived type to dbgs() with a newline.
612 void DIDerivedType::dump() const {
613   print(dbgs()); dbgs() << '\n';
614 }
615
616 /// dump - Print composite type to dbgs() with a newline.
617 void DICompositeType::dump() const {
618   print(dbgs()); dbgs() << '\n';
619 }
620
621 /// dump - Print subprogram to dbgs() with a newline.
622 void DISubprogram::dump() const {
623   print(dbgs()); dbgs() << '\n';
624 }
625
626 /// dump - Print global variable.
627 void DIGlobalVariable::dump() const {
628   print(dbgs()); dbgs() << '\n';
629 }
630
631 /// dump - Print variable.
632 void DIVariable::dump() const {
633   print(dbgs()); dbgs() << '\n';
634 }
635
636 //===----------------------------------------------------------------------===//
637 // DIFactory: Basic Helpers
638 //===----------------------------------------------------------------------===//
639
640 DIFactory::DIFactory(Module &m)
641   : M(m), VMContext(M.getContext()), DeclareFn(0), ValueFn(0) {}
642
643 Constant *DIFactory::GetTagConstant(unsigned TAG) {
644   assert((TAG & LLVMDebugVersionMask) == 0 &&
645          "Tag too large for debug encoding!");
646   return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
647 }
648
649 //===----------------------------------------------------------------------===//
650 // DIFactory: Primary Constructors
651 //===----------------------------------------------------------------------===//
652
653 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
654 /// This implicitly uniques the arrays created.
655 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
656   SmallVector<Value*, 16> Elts;
657
658   if (NumTys == 0)
659     Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
660   else
661     for (unsigned i = 0; i != NumTys; ++i)
662       Elts.push_back(Tys[i]);
663
664   return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
665 }
666
667 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
668 /// implicitly uniques the values returned.
669 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
670   Value *Elts[] = {
671     GetTagConstant(dwarf::DW_TAG_subrange_type),
672     ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
673     ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
674   };
675
676   return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
677 }
678
679
680
681 /// CreateCompileUnit - Create a new descriptor for the specified compile
682 /// unit.  Note that this does not unique compile units within the module.
683 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
684                                            StringRef Filename,
685                                            StringRef Directory,
686                                            StringRef Producer,
687                                            bool isMain,
688                                            bool isOptimized,
689                                            StringRef Flags,
690                                            unsigned RunTimeVer) {
691   Value *Elts[] = {
692     GetTagConstant(dwarf::DW_TAG_compile_unit),
693     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
694     ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
695     MDString::get(VMContext, Filename),
696     MDString::get(VMContext, Directory),
697     MDString::get(VMContext, Producer),
698     ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
699     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
700     MDString::get(VMContext, Flags),
701     ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
702   };
703
704   return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
705 }
706
707 /// CreateFile -  Create a new descriptor for the specified file.
708 DIFile DIFactory::CreateFile(StringRef Filename,
709                              StringRef Directory,
710                              DICompileUnit CU) {
711   Value *Elts[] = {
712     GetTagConstant(dwarf::DW_TAG_file_type),
713     MDString::get(VMContext, Filename),
714     MDString::get(VMContext, Directory),
715     CU
716   };
717
718   return DIFile(MDNode::get(VMContext, &Elts[0], 4));
719 }
720
721 /// CreateEnumerator - Create a single enumerator value.
722 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
723   Value *Elts[] = {
724     GetTagConstant(dwarf::DW_TAG_enumerator),
725     MDString::get(VMContext, Name),
726     ConstantInt::get(Type::getInt64Ty(VMContext), Val)
727   };
728   return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
729 }
730
731
732 /// CreateBasicType - Create a basic type like int, float, etc.
733 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
734                                        StringRef Name,
735                                        DIFile F,
736                                        unsigned LineNumber,
737                                        uint64_t SizeInBits,
738                                        uint64_t AlignInBits,
739                                        uint64_t OffsetInBits, unsigned Flags,
740                                        unsigned Encoding) {
741   Value *Elts[] = {
742     GetTagConstant(dwarf::DW_TAG_base_type),
743     Context,
744     MDString::get(VMContext, Name),
745     F,
746     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
747     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
748     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
749     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
750     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
751     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
752   };
753   return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
754 }
755
756
757 /// CreateBasicType - Create a basic type like int, float, etc.
758 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
759                                          StringRef Name,
760                                          DIFile F,
761                                          unsigned LineNumber,
762                                          Constant *SizeInBits,
763                                          Constant *AlignInBits,
764                                          Constant *OffsetInBits, unsigned Flags,
765                                          unsigned Encoding) {
766   Value *Elts[] = {
767     GetTagConstant(dwarf::DW_TAG_base_type),
768     Context,
769     MDString::get(VMContext, Name),
770     F,
771     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
772     SizeInBits,
773     AlignInBits,
774     OffsetInBits,
775     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
776     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
777   };
778   return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
779 }
780
781 /// CreateArtificialType - Create a new DIType with "artificial" flag set.
782 DIType DIFactory::CreateArtificialType(DIType Ty) {
783   if (Ty.isArtificial())
784     return Ty;
785
786   SmallVector<Value *, 9> Elts;
787   MDNode *N = Ty;
788   assert (N && "Unexpected input DIType!");
789   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
790     if (Value *V = N->getOperand(i))
791       Elts.push_back(V);
792     else
793       Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext)));
794   }
795
796   unsigned CurFlags = Ty.getFlags();
797   CurFlags = CurFlags | DIType::FlagArtificial;
798
799   // Flags are stored at this slot.
800   Elts[8] =  ConstantInt::get(Type::getInt32Ty(VMContext), CurFlags);
801
802   return DIType(MDNode::get(VMContext, Elts.data(), Elts.size()));
803 }
804
805 /// CreateDerivedType - Create a derived type like const qualified type,
806 /// pointer, typedef, etc.
807 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
808                                            DIDescriptor Context,
809                                            StringRef Name,
810                                            DIFile F,
811                                            unsigned LineNumber,
812                                            uint64_t SizeInBits,
813                                            uint64_t AlignInBits,
814                                            uint64_t OffsetInBits,
815                                            unsigned Flags,
816                                            DIType DerivedFrom) {
817   Value *Elts[] = {
818     GetTagConstant(Tag),
819     Context,
820     MDString::get(VMContext, Name),
821     F,
822     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
823     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
824     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
825     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
826     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
827     DerivedFrom,
828   };
829   return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
830 }
831
832
833 /// CreateDerivedType - Create a derived type like const qualified type,
834 /// pointer, typedef, etc.
835 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
836                                              DIDescriptor Context,
837                                              StringRef Name,
838                                              DIFile F,
839                                              unsigned LineNumber,
840                                              Constant *SizeInBits,
841                                              Constant *AlignInBits,
842                                              Constant *OffsetInBits,
843                                              unsigned Flags,
844                                              DIType DerivedFrom) {
845   Value *Elts[] = {
846     GetTagConstant(Tag),
847     Context,
848     MDString::get(VMContext, Name),
849     F,
850     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
851     SizeInBits,
852     AlignInBits,
853     OffsetInBits,
854     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
855     DerivedFrom,
856   };
857   return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
858 }
859
860
861 /// CreateCompositeType - Create a composite type like array, struct, etc.
862 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
863                                                DIDescriptor Context,
864                                                StringRef Name,
865                                                DIFile F,
866                                                unsigned LineNumber,
867                                                uint64_t SizeInBits,
868                                                uint64_t AlignInBits,
869                                                uint64_t OffsetInBits,
870                                                unsigned Flags,
871                                                DIType DerivedFrom,
872                                                DIArray Elements,
873                                                unsigned RuntimeLang,
874                                                MDNode *ContainingType) {
875
876   Value *Elts[] = {
877     GetTagConstant(Tag),
878     Context,
879     MDString::get(VMContext, Name),
880     F,
881     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
882     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
883     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
884     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
885     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
886     DerivedFrom,
887     Elements,
888     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang),
889     ContainingType
890   };
891   return DICompositeType(MDNode::get(VMContext, &Elts[0], 13));
892 }
893
894
895 /// CreateCompositeType - Create a composite type like array, struct, etc.
896 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
897                                                  DIDescriptor Context,
898                                                  StringRef Name,
899                                                  DIFile F,
900                                                  unsigned LineNumber,
901                                                  Constant *SizeInBits,
902                                                  Constant *AlignInBits,
903                                                  Constant *OffsetInBits,
904                                                  unsigned Flags,
905                                                  DIType DerivedFrom,
906                                                  DIArray Elements,
907                                                  unsigned RuntimeLang) {
908
909   Value *Elts[] = {
910     GetTagConstant(Tag),
911     Context,
912     MDString::get(VMContext, Name),
913     F,
914     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
915     SizeInBits,
916     AlignInBits,
917     OffsetInBits,
918     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
919     DerivedFrom,
920     Elements,
921     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
922   };
923   return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
924 }
925
926
927 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
928 /// See comments in DISubprogram for descriptions of these fields.  This
929 /// method does not unique the generated descriptors.
930 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
931                                          StringRef Name,
932                                          StringRef DisplayName,
933                                          StringRef LinkageName,
934                                          DIFile F,
935                                          unsigned LineNo, DIType Ty,
936                                          bool isLocalToUnit,
937                                          bool isDefinition,
938                                          unsigned VK, unsigned VIndex,
939                                          DIType ContainingType,
940                                          bool isArtificial,
941                                          bool isOptimized) {
942
943   Value *Elts[] = {
944     GetTagConstant(dwarf::DW_TAG_subprogram),
945     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
946     Context,
947     MDString::get(VMContext, Name),
948     MDString::get(VMContext, DisplayName),
949     MDString::get(VMContext, LinkageName),
950     F,
951     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
952     Ty,
953     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
954     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
955     ConstantInt::get(Type::getInt32Ty(VMContext), (unsigned)VK),
956     ConstantInt::get(Type::getInt32Ty(VMContext), VIndex),
957     ContainingType,
958     ConstantInt::get(Type::getInt1Ty(VMContext), isArtificial),
959     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized)
960   };
961   return DISubprogram(MDNode::get(VMContext, &Elts[0], 16));
962 }
963
964 /// CreateSubprogramDefinition - Create new subprogram descriptor for the
965 /// given declaration. 
966 DISubprogram DIFactory::CreateSubprogramDefinition(DISubprogram &SPDeclaration) {
967   if (SPDeclaration.isDefinition())
968     return DISubprogram(SPDeclaration);
969
970   MDNode *DeclNode = SPDeclaration;
971   Value *Elts[] = {
972     GetTagConstant(dwarf::DW_TAG_subprogram),
973     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
974     DeclNode->getOperand(2), // Context
975     DeclNode->getOperand(3), // Name
976     DeclNode->getOperand(4), // DisplayName
977     DeclNode->getOperand(5), // LinkageName
978     DeclNode->getOperand(6), // CompileUnit
979     DeclNode->getOperand(7), // LineNo
980     DeclNode->getOperand(8), // Type
981     DeclNode->getOperand(9), // isLocalToUnit
982     ConstantInt::get(Type::getInt1Ty(VMContext), true),
983     DeclNode->getOperand(11), // Virtuality
984     DeclNode->getOperand(12), // VIndex
985     DeclNode->getOperand(13), // Containting Type
986     DeclNode->getOperand(14), // isArtificial
987     DeclNode->getOperand(15)  // isOptimized
988   };
989   return DISubprogram(MDNode::get(VMContext, &Elts[0], 16));
990 }
991
992 /// CreateGlobalVariable - Create a new descriptor for the specified global.
993 DIGlobalVariable
994 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
995                                 StringRef DisplayName,
996                                 StringRef LinkageName,
997                                 DIFile F,
998                                 unsigned LineNo, DIType Ty,bool isLocalToUnit,
999                                 bool isDefinition, llvm::GlobalVariable *Val) {
1000   Value *Elts[] = {
1001     GetTagConstant(dwarf::DW_TAG_variable),
1002     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1003     Context,
1004     MDString::get(VMContext, Name),
1005     MDString::get(VMContext, DisplayName),
1006     MDString::get(VMContext, LinkageName),
1007     F,
1008     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1009     Ty,
1010     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1011     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1012     Val
1013   };
1014
1015   Value *const *Vs = &Elts[0];
1016   MDNode *Node = MDNode::get(VMContext,Vs, 12);
1017
1018   // Create a named metadata so that we do not lose this mdnode.
1019   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
1020   NMD->addOperand(Node);
1021
1022   return DIGlobalVariable(Node);
1023 }
1024
1025
1026 /// CreateVariable - Create a new descriptor for the specified variable.
1027 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
1028                                      StringRef Name,
1029                                      DIFile F,
1030                                      unsigned LineNo,
1031                                      DIType Ty) {
1032   Value *Elts[] = {
1033     GetTagConstant(Tag),
1034     Context,
1035     MDString::get(VMContext, Name),
1036     F,
1037     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1038     Ty,
1039   };
1040   return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
1041 }
1042
1043
1044 /// CreateComplexVariable - Create a new descriptor for the specified variable
1045 /// which has a complex address expression for its address.
1046 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
1047                                             const std::string &Name,
1048                                             DIFile F,
1049                                             unsigned LineNo,
1050                                             DIType Ty, 
1051                                             SmallVector<Value *, 9> &addr) {
1052   SmallVector<Value *, 9> Elts;
1053   Elts.push_back(GetTagConstant(Tag));
1054   Elts.push_back(Context);
1055   Elts.push_back(MDString::get(VMContext, Name));
1056   Elts.push_back(F);
1057   Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
1058   Elts.push_back(Ty);
1059   Elts.insert(Elts.end(), addr.begin(), addr.end());
1060
1061   return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
1062 }
1063
1064
1065 /// CreateBlock - This creates a descriptor for a lexical block with the
1066 /// specified parent VMContext.
1067 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context,
1068                                              unsigned LineNo, unsigned Col) {
1069   Value *Elts[] = {
1070     GetTagConstant(dwarf::DW_TAG_lexical_block),
1071     Context,
1072     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1073     ConstantInt::get(Type::getInt32Ty(VMContext), Col)
1074   };
1075   return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 4));
1076 }
1077
1078 /// CreateNameSpace - This creates new descriptor for a namespace
1079 /// with the specified parent context.
1080 DINameSpace DIFactory::CreateNameSpace(DIDescriptor Context, StringRef Name,
1081                                        DIFile F,
1082                                        unsigned LineNo) {
1083   Value *Elts[] = {
1084     GetTagConstant(dwarf::DW_TAG_namespace),
1085     Context,
1086     MDString::get(VMContext, Name),
1087     F,
1088     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
1089   };
1090   return DINameSpace(MDNode::get(VMContext, &Elts[0], 5));
1091 }
1092
1093 /// CreateLocation - Creates a debug info location.
1094 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1095                                      DIScope S, DILocation OrigLoc) {
1096   Value *Elts[] = {
1097     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1098     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1099     S,
1100     OrigLoc,
1101   };
1102   return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1103 }
1104
1105 /// CreateLocation - Creates a debug info location.
1106 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1107                                      DIScope S, MDNode *OrigLoc) {
1108  Value *Elts[] = {
1109     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1110     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1111     S,
1112     OrigLoc
1113   };
1114   return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1115 }
1116
1117 //===----------------------------------------------------------------------===//
1118 // DIFactory: Routines for inserting code into a function
1119 //===----------------------------------------------------------------------===//
1120
1121 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1122 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1123                                       Instruction *InsertBefore) {
1124   assert(Storage && "no storage passed to dbg.declare");
1125   assert(D.Verify() && "empty DIVariable passed to dbg.declare");
1126   if (!DeclareFn)
1127     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1128
1129   Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1130                     D };
1131   return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1132 }
1133
1134 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1135 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1136                                       BasicBlock *InsertAtEnd) {
1137   assert(Storage && "no storage passed to dbg.declare");
1138   assert(D.Verify() && "invalid DIVariable passed to dbg.declare");
1139   if (!DeclareFn)
1140     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1141
1142   Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1143                     D };
1144
1145   // If this block already has a terminator then insert this intrinsic
1146   // before the terminator.
1147   if (TerminatorInst *T = InsertAtEnd->getTerminator()) 
1148     return CallInst::Create(DeclareFn, Args, Args+2, "", T);
1149   else
1150     return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);}
1151
1152 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1153 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1154                                                 DIVariable D,
1155                                                 Instruction *InsertBefore) {
1156   assert(V && "no value passed to dbg.value");
1157   assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1158   if (!ValueFn)
1159     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1160
1161   Value *Args[] = { MDNode::get(V->getContext(), &V, 1),
1162                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1163                     D };
1164   return CallInst::Create(ValueFn, Args, Args+3, "", InsertBefore);
1165 }
1166
1167 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1168 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1169                                                 DIVariable D,
1170                                                 BasicBlock *InsertAtEnd) {
1171   assert(V && "no value passed to dbg.value");
1172   assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1173   if (!ValueFn)
1174     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1175
1176   Value *Args[] = { MDNode::get(V->getContext(), &V, 1), 
1177                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1178                     D };
1179   return CallInst::Create(ValueFn, Args, Args+3, "", InsertAtEnd);
1180 }
1181
1182 //===----------------------------------------------------------------------===//
1183 // DebugInfoFinder implementations.
1184 //===----------------------------------------------------------------------===//
1185
1186 /// processModule - Process entire module and collect debug info.
1187 void DebugInfoFinder::processModule(Module &M) {
1188   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1189     for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1190       for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1191            ++BI) {
1192         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1193           processDeclare(DDI);
1194         
1195         DebugLoc Loc = BI->getDebugLoc();
1196         if (Loc.isUnknown())
1197           continue;
1198         
1199         LLVMContext &Ctx = BI->getContext();
1200         DIDescriptor Scope(Loc.getScope(Ctx));
1201         
1202         if (Scope.isCompileUnit())
1203           addCompileUnit(DICompileUnit(Scope));
1204         else if (Scope.isSubprogram())
1205           processSubprogram(DISubprogram(Scope));
1206         else if (Scope.isLexicalBlock())
1207           processLexicalBlock(DILexicalBlock(Scope));
1208         
1209         if (MDNode *IA = Loc.getInlinedAt(Ctx))
1210           processLocation(DILocation(IA));
1211       }
1212
1213   NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
1214   if (!NMD)
1215     return;
1216
1217   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1218     DIGlobalVariable DIG(cast<MDNode>(NMD->getOperand(i)));
1219     if (addGlobalVariable(DIG)) {
1220       addCompileUnit(DIG.getCompileUnit());
1221       processType(DIG.getType());
1222     }
1223   }
1224 }
1225
1226 /// processLocation - Process DILocation.
1227 void DebugInfoFinder::processLocation(DILocation Loc) {
1228   if (!Loc.Verify()) return;
1229   DIDescriptor S(Loc.getScope());
1230   if (S.isCompileUnit())
1231     addCompileUnit(DICompileUnit(S));
1232   else if (S.isSubprogram())
1233     processSubprogram(DISubprogram(S));
1234   else if (S.isLexicalBlock())
1235     processLexicalBlock(DILexicalBlock(S));
1236   processLocation(Loc.getOrigLocation());
1237 }
1238
1239 /// processType - Process DIType.
1240 void DebugInfoFinder::processType(DIType DT) {
1241   if (!addType(DT))
1242     return;
1243
1244   addCompileUnit(DT.getCompileUnit());
1245   if (DT.isCompositeType()) {
1246     DICompositeType DCT(DT);
1247     processType(DCT.getTypeDerivedFrom());
1248     DIArray DA = DCT.getTypeArray();
1249     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1250       DIDescriptor D = DA.getElement(i);
1251       if (D.isType())
1252         processType(DIType(D));
1253       else if (D.isSubprogram())
1254         processSubprogram(DISubprogram(D));
1255     }
1256   } else if (DT.isDerivedType()) {
1257     DIDerivedType DDT(DT);
1258     processType(DDT.getTypeDerivedFrom());
1259   }
1260 }
1261
1262 /// processLexicalBlock
1263 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1264   DIScope Context = LB.getContext();
1265   if (Context.isLexicalBlock())
1266     return processLexicalBlock(DILexicalBlock(Context));
1267   else
1268     return processSubprogram(DISubprogram(Context));
1269 }
1270
1271 /// processSubprogram - Process DISubprogram.
1272 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1273   if (!addSubprogram(SP))
1274     return;
1275   addCompileUnit(SP.getCompileUnit());
1276   processType(SP.getType());
1277 }
1278
1279 /// processDeclare - Process DbgDeclareInst.
1280 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1281   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1282   if (!N) return;
1283
1284   DIDescriptor DV(N);
1285   if (!DV.isVariable())
1286     return;
1287
1288   if (!NodesSeen.insert(DV))
1289     return;
1290
1291   addCompileUnit(DIVariable(N).getCompileUnit());
1292   processType(DIVariable(N).getType());
1293 }
1294
1295 /// addType - Add type into Tys.
1296 bool DebugInfoFinder::addType(DIType DT) {
1297   if (!DT.isValid())
1298     return false;
1299
1300   if (!NodesSeen.insert(DT))
1301     return false;
1302
1303   TYs.push_back(DT);
1304   return true;
1305 }
1306
1307 /// addCompileUnit - Add compile unit into CUs.
1308 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1309   if (!CU.Verify())
1310     return false;
1311
1312   if (!NodesSeen.insert(CU))
1313     return false;
1314
1315   CUs.push_back(CU);
1316   return true;
1317 }
1318
1319 /// addGlobalVariable - Add global variable into GVs.
1320 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1321   if (!DIDescriptor(DIG).isGlobalVariable())
1322     return false;
1323
1324   if (!NodesSeen.insert(DIG))
1325     return false;
1326
1327   GVs.push_back(DIG);
1328   return true;
1329 }
1330
1331 // addSubprogram - Add subprgoram into SPs.
1332 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1333   if (!DIDescriptor(SP).isSubprogram())
1334     return false;
1335
1336   if (!NodesSeen.insert(SP))
1337     return false;
1338
1339   SPs.push_back(SP);
1340   return true;
1341 }
1342
1343 /// Find the debug info descriptor corresponding to this global variable.
1344 static Value *findDbgGlobalDeclare(GlobalVariable *V) {
1345   const Module *M = V->getParent();
1346   NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1347   if (!NMD)
1348     return 0;
1349
1350   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1351     DIDescriptor DIG(cast_or_null<MDNode>(NMD->getOperand(i)));
1352     if (!DIG.isGlobalVariable())
1353       continue;
1354     if (DIGlobalVariable(DIG).getGlobal() == V)
1355       return DIG;
1356   }
1357   return 0;
1358 }
1359
1360 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1361 /// It looks through pointer casts too.
1362 static const DbgDeclareInst *findDbgDeclare(const Value *V) {
1363   V = V->stripPointerCasts();
1364   
1365   if (!isa<Instruction>(V) && !isa<Argument>(V))
1366     return 0;
1367     
1368   const Function *F = NULL;
1369   if (const Instruction *I = dyn_cast<Instruction>(V))
1370     F = I->getParent()->getParent();
1371   else if (const Argument *A = dyn_cast<Argument>(V))
1372     F = A->getParent();
1373   
1374   for (Function::const_iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
1375     for (BasicBlock::const_iterator BI = (*FI).begin(), BE = (*FI).end();
1376          BI != BE; ++BI)
1377       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1378         if (DDI->getAddress() == V)
1379           return DDI;
1380
1381   return 0;
1382 }
1383
1384 bool llvm::getLocationInfo(const Value *V, std::string &DisplayName,
1385                            std::string &Type, unsigned &LineNo,
1386                            std::string &File, std::string &Dir) {
1387   DICompileUnit Unit;
1388   DIType TypeD;
1389
1390   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1391     Value *DIGV = findDbgGlobalDeclare(GV);
1392     if (!DIGV) return false;
1393     DIGlobalVariable Var(cast<MDNode>(DIGV));
1394
1395     StringRef D = Var.getDisplayName();
1396     if (!D.empty())
1397       DisplayName = D;
1398     LineNo = Var.getLineNumber();
1399     Unit = Var.getCompileUnit();
1400     TypeD = Var.getType();
1401   } else {
1402     const DbgDeclareInst *DDI = findDbgDeclare(V);
1403     if (!DDI) return false;
1404     DIVariable Var(cast<MDNode>(DDI->getVariable()));
1405
1406     StringRef D = Var.getName();
1407     if (!D.empty())
1408       DisplayName = D;
1409     LineNo = Var.getLineNumber();
1410     Unit = Var.getCompileUnit();
1411     TypeD = Var.getType();
1412   }
1413
1414   StringRef T = TypeD.getName();
1415   if (!T.empty())
1416     Type = T;
1417   StringRef F = Unit.getFilename();
1418   if (!F.empty())
1419     File = F;
1420   StringRef D = Unit.getDirectory();
1421   if (!D.empty())
1422     Dir = D;
1423   return true;
1424 }
1425
1426 /// getDISubprogram - Find subprogram that is enclosing this scope.
1427 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
1428   DIDescriptor D(Scope);
1429   if (D.isSubprogram())
1430     return DISubprogram(Scope);
1431   
1432   if (D.isLexicalBlock())
1433     return getDISubprogram(DILexicalBlock(Scope).getContext());
1434   
1435   return DISubprogram();
1436 }
1437
1438 /// getDICompositeType - Find underlying composite type.
1439 DICompositeType llvm::getDICompositeType(DIType T) {
1440   if (T.isCompositeType())
1441     return DICompositeType(T);
1442   
1443   if (T.isDerivedType())
1444     return getDICompositeType(DIDerivedType(T).getTypeDerivedFrom());
1445   
1446   return DICompositeType();
1447 }