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