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