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