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