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