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