Verify variable directly.
[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 /// getOriginalTypeSize - If this type is derived from a base type then
354 /// return base type size.
355 uint64_t DIDerivedType::getOriginalTypeSize() const {
356   unsigned Tag = getTag();
357   if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef ||
358       Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
359       Tag == dwarf::DW_TAG_restrict_type) {
360     DIType BaseType = getTypeDerivedFrom();
361     // If this type is not derived from any type then take conservative 
362     // approach.
363     if (!BaseType.isValid())
364       return getSizeInBits();
365     if (BaseType.isDerivedType())
366       return DIDerivedType(BaseType).getOriginalTypeSize();
367     else
368       return BaseType.getSizeInBits();
369   }
370     
371   return getSizeInBits();
372 }
373
374 /// isInlinedFnArgument - Return trule if this variable provides debugging
375 /// information for an inlined function arguments.
376 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
377   assert(CurFn && "Invalid function");
378   if (!getContext().isSubprogram())
379     return false;
380   // This variable is not inlined function argument if its scope 
381   // does not describe current function.
382   return !(DISubprogram(getContext()).describes(CurFn));
383 }
384
385 /// describes - Return true if this subprogram provides debugging
386 /// information for the function F.
387 bool DISubprogram::describes(const Function *F) {
388   assert(F && "Invalid function");
389   StringRef Name = getLinkageName();
390   if (Name.empty())
391     Name = getName();
392   if (F->getName() == Name)
393     return true;
394   return false;
395 }
396
397 unsigned DISubprogram::isOptimized() const     {
398   assert (DbgNode && "Invalid subprogram descriptor!");
399   if (DbgNode->getNumOperands() == 16)
400     return getUnsignedField(15);
401   return 0;
402 }
403
404 StringRef DIScope::getFilename() const {
405   if (!DbgNode)
406     return StringRef();
407   if (isLexicalBlock()) 
408     return DILexicalBlock(DbgNode).getFilename();
409   if (isSubprogram())
410     return DISubprogram(DbgNode).getFilename();
411   if (isCompileUnit())
412     return DICompileUnit(DbgNode).getFilename();
413   if (isNameSpace())
414     return DINameSpace(DbgNode).getFilename();
415   if (isType())
416     return DIType(DbgNode).getFilename();
417   if (isFile())
418     return DIFile(DbgNode).getFilename();
419   assert(0 && "Invalid DIScope!");
420   return StringRef();
421 }
422
423 StringRef DIScope::getDirectory() const {
424   if (!DbgNode)
425     return StringRef();
426   if (isLexicalBlock()) 
427     return DILexicalBlock(DbgNode).getDirectory();
428   if (isSubprogram())
429     return DISubprogram(DbgNode).getDirectory();
430   if (isCompileUnit())
431     return DICompileUnit(DbgNode).getDirectory();
432   if (isNameSpace())
433     return DINameSpace(DbgNode).getDirectory();
434   if (isType())
435     return DIType(DbgNode).getDirectory();
436   if (isFile())
437     return DIFile(DbgNode).getDirectory();
438   assert(0 && "Invalid DIScope!");
439   return StringRef();
440 }
441
442 //===----------------------------------------------------------------------===//
443 // DIDescriptor: dump routines for all descriptors.
444 //===----------------------------------------------------------------------===//
445
446
447 /// print - Print descriptor.
448 void DIDescriptor::print(raw_ostream &OS) const {
449   OS << "[" << dwarf::TagString(getTag()) << "] ";
450   OS.write_hex((intptr_t) &*DbgNode) << ']';
451 }
452
453 /// print - Print compile unit.
454 void DICompileUnit::print(raw_ostream &OS) const {
455   if (getLanguage())
456     OS << " [" << dwarf::LanguageString(getLanguage()) << "] ";
457
458   OS << " [" << getDirectory() << "/" << getFilename() << " ]";
459 }
460
461 /// print - Print type.
462 void DIType::print(raw_ostream &OS) const {
463   if (!DbgNode) return;
464
465   StringRef Res = getName();
466   if (!Res.empty())
467     OS << " [" << Res << "] ";
468
469   unsigned Tag = getTag();
470   OS << " [" << dwarf::TagString(Tag) << "] ";
471
472   // TODO : Print context
473   getCompileUnit().print(OS);
474   OS << " ["
475          << "line " << getLineNumber() << ", "
476          << getSizeInBits() << " bits, "
477          << getAlignInBits() << " bit alignment, "
478          << getOffsetInBits() << " bit offset"
479          << "] ";
480
481   if (isPrivate())
482     OS << " [private] ";
483   else if (isProtected())
484     OS << " [protected] ";
485
486   if (isForwardDecl())
487     OS << " [fwd] ";
488
489   if (isBasicType())
490     DIBasicType(DbgNode).print(OS);
491   else if (isDerivedType())
492     DIDerivedType(DbgNode).print(OS);
493   else if (isCompositeType())
494     DICompositeType(DbgNode).print(OS);
495   else {
496     OS << "Invalid DIType\n";
497     return;
498   }
499
500   OS << "\n";
501 }
502
503 /// print - Print basic type.
504 void DIBasicType::print(raw_ostream &OS) const {
505   OS << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
506 }
507
508 /// print - Print derived type.
509 void DIDerivedType::print(raw_ostream &OS) const {
510   OS << "\n\t Derived From: "; getTypeDerivedFrom().print(OS);
511 }
512
513 /// print - Print composite type.
514 void DICompositeType::print(raw_ostream &OS) const {
515   DIArray A = getTypeArray();
516   OS << " [" << A.getNumElements() << " elements]";
517 }
518
519 /// print - Print global.
520 void DIGlobal::print(raw_ostream &OS) const {
521   StringRef Res = getName();
522   if (!Res.empty())
523     OS << " [" << Res << "] ";
524
525   unsigned Tag = getTag();
526   OS << " [" << dwarf::TagString(Tag) << "] ";
527
528   // TODO : Print context
529   getCompileUnit().print(OS);
530   OS << " [" << getLineNumber() << "] ";
531
532   if (isLocalToUnit())
533     OS << " [local] ";
534
535   if (isDefinition())
536     OS << " [def] ";
537
538   if (isGlobalVariable())
539     DIGlobalVariable(DbgNode).print(OS);
540
541   OS << "\n";
542 }
543
544 /// print - Print subprogram.
545 void DISubprogram::print(raw_ostream &OS) const {
546   StringRef Res = getName();
547   if (!Res.empty())
548     OS << " [" << Res << "] ";
549
550   unsigned Tag = getTag();
551   OS << " [" << dwarf::TagString(Tag) << "] ";
552
553   // TODO : Print context
554   getCompileUnit().print(OS);
555   OS << " [" << getLineNumber() << "] ";
556
557   if (isLocalToUnit())
558     OS << " [local] ";
559
560   if (isDefinition())
561     OS << " [def] ";
562
563   OS << "\n";
564 }
565
566 /// print - Print global variable.
567 void DIGlobalVariable::print(raw_ostream &OS) const {
568   OS << " [";
569   getGlobal()->print(OS);
570   OS << "] ";
571 }
572
573 /// print - Print variable.
574 void DIVariable::print(raw_ostream &OS) const {
575   StringRef Res = getName();
576   if (!Res.empty())
577     OS << " [" << Res << "] ";
578
579   getCompileUnit().print(OS);
580   OS << " [" << getLineNumber() << "] ";
581   getType().print(OS);
582   OS << "\n";
583
584   // FIXME: Dump complex addresses
585 }
586
587 /// dump - Print descriptor to dbgs() with a newline.
588 void DIDescriptor::dump() const {
589   print(dbgs()); dbgs() << '\n';
590 }
591
592 /// dump - Print compile unit to dbgs() with a newline.
593 void DICompileUnit::dump() const {
594   print(dbgs()); dbgs() << '\n';
595 }
596
597 /// dump - Print type to dbgs() with a newline.
598 void DIType::dump() const {
599   print(dbgs()); dbgs() << '\n';
600 }
601
602 /// dump - Print basic type to dbgs() with a newline.
603 void DIBasicType::dump() const {
604   print(dbgs()); dbgs() << '\n';
605 }
606
607 /// dump - Print derived type to dbgs() with a newline.
608 void DIDerivedType::dump() const {
609   print(dbgs()); dbgs() << '\n';
610 }
611
612 /// dump - Print composite type to dbgs() with a newline.
613 void DICompositeType::dump() const {
614   print(dbgs()); dbgs() << '\n';
615 }
616
617 /// dump - Print global to dbgs() with a newline.
618 void DIGlobal::dump() const {
619   print(dbgs()); dbgs() << '\n';
620 }
621
622 /// dump - Print subprogram to dbgs() with a newline.
623 void DISubprogram::dump() const {
624   print(dbgs()); dbgs() << '\n';
625 }
626
627 /// dump - Print global variable.
628 void DIGlobalVariable::dump() const {
629   print(dbgs()); dbgs() << '\n';
630 }
631
632 /// dump - Print variable.
633 void DIVariable::dump() const {
634   print(dbgs()); dbgs() << '\n';
635 }
636
637 //===----------------------------------------------------------------------===//
638 // DIFactory: Basic Helpers
639 //===----------------------------------------------------------------------===//
640
641 DIFactory::DIFactory(Module &m)
642   : M(m), VMContext(M.getContext()), DeclareFn(0), ValueFn(0) {}
643
644 Constant *DIFactory::GetTagConstant(unsigned TAG) {
645   assert((TAG & LLVMDebugVersionMask) == 0 &&
646          "Tag too large for debug encoding!");
647   return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
648 }
649
650 //===----------------------------------------------------------------------===//
651 // DIFactory: Primary Constructors
652 //===----------------------------------------------------------------------===//
653
654 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
655 /// This implicitly uniques the arrays created.
656 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
657   SmallVector<Value*, 16> Elts;
658
659   if (NumTys == 0)
660     Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
661   else
662     for (unsigned i = 0; i != NumTys; ++i)
663       Elts.push_back(Tys[i]);
664
665   return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
666 }
667
668 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
669 /// implicitly uniques the values returned.
670 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
671   Value *Elts[] = {
672     GetTagConstant(dwarf::DW_TAG_subrange_type),
673     ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
674     ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
675   };
676
677   return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
678 }
679
680
681
682 /// CreateCompileUnit - Create a new descriptor for the specified compile
683 /// unit.  Note that this does not unique compile units within the module.
684 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
685                                            StringRef Filename,
686                                            StringRef Directory,
687                                            StringRef Producer,
688                                            bool isMain,
689                                            bool isOptimized,
690                                            StringRef Flags,
691                                            unsigned RunTimeVer) {
692   Value *Elts[] = {
693     GetTagConstant(dwarf::DW_TAG_compile_unit),
694     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
695     ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
696     MDString::get(VMContext, Filename),
697     MDString::get(VMContext, Directory),
698     MDString::get(VMContext, Producer),
699     ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
700     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
701     MDString::get(VMContext, Flags),
702     ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
703   };
704
705   return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
706 }
707
708 /// CreateFile -  Create a new descriptor for the specified file.
709 DIFile DIFactory::CreateFile(StringRef Filename,
710                              StringRef Directory,
711                              DICompileUnit CU) {
712   Value *Elts[] = {
713     GetTagConstant(dwarf::DW_TAG_file_type),
714     MDString::get(VMContext, Filename),
715     MDString::get(VMContext, Directory),
716     CU
717   };
718
719   return DIFile(MDNode::get(VMContext, &Elts[0], 4));
720 }
721
722 /// CreateEnumerator - Create a single enumerator value.
723 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
724   Value *Elts[] = {
725     GetTagConstant(dwarf::DW_TAG_enumerator),
726     MDString::get(VMContext, Name),
727     ConstantInt::get(Type::getInt64Ty(VMContext), Val)
728   };
729   return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
730 }
731
732
733 /// CreateBasicType - Create a basic type like int, float, etc.
734 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
735                                        StringRef Name,
736                                        DIFile F,
737                                        unsigned LineNumber,
738                                        uint64_t SizeInBits,
739                                        uint64_t AlignInBits,
740                                        uint64_t OffsetInBits, unsigned Flags,
741                                        unsigned Encoding) {
742   Value *Elts[] = {
743     GetTagConstant(dwarf::DW_TAG_base_type),
744     Context,
745     MDString::get(VMContext, Name),
746     F,
747     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
748     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
749     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
750     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
751     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
752     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
753   };
754   return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
755 }
756
757
758 /// CreateBasicType - Create a basic type like int, float, etc.
759 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
760                                          StringRef Name,
761                                          DIFile F,
762                                          unsigned LineNumber,
763                                          Constant *SizeInBits,
764                                          Constant *AlignInBits,
765                                          Constant *OffsetInBits, unsigned Flags,
766                                          unsigned Encoding) {
767   Value *Elts[] = {
768     GetTagConstant(dwarf::DW_TAG_base_type),
769     Context,
770     MDString::get(VMContext, Name),
771     F,
772     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
773     SizeInBits,
774     AlignInBits,
775     OffsetInBits,
776     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
777     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
778   };
779   return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
780 }
781
782 /// CreateArtificialType - Create a new DIType with "artificial" flag set.
783 DIType DIFactory::CreateArtificialType(DIType Ty) {
784   if (Ty.isArtificial())
785     return Ty;
786
787   SmallVector<Value *, 9> Elts;
788   MDNode *N = Ty;
789   assert (N && "Unexpected input DIType!");
790   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
791     if (Value *V = N->getOperand(i))
792       Elts.push_back(V);
793     else
794       Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext)));
795   }
796
797   unsigned CurFlags = Ty.getFlags();
798   CurFlags = CurFlags | DIType::FlagArtificial;
799
800   // Flags are stored at this slot.
801   Elts[8] =  ConstantInt::get(Type::getInt32Ty(VMContext), CurFlags);
802
803   return DIType(MDNode::get(VMContext, Elts.data(), Elts.size()));
804 }
805
806 /// CreateDerivedType - Create a derived type like const qualified type,
807 /// pointer, typedef, etc.
808 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
809                                            DIDescriptor Context,
810                                            StringRef Name,
811                                            DIFile F,
812                                            unsigned LineNumber,
813                                            uint64_t SizeInBits,
814                                            uint64_t AlignInBits,
815                                            uint64_t OffsetInBits,
816                                            unsigned Flags,
817                                            DIType DerivedFrom) {
818   Value *Elts[] = {
819     GetTagConstant(Tag),
820     Context,
821     MDString::get(VMContext, Name),
822     F,
823     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
824     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
825     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
826     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
827     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
828     DerivedFrom,
829   };
830   return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
831 }
832
833
834 /// CreateDerivedType - Create a derived type like const qualified type,
835 /// pointer, typedef, etc.
836 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
837                                              DIDescriptor Context,
838                                              StringRef Name,
839                                              DIFile F,
840                                              unsigned LineNumber,
841                                              Constant *SizeInBits,
842                                              Constant *AlignInBits,
843                                              Constant *OffsetInBits,
844                                              unsigned Flags,
845                                              DIType DerivedFrom) {
846   Value *Elts[] = {
847     GetTagConstant(Tag),
848     Context,
849     MDString::get(VMContext, Name),
850     F,
851     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
852     SizeInBits,
853     AlignInBits,
854     OffsetInBits,
855     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
856     DerivedFrom,
857   };
858   return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
859 }
860
861
862 /// CreateCompositeType - Create a composite type like array, struct, etc.
863 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
864                                                DIDescriptor Context,
865                                                StringRef Name,
866                                                DIFile F,
867                                                unsigned LineNumber,
868                                                uint64_t SizeInBits,
869                                                uint64_t AlignInBits,
870                                                uint64_t OffsetInBits,
871                                                unsigned Flags,
872                                                DIType DerivedFrom,
873                                                DIArray Elements,
874                                                unsigned RuntimeLang,
875                                                MDNode *ContainingType) {
876
877   Value *Elts[] = {
878     GetTagConstant(Tag),
879     Context,
880     MDString::get(VMContext, Name),
881     F,
882     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
883     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
884     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
885     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
886     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
887     DerivedFrom,
888     Elements,
889     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang),
890     ContainingType
891   };
892   return DICompositeType(MDNode::get(VMContext, &Elts[0], 13));
893 }
894
895
896 /// CreateCompositeType - Create a composite type like array, struct, etc.
897 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
898                                                  DIDescriptor Context,
899                                                  StringRef Name,
900                                                  DIFile F,
901                                                  unsigned LineNumber,
902                                                  Constant *SizeInBits,
903                                                  Constant *AlignInBits,
904                                                  Constant *OffsetInBits,
905                                                  unsigned Flags,
906                                                  DIType DerivedFrom,
907                                                  DIArray Elements,
908                                                  unsigned RuntimeLang) {
909
910   Value *Elts[] = {
911     GetTagConstant(Tag),
912     Context,
913     MDString::get(VMContext, Name),
914     F,
915     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
916     SizeInBits,
917     AlignInBits,
918     OffsetInBits,
919     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
920     DerivedFrom,
921     Elements,
922     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
923   };
924   return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
925 }
926
927
928 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
929 /// See comments in DISubprogram for descriptions of these fields.  This
930 /// method does not unique the generated descriptors.
931 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
932                                          StringRef Name,
933                                          StringRef DisplayName,
934                                          StringRef LinkageName,
935                                          DIFile F,
936                                          unsigned LineNo, DIType Ty,
937                                          bool isLocalToUnit,
938                                          bool isDefinition,
939                                          unsigned VK, unsigned VIndex,
940                                          DIType ContainingType,
941                                          bool isArtificial,
942                                          bool isOptimized) {
943
944   Value *Elts[] = {
945     GetTagConstant(dwarf::DW_TAG_subprogram),
946     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
947     Context,
948     MDString::get(VMContext, Name),
949     MDString::get(VMContext, DisplayName),
950     MDString::get(VMContext, LinkageName),
951     F,
952     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
953     Ty,
954     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
955     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
956     ConstantInt::get(Type::getInt32Ty(VMContext), (unsigned)VK),
957     ConstantInt::get(Type::getInt32Ty(VMContext), VIndex),
958     ContainingType,
959     ConstantInt::get(Type::getInt1Ty(VMContext), isArtificial),
960     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized)
961   };
962   return DISubprogram(MDNode::get(VMContext, &Elts[0], 16));
963 }
964
965 /// CreateSubprogramDefinition - Create new subprogram descriptor for the
966 /// given declaration. 
967 DISubprogram DIFactory::CreateSubprogramDefinition(DISubprogram &SPDeclaration) {
968   if (SPDeclaration.isDefinition())
969     return DISubprogram(SPDeclaration);
970
971   MDNode *DeclNode = SPDeclaration;
972   Value *Elts[] = {
973     GetTagConstant(dwarf::DW_TAG_subprogram),
974     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
975     DeclNode->getOperand(2), // Context
976     DeclNode->getOperand(3), // Name
977     DeclNode->getOperand(4), // DisplayName
978     DeclNode->getOperand(5), // LinkageName
979     DeclNode->getOperand(6), // CompileUnit
980     DeclNode->getOperand(7), // LineNo
981     DeclNode->getOperand(8), // Type
982     DeclNode->getOperand(9), // isLocalToUnit
983     ConstantInt::get(Type::getInt1Ty(VMContext), true),
984     DeclNode->getOperand(11), // Virtuality
985     DeclNode->getOperand(12), // VIndex
986     DeclNode->getOperand(13), // Containting Type
987     DeclNode->getOperand(14), // isArtificial
988     DeclNode->getOperand(15)  // isOptimized
989   };
990   return DISubprogram(MDNode::get(VMContext, &Elts[0], 16));
991 }
992
993 /// CreateGlobalVariable - Create a new descriptor for the specified global.
994 DIGlobalVariable
995 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
996                                 StringRef DisplayName,
997                                 StringRef LinkageName,
998                                 DIFile F,
999                                 unsigned LineNo, DIType Ty,bool isLocalToUnit,
1000                                 bool isDefinition, llvm::GlobalVariable *Val) {
1001   Value *Elts[] = {
1002     GetTagConstant(dwarf::DW_TAG_variable),
1003     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
1004     Context,
1005     MDString::get(VMContext, Name),
1006     MDString::get(VMContext, DisplayName),
1007     MDString::get(VMContext, LinkageName),
1008     F,
1009     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1010     Ty,
1011     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
1012     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
1013     Val
1014   };
1015
1016   Value *const *Vs = &Elts[0];
1017   MDNode *Node = MDNode::get(VMContext,Vs, 12);
1018
1019   // Create a named metadata so that we do not lose this mdnode.
1020   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
1021   NMD->addOperand(Node);
1022
1023   return DIGlobalVariable(Node);
1024 }
1025
1026
1027 /// CreateVariable - Create a new descriptor for the specified variable.
1028 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
1029                                      StringRef Name,
1030                                      DIFile F,
1031                                      unsigned LineNo,
1032                                      DIType Ty) {
1033   Value *Elts[] = {
1034     GetTagConstant(Tag),
1035     Context,
1036     MDString::get(VMContext, Name),
1037     F,
1038     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1039     Ty,
1040   };
1041   return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
1042 }
1043
1044
1045 /// CreateComplexVariable - Create a new descriptor for the specified variable
1046 /// which has a complex address expression for its address.
1047 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
1048                                             const std::string &Name,
1049                                             DIFile F,
1050                                             unsigned LineNo,
1051                                             DIType Ty, 
1052                                             SmallVector<Value *, 9> &addr) {
1053   SmallVector<Value *, 9> Elts;
1054   Elts.push_back(GetTagConstant(Tag));
1055   Elts.push_back(Context);
1056   Elts.push_back(MDString::get(VMContext, Name));
1057   Elts.push_back(F);
1058   Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
1059   Elts.push_back(Ty);
1060   Elts.insert(Elts.end(), addr.begin(), addr.end());
1061
1062   return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
1063 }
1064
1065
1066 /// CreateBlock - This creates a descriptor for a lexical block with the
1067 /// specified parent VMContext.
1068 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context,
1069                                              unsigned LineNo, unsigned Col) {
1070   Value *Elts[] = {
1071     GetTagConstant(dwarf::DW_TAG_lexical_block),
1072     Context,
1073     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1074     ConstantInt::get(Type::getInt32Ty(VMContext), Col)
1075   };
1076   return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 4));
1077 }
1078
1079 /// CreateNameSpace - This creates new descriptor for a namespace
1080 /// with the specified parent context.
1081 DINameSpace DIFactory::CreateNameSpace(DIDescriptor Context, StringRef Name,
1082                                        DIFile F,
1083                                        unsigned LineNo) {
1084   Value *Elts[] = {
1085     GetTagConstant(dwarf::DW_TAG_namespace),
1086     Context,
1087     MDString::get(VMContext, Name),
1088     F,
1089     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
1090   };
1091   return DINameSpace(MDNode::get(VMContext, &Elts[0], 5));
1092 }
1093
1094 /// CreateLocation - Creates a debug info location.
1095 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1096                                      DIScope S, DILocation OrigLoc) {
1097   Value *Elts[] = {
1098     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1099     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1100     S,
1101     OrigLoc,
1102   };
1103   return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1104 }
1105
1106 /// CreateLocation - Creates a debug info location.
1107 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1108                                      DIScope S, MDNode *OrigLoc) {
1109  Value *Elts[] = {
1110     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1111     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1112     S,
1113     OrigLoc
1114   };
1115   return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1116 }
1117
1118 //===----------------------------------------------------------------------===//
1119 // DIFactory: Routines for inserting code into a function
1120 //===----------------------------------------------------------------------===//
1121
1122 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1123 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1124                                       Instruction *InsertBefore) {
1125   assert(Storage && "no storage passed to dbg.declare");
1126   assert(D.Verify() && "empty DIVariable passed to dbg.declare");
1127   if (!DeclareFn)
1128     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1129
1130   Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1131                     D };
1132   return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1133 }
1134
1135 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1136 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1137                                       BasicBlock *InsertAtEnd) {
1138   assert(Storage && "no storage passed to dbg.declare");
1139   assert(D.Verify() && "invalid DIVariable passed to dbg.declare");
1140   if (!DeclareFn)
1141     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1142
1143   Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1144                     D };
1145
1146   // If this block already has a terminator then insert this intrinsic
1147   // before the terminator.
1148   if (TerminatorInst *T = InsertAtEnd->getTerminator()) 
1149     return CallInst::Create(DeclareFn, Args, Args+2, "", T);
1150   else
1151     return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);}
1152
1153 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1154 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1155                                                 DIVariable D,
1156                                                 Instruction *InsertBefore) {
1157   assert(V && "no value passed to dbg.value");
1158   assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1159   if (!ValueFn)
1160     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1161
1162   Value *Args[] = { MDNode::get(V->getContext(), &V, 1),
1163                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1164                     D };
1165   return CallInst::Create(ValueFn, Args, Args+3, "", InsertBefore);
1166 }
1167
1168 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1169 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1170                                                 DIVariable D,
1171                                                 BasicBlock *InsertAtEnd) {
1172   assert(V && "no value passed to dbg.value");
1173   assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1174   if (!ValueFn)
1175     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1176
1177   Value *Args[] = { MDNode::get(V->getContext(), &V, 1), 
1178                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1179                     D };
1180   return CallInst::Create(ValueFn, Args, Args+3, "", InsertAtEnd);
1181 }
1182
1183 //===----------------------------------------------------------------------===//
1184 // DebugInfoFinder implementations.
1185 //===----------------------------------------------------------------------===//
1186
1187 /// processModule - Process entire module and collect debug info.
1188 void DebugInfoFinder::processModule(Module &M) {
1189   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1190     for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1191       for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1192            ++BI) {
1193         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1194           processDeclare(DDI);
1195         
1196         DebugLoc Loc = BI->getDebugLoc();
1197         if (Loc.isUnknown())
1198           continue;
1199         
1200         LLVMContext &Ctx = BI->getContext();
1201         DIDescriptor Scope(Loc.getScope(Ctx));
1202         
1203         if (Scope.isCompileUnit())
1204           addCompileUnit(DICompileUnit(Scope));
1205         else if (Scope.isSubprogram())
1206           processSubprogram(DISubprogram(Scope));
1207         else if (Scope.isLexicalBlock())
1208           processLexicalBlock(DILexicalBlock(Scope));
1209         
1210         if (MDNode *IA = Loc.getInlinedAt(Ctx))
1211           processLocation(DILocation(IA));
1212       }
1213
1214   NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
1215   if (!NMD)
1216     return;
1217
1218   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1219     DIGlobalVariable DIG(cast<MDNode>(NMD->getOperand(i)));
1220     if (addGlobalVariable(DIG)) {
1221       addCompileUnit(DIG.getCompileUnit());
1222       processType(DIG.getType());
1223     }
1224   }
1225 }
1226
1227 /// processLocation - Process DILocation.
1228 void DebugInfoFinder::processLocation(DILocation Loc) {
1229   if (!Loc.Verify()) return;
1230   DIDescriptor S(Loc.getScope());
1231   if (S.isCompileUnit())
1232     addCompileUnit(DICompileUnit(S));
1233   else if (S.isSubprogram())
1234     processSubprogram(DISubprogram(S));
1235   else if (S.isLexicalBlock())
1236     processLexicalBlock(DILexicalBlock(S));
1237   processLocation(Loc.getOrigLocation());
1238 }
1239
1240 /// processType - Process DIType.
1241 void DebugInfoFinder::processType(DIType DT) {
1242   if (!addType(DT))
1243     return;
1244
1245   addCompileUnit(DT.getCompileUnit());
1246   if (DT.isCompositeType()) {
1247     DICompositeType DCT(DT);
1248     processType(DCT.getTypeDerivedFrom());
1249     DIArray DA = DCT.getTypeArray();
1250     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1251       DIDescriptor D = DA.getElement(i);
1252       if (D.isType())
1253         processType(DIType(D));
1254       else if (D.isSubprogram())
1255         processSubprogram(DISubprogram(D));
1256     }
1257   } else if (DT.isDerivedType()) {
1258     DIDerivedType DDT(DT);
1259     processType(DDT.getTypeDerivedFrom());
1260   }
1261 }
1262
1263 /// processLexicalBlock
1264 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1265   DIScope Context = LB.getContext();
1266   if (Context.isLexicalBlock())
1267     return processLexicalBlock(DILexicalBlock(Context));
1268   else
1269     return processSubprogram(DISubprogram(Context));
1270 }
1271
1272 /// processSubprogram - Process DISubprogram.
1273 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1274   if (!addSubprogram(SP))
1275     return;
1276   addCompileUnit(SP.getCompileUnit());
1277   processType(SP.getType());
1278 }
1279
1280 /// processDeclare - Process DbgDeclareInst.
1281 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1282   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1283   if (!N) return;
1284
1285   DIDescriptor DV(N);
1286   if (!DV.isVariable())
1287     return;
1288
1289   if (!NodesSeen.insert(DV))
1290     return;
1291
1292   addCompileUnit(DIVariable(N).getCompileUnit());
1293   processType(DIVariable(N).getType());
1294 }
1295
1296 /// addType - Add type into Tys.
1297 bool DebugInfoFinder::addType(DIType DT) {
1298   if (!DT.isValid())
1299     return false;
1300
1301   if (!NodesSeen.insert(DT))
1302     return false;
1303
1304   TYs.push_back(DT);
1305   return true;
1306 }
1307
1308 /// addCompileUnit - Add compile unit into CUs.
1309 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1310   if (!CU.Verify())
1311     return false;
1312
1313   if (!NodesSeen.insert(CU))
1314     return false;
1315
1316   CUs.push_back(CU);
1317   return true;
1318 }
1319
1320 /// addGlobalVariable - Add global variable into GVs.
1321 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1322   if (!DIDescriptor(DIG).isGlobalVariable())
1323     return false;
1324
1325   if (!NodesSeen.insert(DIG))
1326     return false;
1327
1328   GVs.push_back(DIG);
1329   return true;
1330 }
1331
1332 // addSubprogram - Add subprgoram into SPs.
1333 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1334   if (!DIDescriptor(SP).isSubprogram())
1335     return false;
1336
1337   if (!NodesSeen.insert(SP))
1338     return false;
1339
1340   SPs.push_back(SP);
1341   return true;
1342 }
1343
1344 /// Find the debug info descriptor corresponding to this global variable.
1345 static Value *findDbgGlobalDeclare(GlobalVariable *V) {
1346   const Module *M = V->getParent();
1347   NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1348   if (!NMD)
1349     return 0;
1350
1351   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1352     DIDescriptor DIG(cast_or_null<MDNode>(NMD->getOperand(i)));
1353     if (!DIG.isGlobalVariable())
1354       continue;
1355     if (DIGlobalVariable(DIG).getGlobal() == V)
1356       return DIG;
1357   }
1358   return 0;
1359 }
1360
1361 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1362 /// It looks through pointer casts too.
1363 static const DbgDeclareInst *findDbgDeclare(const Value *V) {
1364   V = V->stripPointerCasts();
1365   
1366   if (!isa<Instruction>(V) && !isa<Argument>(V))
1367     return 0;
1368     
1369   const Function *F = NULL;
1370   if (const Instruction *I = dyn_cast<Instruction>(V))
1371     F = I->getParent()->getParent();
1372   else if (const Argument *A = dyn_cast<Argument>(V))
1373     F = A->getParent();
1374   
1375   for (Function::const_iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
1376     for (BasicBlock::const_iterator BI = (*FI).begin(), BE = (*FI).end();
1377          BI != BE; ++BI)
1378       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1379         if (DDI->getAddress() == V)
1380           return DDI;
1381
1382   return 0;
1383 }
1384
1385 bool llvm::getLocationInfo(const Value *V, std::string &DisplayName,
1386                            std::string &Type, unsigned &LineNo,
1387                            std::string &File, std::string &Dir) {
1388   DICompileUnit Unit;
1389   DIType TypeD;
1390
1391   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1392     Value *DIGV = findDbgGlobalDeclare(GV);
1393     if (!DIGV) return false;
1394     DIGlobalVariable Var(cast<MDNode>(DIGV));
1395
1396     StringRef D = Var.getDisplayName();
1397     if (!D.empty())
1398       DisplayName = D;
1399     LineNo = Var.getLineNumber();
1400     Unit = Var.getCompileUnit();
1401     TypeD = Var.getType();
1402   } else {
1403     const DbgDeclareInst *DDI = findDbgDeclare(V);
1404     if (!DDI) return false;
1405     DIVariable Var(cast<MDNode>(DDI->getVariable()));
1406
1407     StringRef D = Var.getName();
1408     if (!D.empty())
1409       DisplayName = D;
1410     LineNo = Var.getLineNumber();
1411     Unit = Var.getCompileUnit();
1412     TypeD = Var.getType();
1413   }
1414
1415   StringRef T = TypeD.getName();
1416   if (!T.empty())
1417     Type = T;
1418   StringRef F = Unit.getFilename();
1419   if (!F.empty())
1420     File = F;
1421   StringRef D = Unit.getDirectory();
1422   if (!D.empty())
1423     Dir = D;
1424   return true;
1425 }
1426
1427 /// getDISubprogram - Find subprogram that is enclosing this scope.
1428 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
1429   DIDescriptor D(Scope);
1430   if (D.isSubprogram())
1431     return DISubprogram(Scope);
1432   
1433   if (D.isLexicalBlock())
1434     return getDISubprogram(DILexicalBlock(Scope).getContext());
1435   
1436   return DISubprogram();
1437 }
1438
1439 /// getDICompositeType - Find underlying composite type.
1440 DICompositeType llvm::getDICompositeType(DIType T) {
1441   if (T.isCompositeType())
1442     return DICompositeType(T);
1443   
1444   if (T.isDerivedType())
1445     return getDICompositeType(DIDerivedType(T).getTypeDerivedFrom());
1446   
1447   return DICompositeType();
1448 }