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