Change dbgs() back to errs() for assert messages as Chris requested.
[oota-llvm.git] / lib / Analysis / DebugInfo.cpp
1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/DebugInfo.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.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, CodeGenOpt::Level 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
1121   MetadataContext &TheMetadata = M.getContext().getMetadata();
1122   unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
1123
1124   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1125     for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1126       for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1127            ++BI) {
1128         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1129           processDeclare(DDI);
1130         else if (MDDbgKind) 
1131           if (MDNode *L = TheMetadata.getMD(MDDbgKind, BI)) 
1132             processLocation(DILocation(L));
1133       }
1134
1135   NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
1136   if (!NMD)
1137     return;
1138
1139   for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1140     DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
1141     if (addGlobalVariable(DIG)) {
1142       addCompileUnit(DIG.getCompileUnit());
1143       processType(DIG.getType());
1144     }
1145   }
1146 }
1147
1148 /// processLocation - Process DILocation.
1149 void DebugInfoFinder::processLocation(DILocation Loc) {
1150   if (Loc.isNull()) return;
1151   DIScope S(Loc.getScope().getNode());
1152   if (S.isNull()) return;
1153   if (S.isCompileUnit())
1154     addCompileUnit(DICompileUnit(S.getNode()));
1155   else if (S.isSubprogram())
1156     processSubprogram(DISubprogram(S.getNode()));
1157   else if (S.isLexicalBlock())
1158     processLexicalBlock(DILexicalBlock(S.getNode()));
1159   processLocation(Loc.getOrigLocation());
1160 }
1161
1162 /// processType - Process DIType.
1163 void DebugInfoFinder::processType(DIType DT) {
1164   if (!addType(DT))
1165     return;
1166
1167   addCompileUnit(DT.getCompileUnit());
1168   if (DT.isCompositeType()) {
1169     DICompositeType DCT(DT.getNode());
1170     processType(DCT.getTypeDerivedFrom());
1171     DIArray DA = DCT.getTypeArray();
1172     if (!DA.isNull())
1173       for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1174         DIDescriptor D = DA.getElement(i);
1175         DIType TypeE = DIType(D.getNode());
1176         if (!TypeE.isNull())
1177           processType(TypeE);
1178         else
1179           processSubprogram(DISubprogram(D.getNode()));
1180       }
1181   } else if (DT.isDerivedType()) {
1182     DIDerivedType DDT(DT.getNode());
1183     if (!DDT.isNull())
1184       processType(DDT.getTypeDerivedFrom());
1185   }
1186 }
1187
1188 /// processLexicalBlock
1189 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1190   if (LB.isNull())
1191     return;
1192   DIScope Context = LB.getContext();
1193   if (Context.isLexicalBlock())
1194     return processLexicalBlock(DILexicalBlock(Context.getNode()));
1195   else
1196     return processSubprogram(DISubprogram(Context.getNode()));
1197 }
1198
1199 /// processSubprogram - Process DISubprogram.
1200 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1201   if (SP.isNull())
1202     return;
1203   if (!addSubprogram(SP))
1204     return;
1205   addCompileUnit(SP.getCompileUnit());
1206   processType(SP.getType());
1207 }
1208
1209 /// processDeclare - Process DbgDeclareInst.
1210 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1211   DIVariable DV(cast<MDNode>(DDI->getVariable()));
1212   if (DV.isNull())
1213     return;
1214
1215   if (!NodesSeen.insert(DV.getNode()))
1216     return;
1217
1218   addCompileUnit(DV.getCompileUnit());
1219   processType(DV.getType());
1220 }
1221
1222 /// addType - Add type into Tys.
1223 bool DebugInfoFinder::addType(DIType DT) {
1224   if (DT.isNull())
1225     return false;
1226
1227   if (!NodesSeen.insert(DT.getNode()))
1228     return false;
1229
1230   TYs.push_back(DT.getNode());
1231   return true;
1232 }
1233
1234 /// addCompileUnit - Add compile unit into CUs.
1235 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1236   if (CU.isNull())
1237     return false;
1238
1239   if (!NodesSeen.insert(CU.getNode()))
1240     return false;
1241
1242   CUs.push_back(CU.getNode());
1243   return true;
1244 }
1245
1246 /// addGlobalVariable - Add global variable into GVs.
1247 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1248   if (DIG.isNull())
1249     return false;
1250
1251   if (!NodesSeen.insert(DIG.getNode()))
1252     return false;
1253
1254   GVs.push_back(DIG.getNode());
1255   return true;
1256 }
1257
1258 // addSubprogram - Add subprgoram into SPs.
1259 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1260   if (SP.isNull())
1261     return false;
1262
1263   if (!NodesSeen.insert(SP.getNode()))
1264     return false;
1265
1266   SPs.push_back(SP.getNode());
1267   return true;
1268 }
1269
1270 namespace llvm {
1271   /// findStopPoint - Find the stoppoint coressponding to this instruction, that
1272   /// is the stoppoint that dominates this instruction.
1273   const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
1274     if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
1275       return DSI;
1276
1277     const BasicBlock *BB = Inst->getParent();
1278     BasicBlock::const_iterator I = Inst, B;
1279     while (BB) {
1280       B = BB->begin();
1281
1282       // A BB consisting only of a terminator can't have a stoppoint.
1283       while (I != B) {
1284         --I;
1285         if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1286           return DSI;
1287       }
1288
1289       // This BB didn't have a stoppoint: if there is only one predecessor, look
1290       // for a stoppoint there. We could use getIDom(), but that would require
1291       // dominator info.
1292       BB = I->getParent()->getUniquePredecessor();
1293       if (BB)
1294         I = BB->getTerminator();
1295     }
1296
1297     return 0;
1298   }
1299
1300   /// findBBStopPoint - Find the stoppoint corresponding to first real
1301   /// (non-debug intrinsic) instruction in this Basic Block, and return the
1302   /// stoppoint for it.
1303   const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1304     for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1305       if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1306         return DSI;
1307
1308     // Fallback to looking for stoppoint of unique predecessor. Useful if this
1309     // BB contains no stoppoints, but unique predecessor does.
1310     BB = BB->getUniquePredecessor();
1311     if (BB)
1312       return findStopPoint(BB->getTerminator());
1313
1314     return 0;
1315   }
1316
1317   Value *findDbgGlobalDeclare(GlobalVariable *V) {
1318     const Module *M = V->getParent();
1319     NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1320     if (!NMD)
1321       return 0;
1322
1323     for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1324       DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
1325       if (DIG.isNull())
1326         continue;
1327       if (DIG.getGlobal() == V)
1328         return DIG.getNode();
1329     }
1330     return 0;
1331   }
1332
1333   /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1334   /// It looks through pointer casts too.
1335   const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1336     if (stripCasts) {
1337       V = V->stripPointerCasts();
1338
1339       // Look for the bitcast.
1340       for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1341             I != E; ++I)
1342         if (isa<BitCastInst>(I)) {
1343           const DbgDeclareInst *DDI = findDbgDeclare(*I, false);
1344           if (DDI) return DDI;
1345         }
1346       return 0;
1347     }
1348
1349     // Find llvm.dbg.declare among uses of the instruction.
1350     for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1351           I != E; ++I)
1352       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1353         return DDI;
1354
1355     return 0;
1356   }
1357
1358 bool getLocationInfo(const Value *V, std::string &DisplayName,
1359                      std::string &Type, unsigned &LineNo, std::string &File,
1360                        std::string &Dir) {
1361     DICompileUnit Unit;
1362     DIType TypeD;
1363
1364     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1365       Value *DIGV = findDbgGlobalDeclare(GV);
1366       if (!DIGV) return false;
1367       DIGlobalVariable Var(cast<MDNode>(DIGV));
1368
1369       StringRef D = Var.getDisplayName();
1370       if (!D.empty())
1371         DisplayName = D;
1372       LineNo = Var.getLineNumber();
1373       Unit = Var.getCompileUnit();
1374       TypeD = Var.getType();
1375     } else {
1376       const DbgDeclareInst *DDI = findDbgDeclare(V);
1377       if (!DDI) return false;
1378       DIVariable Var(cast<MDNode>(DDI->getVariable()));
1379
1380       StringRef D = Var.getName();
1381       if (!D.empty())
1382         DisplayName = D;
1383       LineNo = Var.getLineNumber();
1384       Unit = Var.getCompileUnit();
1385       TypeD = Var.getType();
1386     }
1387
1388     StringRef T = TypeD.getName();
1389     if (!T.empty())
1390       Type = T;
1391     StringRef F = Unit.getFilename();
1392     if (!F.empty())
1393       File = F;
1394     StringRef D = Unit.getDirectory();
1395     if (!D.empty())
1396       Dir = D;
1397     return true;
1398   }
1399
1400   /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug
1401   /// info intrinsic.
1402   bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI,
1403                                  CodeGenOpt::Level OptLev) {
1404     return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1405   }
1406
1407   /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug
1408   /// info intrinsic.
1409   bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1410                                  CodeGenOpt::Level OptLev) {
1411     return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1412   }
1413
1414   /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug
1415   /// info intrinsic.
1416   bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1417                                  CodeGenOpt::Level OptLev) {
1418     return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1419   }
1420
1421   /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug
1422   /// info intrinsic.
1423   bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1424                                  CodeGenOpt::Level OptLev) {
1425     return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1426   }
1427
1428
1429   /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug
1430   /// info intrinsic.
1431   bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1432                                  CodeGenOpt::Level OptLev) {
1433     return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1434   }
1435
1436   /// ExtractDebugLocation - Extract debug location information
1437   /// from llvm.dbg.stoppoint intrinsic.
1438   DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1439                                 DebugLocTracker &DebugLocInfo) {
1440     DebugLoc DL;
1441     Value *Context = SPI.getContext();
1442
1443     // If this location is already tracked then use it.
1444     DebugLocTuple Tuple(cast<MDNode>(Context), NULL, SPI.getLine(),
1445                         SPI.getColumn());
1446     DenseMap<DebugLocTuple, unsigned>::iterator II
1447       = DebugLocInfo.DebugIdMap.find(Tuple);
1448     if (II != DebugLocInfo.DebugIdMap.end())
1449       return DebugLoc::get(II->second);
1450
1451     // Add a new location entry.
1452     unsigned Id = DebugLocInfo.DebugLocations.size();
1453     DebugLocInfo.DebugLocations.push_back(Tuple);
1454     DebugLocInfo.DebugIdMap[Tuple] = Id;
1455
1456     return DebugLoc::get(Id);
1457   }
1458
1459   /// ExtractDebugLocation - Extract debug location information
1460   /// from DILocation.
1461   DebugLoc ExtractDebugLocation(DILocation &Loc,
1462                                 DebugLocTracker &DebugLocInfo) {
1463     DebugLoc DL;
1464     MDNode *Context = Loc.getScope().getNode();
1465     MDNode *InlinedLoc = NULL;
1466     if (!Loc.getOrigLocation().isNull())
1467       InlinedLoc = Loc.getOrigLocation().getNode();
1468     // If this location is already tracked then use it.
1469     DebugLocTuple Tuple(Context, InlinedLoc, Loc.getLineNumber(),
1470                         Loc.getColumnNumber());
1471     DenseMap<DebugLocTuple, unsigned>::iterator II
1472       = DebugLocInfo.DebugIdMap.find(Tuple);
1473     if (II != DebugLocInfo.DebugIdMap.end())
1474       return DebugLoc::get(II->second);
1475
1476     // Add a new location entry.
1477     unsigned Id = DebugLocInfo.DebugLocations.size();
1478     DebugLocInfo.DebugLocations.push_back(Tuple);
1479     DebugLocInfo.DebugIdMap[Tuple] = Id;
1480
1481     return DebugLoc::get(Id);
1482   }
1483
1484   /// ExtractDebugLocation - Extract debug location information
1485   /// from llvm.dbg.func_start intrinsic.
1486   DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1487                                 DebugLocTracker &DebugLocInfo) {
1488     DebugLoc DL;
1489     Value *SP = FSI.getSubprogram();
1490
1491     DISubprogram Subprogram(cast<MDNode>(SP));
1492     unsigned Line = Subprogram.getLineNumber();
1493     DICompileUnit CU(Subprogram.getCompileUnit());
1494
1495     // If this location is already tracked then use it.
1496     DebugLocTuple Tuple(CU.getNode(), NULL, Line, /* Column */ 0);
1497     DenseMap<DebugLocTuple, unsigned>::iterator II
1498       = DebugLocInfo.DebugIdMap.find(Tuple);
1499     if (II != DebugLocInfo.DebugIdMap.end())
1500       return DebugLoc::get(II->second);
1501
1502     // Add a new location entry.
1503     unsigned Id = DebugLocInfo.DebugLocations.size();
1504     DebugLocInfo.DebugLocations.push_back(Tuple);
1505     DebugLocInfo.DebugIdMap[Tuple] = Id;
1506
1507     return DebugLoc::get(Id);
1508   }
1509
1510   /// getDISubprogram - Find subprogram that is enclosing this scope.
1511   DISubprogram getDISubprogram(MDNode *Scope) {
1512     DIDescriptor D(Scope);
1513     if (D.isNull())
1514       return DISubprogram();
1515     
1516     if (D.isCompileUnit())
1517       return DISubprogram();
1518     
1519     if (D.isSubprogram())
1520       return DISubprogram(Scope);
1521     
1522     if (D.isLexicalBlock())
1523       return getDISubprogram(DILexicalBlock(Scope).getContext().getNode());
1524     
1525     return DISubprogram();
1526   }
1527
1528   /// getDICompositeType - Find underlying composite type.
1529   DICompositeType getDICompositeType(DIType T) {
1530     if (T.isNull())
1531       return DICompositeType();
1532     
1533     if (T.isCompositeType())
1534       return DICompositeType(T.getNode());
1535     
1536     if (T.isDerivedType())
1537       return getDICompositeType(DIDerivedType(T.getNode()).getTypeDerivedFrom());
1538     
1539     return DICompositeType();
1540   }
1541 }