194811be903fe667b37b7fe48f78c425fa526263
[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, bool OptimizedBuild) {
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   MDNode *Node = MDNode::get(VMContext, &Elts[0], 6);
1041   if (OptimizedBuild) {
1042     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.lv");
1043     NMD->addOperand(Node);
1044   }
1045   return DIVariable(Node);
1046 }
1047
1048
1049 /// CreateComplexVariable - Create a new descriptor for the specified variable
1050 /// which has a complex address expression for its address.
1051 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
1052                                             const std::string &Name,
1053                                             DIFile F,
1054                                             unsigned LineNo,
1055                                             DIType Ty, 
1056                                             SmallVector<Value *, 9> &addr) {
1057   SmallVector<Value *, 9> Elts;
1058   Elts.push_back(GetTagConstant(Tag));
1059   Elts.push_back(Context);
1060   Elts.push_back(MDString::get(VMContext, Name));
1061   Elts.push_back(F);
1062   Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
1063   Elts.push_back(Ty);
1064   Elts.insert(Elts.end(), addr.begin(), addr.end());
1065
1066   return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
1067 }
1068
1069
1070 /// CreateBlock - This creates a descriptor for a lexical block with the
1071 /// specified parent VMContext.
1072 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context,
1073                                              unsigned LineNo, unsigned Col) {
1074   Value *Elts[] = {
1075     GetTagConstant(dwarf::DW_TAG_lexical_block),
1076     Context,
1077     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1078     ConstantInt::get(Type::getInt32Ty(VMContext), Col)
1079   };
1080   return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 4));
1081 }
1082
1083 /// CreateNameSpace - This creates new descriptor for a namespace
1084 /// with the specified parent context.
1085 DINameSpace DIFactory::CreateNameSpace(DIDescriptor Context, StringRef Name,
1086                                        DIFile F,
1087                                        unsigned LineNo) {
1088   Value *Elts[] = {
1089     GetTagConstant(dwarf::DW_TAG_namespace),
1090     Context,
1091     MDString::get(VMContext, Name),
1092     F,
1093     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
1094   };
1095   return DINameSpace(MDNode::get(VMContext, &Elts[0], 5));
1096 }
1097
1098 /// CreateLocation - Creates a debug info location.
1099 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1100                                      DIScope S, DILocation OrigLoc) {
1101   Value *Elts[] = {
1102     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1103     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1104     S,
1105     OrigLoc,
1106   };
1107   return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1108 }
1109
1110 /// CreateLocation - Creates a debug info location.
1111 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1112                                      DIScope S, MDNode *OrigLoc) {
1113  Value *Elts[] = {
1114     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1115     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1116     S,
1117     OrigLoc
1118   };
1119   return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1120 }
1121
1122 //===----------------------------------------------------------------------===//
1123 // DIFactory: Routines for inserting code into a function
1124 //===----------------------------------------------------------------------===//
1125
1126 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1127 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1128                                       Instruction *InsertBefore) {
1129   assert(Storage && "no storage passed to dbg.declare");
1130   assert(D.Verify() && "empty DIVariable passed to dbg.declare");
1131   if (!DeclareFn)
1132     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1133
1134   Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1135                     D };
1136   return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1137 }
1138
1139 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1140 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1141                                       BasicBlock *InsertAtEnd) {
1142   assert(Storage && "no storage passed to dbg.declare");
1143   assert(D.Verify() && "invalid DIVariable passed to dbg.declare");
1144   if (!DeclareFn)
1145     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1146
1147   Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1148                     D };
1149
1150   // If this block already has a terminator then insert this intrinsic
1151   // before the terminator.
1152   if (TerminatorInst *T = InsertAtEnd->getTerminator()) 
1153     return CallInst::Create(DeclareFn, Args, Args+2, "", T);
1154   else
1155     return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);}
1156
1157 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1158 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1159                                                 DIVariable D,
1160                                                 Instruction *InsertBefore) {
1161   assert(V && "no value passed to dbg.value");
1162   assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1163   if (!ValueFn)
1164     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1165
1166   Value *Args[] = { MDNode::get(V->getContext(), &V, 1),
1167                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1168                     D };
1169   return CallInst::Create(ValueFn, Args, Args+3, "", InsertBefore);
1170 }
1171
1172 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1173 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1174                                                 DIVariable D,
1175                                                 BasicBlock *InsertAtEnd) {
1176   assert(V && "no value passed to dbg.value");
1177   assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1178   if (!ValueFn)
1179     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1180
1181   Value *Args[] = { MDNode::get(V->getContext(), &V, 1), 
1182                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1183                     D };
1184   return CallInst::Create(ValueFn, Args, Args+3, "", InsertAtEnd);
1185 }
1186
1187 //===----------------------------------------------------------------------===//
1188 // DebugInfoFinder implementations.
1189 //===----------------------------------------------------------------------===//
1190
1191 /// processModule - Process entire module and collect debug info.
1192 void DebugInfoFinder::processModule(Module &M) {
1193   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1194     for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1195       for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1196            ++BI) {
1197         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1198           processDeclare(DDI);
1199         
1200         DebugLoc Loc = BI->getDebugLoc();
1201         if (Loc.isUnknown())
1202           continue;
1203         
1204         LLVMContext &Ctx = BI->getContext();
1205         DIDescriptor Scope(Loc.getScope(Ctx));
1206         
1207         if (Scope.isCompileUnit())
1208           addCompileUnit(DICompileUnit(Scope));
1209         else if (Scope.isSubprogram())
1210           processSubprogram(DISubprogram(Scope));
1211         else if (Scope.isLexicalBlock())
1212           processLexicalBlock(DILexicalBlock(Scope));
1213         
1214         if (MDNode *IA = Loc.getInlinedAt(Ctx))
1215           processLocation(DILocation(IA));
1216       }
1217
1218   NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
1219   if (!NMD)
1220     return;
1221
1222   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1223     DIGlobalVariable DIG(cast<MDNode>(NMD->getOperand(i)));
1224     if (addGlobalVariable(DIG)) {
1225       addCompileUnit(DIG.getCompileUnit());
1226       processType(DIG.getType());
1227     }
1228   }
1229 }
1230
1231 /// processLocation - Process DILocation.
1232 void DebugInfoFinder::processLocation(DILocation Loc) {
1233   if (!Loc.Verify()) return;
1234   DIDescriptor S(Loc.getScope());
1235   if (S.isCompileUnit())
1236     addCompileUnit(DICompileUnit(S));
1237   else if (S.isSubprogram())
1238     processSubprogram(DISubprogram(S));
1239   else if (S.isLexicalBlock())
1240     processLexicalBlock(DILexicalBlock(S));
1241   processLocation(Loc.getOrigLocation());
1242 }
1243
1244 /// processType - Process DIType.
1245 void DebugInfoFinder::processType(DIType DT) {
1246   if (!addType(DT))
1247     return;
1248
1249   addCompileUnit(DT.getCompileUnit());
1250   if (DT.isCompositeType()) {
1251     DICompositeType DCT(DT);
1252     processType(DCT.getTypeDerivedFrom());
1253     DIArray DA = DCT.getTypeArray();
1254     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1255       DIDescriptor D = DA.getElement(i);
1256       if (D.isType())
1257         processType(DIType(D));
1258       else if (D.isSubprogram())
1259         processSubprogram(DISubprogram(D));
1260     }
1261   } else if (DT.isDerivedType()) {
1262     DIDerivedType DDT(DT);
1263     processType(DDT.getTypeDerivedFrom());
1264   }
1265 }
1266
1267 /// processLexicalBlock
1268 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1269   DIScope Context = LB.getContext();
1270   if (Context.isLexicalBlock())
1271     return processLexicalBlock(DILexicalBlock(Context));
1272   else
1273     return processSubprogram(DISubprogram(Context));
1274 }
1275
1276 /// processSubprogram - Process DISubprogram.
1277 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1278   if (!addSubprogram(SP))
1279     return;
1280   addCompileUnit(SP.getCompileUnit());
1281   processType(SP.getType());
1282 }
1283
1284 /// processDeclare - Process DbgDeclareInst.
1285 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1286   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1287   if (!N) return;
1288
1289   DIDescriptor DV(N);
1290   if (!DV.isVariable())
1291     return;
1292
1293   if (!NodesSeen.insert(DV))
1294     return;
1295
1296   addCompileUnit(DIVariable(N).getCompileUnit());
1297   processType(DIVariable(N).getType());
1298 }
1299
1300 /// addType - Add type into Tys.
1301 bool DebugInfoFinder::addType(DIType DT) {
1302   if (!DT.isValid())
1303     return false;
1304
1305   if (!NodesSeen.insert(DT))
1306     return false;
1307
1308   TYs.push_back(DT);
1309   return true;
1310 }
1311
1312 /// addCompileUnit - Add compile unit into CUs.
1313 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1314   if (!CU.Verify())
1315     return false;
1316
1317   if (!NodesSeen.insert(CU))
1318     return false;
1319
1320   CUs.push_back(CU);
1321   return true;
1322 }
1323
1324 /// addGlobalVariable - Add global variable into GVs.
1325 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1326   if (!DIDescriptor(DIG).isGlobalVariable())
1327     return false;
1328
1329   if (!NodesSeen.insert(DIG))
1330     return false;
1331
1332   GVs.push_back(DIG);
1333   return true;
1334 }
1335
1336 // addSubprogram - Add subprgoram into SPs.
1337 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1338   if (!DIDescriptor(SP).isSubprogram())
1339     return false;
1340
1341   if (!NodesSeen.insert(SP))
1342     return false;
1343
1344   SPs.push_back(SP);
1345   return true;
1346 }
1347
1348 /// Find the debug info descriptor corresponding to this global variable.
1349 static Value *findDbgGlobalDeclare(GlobalVariable *V) {
1350   const Module *M = V->getParent();
1351   NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1352   if (!NMD)
1353     return 0;
1354
1355   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1356     DIDescriptor DIG(cast_or_null<MDNode>(NMD->getOperand(i)));
1357     if (!DIG.isGlobalVariable())
1358       continue;
1359     if (DIGlobalVariable(DIG).getGlobal() == V)
1360       return DIG;
1361   }
1362   return 0;
1363 }
1364
1365 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1366 /// It looks through pointer casts too.
1367 static const DbgDeclareInst *findDbgDeclare(const Value *V) {
1368   V = V->stripPointerCasts();
1369   
1370   if (!isa<Instruction>(V) && !isa<Argument>(V))
1371     return 0;
1372     
1373   const Function *F = NULL;
1374   if (const Instruction *I = dyn_cast<Instruction>(V))
1375     F = I->getParent()->getParent();
1376   else if (const Argument *A = dyn_cast<Argument>(V))
1377     F = A->getParent();
1378   
1379   for (Function::const_iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
1380     for (BasicBlock::const_iterator BI = (*FI).begin(), BE = (*FI).end();
1381          BI != BE; ++BI)
1382       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1383         if (DDI->getAddress() == V)
1384           return DDI;
1385
1386   return 0;
1387 }
1388
1389 bool llvm::getLocationInfo(const Value *V, std::string &DisplayName,
1390                            std::string &Type, unsigned &LineNo,
1391                            std::string &File, std::string &Dir) {
1392   DICompileUnit Unit;
1393   DIType TypeD;
1394
1395   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1396     Value *DIGV = findDbgGlobalDeclare(GV);
1397     if (!DIGV) return false;
1398     DIGlobalVariable Var(cast<MDNode>(DIGV));
1399
1400     StringRef D = Var.getDisplayName();
1401     if (!D.empty())
1402       DisplayName = D;
1403     LineNo = Var.getLineNumber();
1404     Unit = Var.getCompileUnit();
1405     TypeD = Var.getType();
1406   } else {
1407     const DbgDeclareInst *DDI = findDbgDeclare(V);
1408     if (!DDI) return false;
1409     DIVariable Var(cast<MDNode>(DDI->getVariable()));
1410
1411     StringRef D = Var.getName();
1412     if (!D.empty())
1413       DisplayName = D;
1414     LineNo = Var.getLineNumber();
1415     Unit = Var.getCompileUnit();
1416     TypeD = Var.getType();
1417   }
1418
1419   StringRef T = TypeD.getName();
1420   if (!T.empty())
1421     Type = T;
1422   StringRef F = Unit.getFilename();
1423   if (!F.empty())
1424     File = F;
1425   StringRef D = Unit.getDirectory();
1426   if (!D.empty())
1427     Dir = D;
1428   return true;
1429 }
1430
1431 /// getDISubprogram - Find subprogram that is enclosing this scope.
1432 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
1433   DIDescriptor D(Scope);
1434   if (D.isSubprogram())
1435     return DISubprogram(Scope);
1436   
1437   if (D.isLexicalBlock())
1438     return getDISubprogram(DILexicalBlock(Scope).getContext());
1439   
1440   return DISubprogram();
1441 }
1442
1443 /// getDICompositeType - Find underlying composite type.
1444 DICompositeType llvm::getDICompositeType(DIType T) {
1445   if (T.isCompositeType())
1446     return DICompositeType(T);
1447   
1448   if (T.isDerivedType())
1449     return getDICompositeType(DIDerivedType(T).getTypeDerivedFrom());
1450   
1451   return DICompositeType();
1452 }