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