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