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