Temporarily XFAIL this test.
[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/Module.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/Support/Streams.h"
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 // DIDescriptor
28 //===----------------------------------------------------------------------===//
29
30 DIDescriptor::DIDescriptor(GlobalVariable *gv, unsigned RequiredTag) {
31   GV = gv;
32   
33   // If this is non-null, check to see if the Tag matches.  If not, set to null.
34   if (GV && getTag() != RequiredTag)
35     GV = 0;
36 }
37
38 const char *DIDescriptor::getStringField(unsigned Elt) const {
39   if (GV == 0)
40     return 0;
41
42   Constant *C = GV->getInitializer();
43   if (C == 0 || Elt >= C->getNumOperands())
44     return 0;
45   
46   // Fills in the string if it succeeds
47   return GetConstantStringInfo(C->getOperand(Elt));
48 }
49
50 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
51   if (GV == 0) return 0;
52   Constant *C = GV->getInitializer();
53   if (C == 0 || Elt >= C->getNumOperands())
54     return 0;
55   if (ConstantInt *CI = dyn_cast<ConstantInt>(C->getOperand(Elt)))
56     return CI->getZExtValue();
57   return 0;
58 }
59
60 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
61   if (GV == 0) return DIDescriptor();
62   Constant *C = GV->getInitializer();
63   if (C == 0 || Elt >= C->getNumOperands())
64     return DIDescriptor();
65   C = C->getOperand(Elt);
66   return DIDescriptor(dyn_cast<GlobalVariable>(C->stripPointerCasts()));
67 }
68
69 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
70   if (GV == 0) return 0;
71   Constant *C = GV->getInitializer();
72   if (C == 0 || Elt >= C->getNumOperands())
73     return 0;
74   C = C->getOperand(Elt);
75   
76   return dyn_cast<GlobalVariable>(C->stripPointerCasts());
77 }
78
79
80
81 //===----------------------------------------------------------------------===//
82 // Simple Descriptor Constructors and other Methods
83 //===----------------------------------------------------------------------===//
84
85 DIAnchor::DIAnchor(GlobalVariable *GV)
86   : DIDescriptor(GV, dwarf::DW_TAG_anchor) {}
87 DIEnumerator::DIEnumerator(GlobalVariable *GV)
88   : DIDescriptor(GV, dwarf::DW_TAG_enumerator) {}
89 DISubrange::DISubrange(GlobalVariable *GV)
90   : DIDescriptor(GV, dwarf::DW_TAG_subrange_type) {}
91 DICompileUnit::DICompileUnit(GlobalVariable *GV)
92   : DIDescriptor(GV, dwarf::DW_TAG_compile_unit) {}
93 DIBasicType::DIBasicType(GlobalVariable *GV)
94   : DIType(GV, dwarf::DW_TAG_base_type) {}
95 DISubprogram::DISubprogram(GlobalVariable *GV)
96   : DIGlobal(GV, dwarf::DW_TAG_subprogram) {}
97 DIGlobalVariable::DIGlobalVariable(GlobalVariable *GV)
98   : DIGlobal(GV, dwarf::DW_TAG_variable) {}
99 DIBlock::DIBlock(GlobalVariable *GV)
100   : DIDescriptor(GV, dwarf::DW_TAG_lexical_block) {}
101 // needed by DIVariable::getType()
102 DIType::DIType(GlobalVariable *gv) : DIDescriptor(gv) {
103   if (!gv) return;
104   unsigned tag = getTag();
105   if (tag != dwarf::DW_TAG_base_type && !DIDerivedType::isDerivedType(tag) &&
106       !DICompositeType::isCompositeType(tag))
107     GV = 0;
108 }
109
110 /// isDerivedType - Return true if the specified tag is legal for
111 /// DIDerivedType.
112 bool DIType::isDerivedType(unsigned Tag) {
113   switch (Tag) {
114   case dwarf::DW_TAG_typedef:
115   case dwarf::DW_TAG_pointer_type:
116   case dwarf::DW_TAG_reference_type:
117   case dwarf::DW_TAG_const_type:
118   case dwarf::DW_TAG_volatile_type:
119   case dwarf::DW_TAG_restrict_type:
120   case dwarf::DW_TAG_member:
121   case dwarf::DW_TAG_inheritance:
122     return true;
123   default:
124     // FIXME: Even though it doesn't make sense, CompositeTypes are current
125     // modelled as DerivedTypes, this should return true for them as well.
126     return false;
127   }
128 }
129
130 DIDerivedType::DIDerivedType(GlobalVariable *GV) : DIType(GV, true, true) {
131   if (GV && !isDerivedType(getTag()))
132     GV = 0;
133 }
134
135 /// isCompositeType - Return true if the specified tag is legal for
136 /// DICompositeType.
137 bool DIType::isCompositeType(unsigned TAG) {
138   switch (TAG) {
139   case dwarf::DW_TAG_array_type:
140   case dwarf::DW_TAG_structure_type:
141   case dwarf::DW_TAG_union_type:
142   case dwarf::DW_TAG_enumeration_type:
143   case dwarf::DW_TAG_vector_type:
144   case dwarf::DW_TAG_subroutine_type:
145     return true;
146   default:
147     return false;
148   }
149 }
150
151 DICompositeType::DICompositeType(GlobalVariable *GV)
152   : DIDerivedType(GV, true, true) {
153   if (GV && !isCompositeType(getTag()))
154     GV = 0;
155 }
156
157 /// isVariable - Return true if the specified tag is legal for DIVariable.
158 bool DIVariable::isVariable(unsigned Tag) {
159   switch (Tag) {
160   case dwarf::DW_TAG_auto_variable:
161   case dwarf::DW_TAG_arg_variable:
162   case dwarf::DW_TAG_return_variable:
163     return true;
164   default:
165     return false;
166   }
167 }
168
169 DIVariable::DIVariable(GlobalVariable *gv) : DIDescriptor(gv) {
170   if (gv && !isVariable(getTag()))
171     GV = 0;
172 }
173
174 unsigned DIArray::getNumElements() const {
175   assert (GV && "Invalid DIArray");
176   Constant *C = GV->getInitializer();
177   assert (C && "Invalid DIArray initializer");
178   return C->getNumOperands();
179 }
180
181 /// Verify - Verify that a compile unit is well formed.
182 bool DICompileUnit::Verify() const {
183   if (isNull()) 
184     return false;
185
186   // It is possible that directory and produce string is empty.
187   return getFilename();
188 }
189
190 /// Verify - Verify that a type descriptor is well formed.
191 bool DIType::Verify() const {
192   if (isNull()) 
193     return false;
194   if (getContext().isNull()) 
195     return false;
196
197   DICompileUnit CU = getCompileUnit();
198   if (!CU.isNull() && !CU.Verify()) 
199     return false;
200   return true;
201 }
202
203 /// Verify - Verify that a composite type descriptor is well formed.
204 bool DICompositeType::Verify() const {
205   if (isNull()) 
206     return false;
207   if (getContext().isNull()) 
208     return false;
209
210   DICompileUnit CU = getCompileUnit();
211   if (!CU.isNull() && !CU.Verify()) 
212     return false;
213   return true;
214 }
215
216 /// Verify - Verify that a subprogram descriptor is well formed.
217 bool DISubprogram::Verify() const {
218   if (isNull())
219     return false;
220   
221   if (getContext().isNull())
222     return false;
223
224   DICompileUnit CU = getCompileUnit();
225   if (!CU.Verify()) 
226     return false;
227
228   DICompositeType Ty = getType();
229   if (!Ty.isNull() && !Ty.Verify())
230     return false;
231   return true;
232 }
233
234 /// Verify - Verify that a global variable descriptor is well formed.
235 bool DIGlobalVariable::Verify() const {
236   if (isNull())
237     return false;
238   
239   if (getContext().isNull())
240     return false;
241
242   DICompileUnit CU = getCompileUnit();
243   if (!CU.Verify()) 
244     return false;
245
246   DIType Ty = getType();
247   if (!Ty.Verify())
248     return false;
249
250   if (!getGlobal())
251     return false;
252
253   return true;
254 }
255
256 /// Verify - Verify that a variable descriptor is well formed.
257 bool DIVariable::Verify() const {
258   if (isNull())
259     return false;
260   
261   if (getContext().isNull())
262     return false;
263
264   DIType Ty = getType();
265   if (!Ty.Verify())
266     return false;
267
268
269   return true;
270 }
271
272 /// getOriginalTypeSize - If this type is derived from a base type then
273 /// return base type size.
274 uint64_t DIDerivedType::getOriginalTypeSize() const {
275   if (getTag() != dwarf::DW_TAG_member)
276     return getSizeInBits();
277   DIType BT = getTypeDerivedFrom();
278   if (BT.getTag() != dwarf::DW_TAG_base_type)
279     return getSizeInBits();
280   return BT.getSizeInBits();
281 }
282
283 //===----------------------------------------------------------------------===//
284 // DIFactory: Basic Helpers
285 //===----------------------------------------------------------------------===//
286
287 DIFactory::DIFactory(Module &m) : M(m) {
288   StopPointFn = FuncStartFn = RegionStartFn = RegionEndFn = DeclareFn = 0;
289   EmptyStructPtr = PointerType::getUnqual(StructType::get(NULL, NULL));
290 }
291
292 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
293 /// This is only valid when the descriptor is non-null.
294 Constant *DIFactory::getCastToEmpty(DIDescriptor D) {
295   if (D.isNull()) return Constant::getNullValue(EmptyStructPtr);
296   return ConstantExpr::getBitCast(D.getGV(), EmptyStructPtr);
297 }
298
299 Constant *DIFactory::GetTagConstant(unsigned TAG) {
300   assert((TAG & LLVMDebugVersionMask) == 0 &&
301          "Tag too large for debug encoding!");
302   return ConstantInt::get(Type::Int32Ty, TAG | LLVMDebugVersion);
303 }
304
305 Constant *DIFactory::GetStringConstant(const std::string &String) {
306   // Check string cache for previous edition.
307   Constant *&Slot = StringCache[String];
308   
309   // Return Constant if previously defined.
310   if (Slot) return Slot;
311   
312   const PointerType *DestTy = PointerType::getUnqual(Type::Int8Ty);
313   
314   // If empty string then use a sbyte* null instead.
315   if (String.empty())
316     return Slot = ConstantPointerNull::get(DestTy);
317
318   // Construct string as an llvm constant.
319   Constant *ConstStr = ConstantArray::get(String);
320     
321   // Otherwise create and return a new string global.
322   GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
323                                              GlobalVariable::InternalLinkage,
324                                              ConstStr, ".str", &M);
325   StrGV->setSection("llvm.metadata");
326   return Slot = ConstantExpr::getBitCast(StrGV, DestTy);
327 }
328
329 /// GetOrCreateAnchor - Look up an anchor for the specified tag and name.  If it
330 /// already exists, return it.  If not, create a new one and return it.
331 DIAnchor DIFactory::GetOrCreateAnchor(unsigned TAG, const char *Name) {
332   const Type *EltTy = StructType::get(Type::Int32Ty, Type::Int32Ty, NULL);
333   
334   // Otherwise, create the global or return it if already in the module.
335   Constant *C = M.getOrInsertGlobal(Name, EltTy);
336   assert(isa<GlobalVariable>(C) && "Incorrectly typed anchor?");
337   GlobalVariable *GV = cast<GlobalVariable>(C);
338   
339   // If it has an initializer, it is already in the module.
340   if (GV->hasInitializer()) 
341     return SubProgramAnchor = DIAnchor(GV);
342   
343   GV->setLinkage(GlobalValue::LinkOnceAnyLinkage);
344   GV->setSection("llvm.metadata");
345   GV->setConstant(true);
346   M.addTypeName("llvm.dbg.anchor.type", EltTy);
347   
348   // Otherwise, set the initializer.
349   Constant *Elts[] = {
350     GetTagConstant(dwarf::DW_TAG_anchor),
351     ConstantInt::get(Type::Int32Ty, TAG)
352   };
353   
354   GV->setInitializer(ConstantStruct::get(Elts, 2));
355   return DIAnchor(GV);
356 }
357
358
359
360 //===----------------------------------------------------------------------===//
361 // DIFactory: Primary Constructors
362 //===----------------------------------------------------------------------===//
363
364 /// GetOrCreateCompileUnitAnchor - Return the anchor for compile units,
365 /// creating a new one if there isn't already one in the module.
366 DIAnchor DIFactory::GetOrCreateCompileUnitAnchor() {
367   // If we already created one, just return it.
368   if (!CompileUnitAnchor.isNull())
369     return CompileUnitAnchor;
370   return CompileUnitAnchor = GetOrCreateAnchor(dwarf::DW_TAG_compile_unit,
371                                                "llvm.dbg.compile_units");
372 }
373
374 /// GetOrCreateSubprogramAnchor - Return the anchor for subprograms,
375 /// creating a new one if there isn't already one in the module.
376 DIAnchor DIFactory::GetOrCreateSubprogramAnchor() {
377   // If we already created one, just return it.
378   if (!SubProgramAnchor.isNull())
379     return SubProgramAnchor;
380   return SubProgramAnchor = GetOrCreateAnchor(dwarf::DW_TAG_subprogram,
381                                               "llvm.dbg.subprograms");
382 }
383
384 /// GetOrCreateGlobalVariableAnchor - Return the anchor for globals,
385 /// creating a new one if there isn't already one in the module.
386 DIAnchor DIFactory::GetOrCreateGlobalVariableAnchor() {
387   // If we already created one, just return it.
388   if (!GlobalVariableAnchor.isNull())
389     return GlobalVariableAnchor;
390   return GlobalVariableAnchor = GetOrCreateAnchor(dwarf::DW_TAG_variable,
391                                                   "llvm.dbg.global_variables");
392 }
393
394 /// GetOrCreateArray - Create an descriptor for an array of descriptors. 
395 /// This implicitly uniques the arrays created.
396 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
397   SmallVector<Constant*, 16> Elts;
398   
399   for (unsigned i = 0; i != NumTys; ++i)
400     Elts.push_back(getCastToEmpty(Tys[i]));
401   
402   Constant *Init = ConstantArray::get(ArrayType::get(EmptyStructPtr,
403                                                      Elts.size()),
404                                       &Elts[0], Elts.size());
405   // If we already have this array, just return the uniqued version.
406   DIDescriptor &Entry = SimpleConstantCache[Init];
407   if (!Entry.isNull()) return DIArray(Entry.getGV());
408   
409   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
410                                           GlobalValue::InternalLinkage,
411                                           Init, "llvm.dbg.array", &M);
412   GV->setSection("llvm.metadata");
413   Entry = DIDescriptor(GV);
414   return DIArray(GV);
415 }
416
417 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
418 /// implicitly uniques the values returned.
419 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
420   Constant *Elts[] = {
421     GetTagConstant(dwarf::DW_TAG_subrange_type),
422     ConstantInt::get(Type::Int64Ty, Lo),
423     ConstantInt::get(Type::Int64Ty, Hi)
424   };
425   
426   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
427
428   // If we already have this range, just return the uniqued version.
429   DIDescriptor &Entry = SimpleConstantCache[Init];
430   if (!Entry.isNull()) return DISubrange(Entry.getGV());
431   
432   M.addTypeName("llvm.dbg.subrange.type", Init->getType());
433
434   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
435                                           GlobalValue::InternalLinkage,
436                                           Init, "llvm.dbg.subrange", &M);
437   GV->setSection("llvm.metadata");
438   Entry = DIDescriptor(GV);
439   return DISubrange(GV);
440 }
441
442
443
444 /// CreateCompileUnit - Create a new descriptor for the specified compile
445 /// unit.  Note that this does not unique compile units within the module.
446 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
447                                            const std::string &Filename,
448                                            const std::string &Directory,
449                                            const std::string &Producer,
450                                            bool isMain,
451                                            bool isOptimized,
452                                            const char *Flags,
453                                            unsigned RunTimeVer) {
454   Constant *Elts[] = {
455     GetTagConstant(dwarf::DW_TAG_compile_unit),
456     getCastToEmpty(GetOrCreateCompileUnitAnchor()),
457     ConstantInt::get(Type::Int32Ty, LangID),
458     GetStringConstant(Filename),
459     GetStringConstant(Directory),
460     GetStringConstant(Producer),
461     ConstantInt::get(Type::Int1Ty, isMain),
462     ConstantInt::get(Type::Int1Ty, isOptimized),
463     GetStringConstant(Flags),
464     ConstantInt::get(Type::Int32Ty, RunTimeVer)
465   };
466   
467   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
468   
469   M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
470   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
471                                           GlobalValue::InternalLinkage,
472                                           Init, "llvm.dbg.compile_unit", &M);
473   GV->setSection("llvm.metadata");
474   return DICompileUnit(GV);
475 }
476
477 /// CreateEnumerator - Create a single enumerator value.
478 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
479   Constant *Elts[] = {
480     GetTagConstant(dwarf::DW_TAG_enumerator),
481     GetStringConstant(Name),
482     ConstantInt::get(Type::Int64Ty, Val)
483   };
484   
485   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
486   
487   M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
488   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
489                                           GlobalValue::InternalLinkage,
490                                           Init, "llvm.dbg.enumerator", &M);
491   GV->setSection("llvm.metadata");
492   return DIEnumerator(GV);
493 }
494
495
496 /// CreateBasicType - Create a basic type like int, float, etc.
497 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
498                                        const std::string &Name,
499                                        DICompileUnit CompileUnit,
500                                        unsigned LineNumber,
501                                        uint64_t SizeInBits,
502                                        uint64_t AlignInBits,
503                                        uint64_t OffsetInBits, unsigned Flags,
504                                        unsigned Encoding) {
505   Constant *Elts[] = {
506     GetTagConstant(dwarf::DW_TAG_base_type),
507     getCastToEmpty(Context),
508     GetStringConstant(Name),
509     getCastToEmpty(CompileUnit),
510     ConstantInt::get(Type::Int32Ty, LineNumber),
511     ConstantInt::get(Type::Int64Ty, SizeInBits),
512     ConstantInt::get(Type::Int64Ty, AlignInBits),
513     ConstantInt::get(Type::Int64Ty, OffsetInBits),
514     ConstantInt::get(Type::Int32Ty, Flags),
515     ConstantInt::get(Type::Int32Ty, Encoding)
516   };
517   
518   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
519   
520   M.addTypeName("llvm.dbg.basictype.type", Init->getType());
521   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
522                                           GlobalValue::InternalLinkage,
523                                           Init, "llvm.dbg.basictype", &M);
524   GV->setSection("llvm.metadata");
525   return DIBasicType(GV);
526 }
527
528 /// CreateDerivedType - Create a derived type like const qualified type,
529 /// pointer, typedef, etc.
530 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
531                                            DIDescriptor Context,
532                                            const std::string &Name,
533                                            DICompileUnit CompileUnit,
534                                            unsigned LineNumber,
535                                            uint64_t SizeInBits,
536                                            uint64_t AlignInBits,
537                                            uint64_t OffsetInBits,
538                                            unsigned Flags,
539                                            DIType DerivedFrom) {
540   Constant *Elts[] = {
541     GetTagConstant(Tag),
542     getCastToEmpty(Context),
543     GetStringConstant(Name),
544     getCastToEmpty(CompileUnit),
545     ConstantInt::get(Type::Int32Ty, LineNumber),
546     ConstantInt::get(Type::Int64Ty, SizeInBits),
547     ConstantInt::get(Type::Int64Ty, AlignInBits),
548     ConstantInt::get(Type::Int64Ty, OffsetInBits),
549     ConstantInt::get(Type::Int32Ty, Flags),
550     getCastToEmpty(DerivedFrom)
551   };
552   
553   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
554   
555   M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
556   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
557                                           GlobalValue::InternalLinkage,
558                                           Init, "llvm.dbg.derivedtype", &M);
559   GV->setSection("llvm.metadata");
560   return DIDerivedType(GV);
561 }
562
563 /// CreateCompositeType - Create a composite type like array, struct, etc.
564 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
565                                                DIDescriptor Context,
566                                                const std::string &Name,
567                                                DICompileUnit CompileUnit,
568                                                unsigned LineNumber,
569                                                uint64_t SizeInBits,
570                                                uint64_t AlignInBits,
571                                                uint64_t OffsetInBits,
572                                                unsigned Flags,
573                                                DIType DerivedFrom,
574                                                DIArray Elements,
575                                                unsigned RuntimeLang) {
576
577   Constant *Elts[] = {
578     GetTagConstant(Tag),
579     getCastToEmpty(Context),
580     GetStringConstant(Name),
581     getCastToEmpty(CompileUnit),
582     ConstantInt::get(Type::Int32Ty, LineNumber),
583     ConstantInt::get(Type::Int64Ty, SizeInBits),
584     ConstantInt::get(Type::Int64Ty, AlignInBits),
585     ConstantInt::get(Type::Int64Ty, OffsetInBits),
586     ConstantInt::get(Type::Int32Ty, Flags),
587     getCastToEmpty(DerivedFrom),
588     getCastToEmpty(Elements),
589     ConstantInt::get(Type::Int32Ty, RuntimeLang)
590   };
591   
592   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
593   
594   M.addTypeName("llvm.dbg.composite.type", Init->getType());
595   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
596                                           GlobalValue::InternalLinkage,
597                                           Init, "llvm.dbg.composite", &M);
598   GV->setSection("llvm.metadata");
599   return DICompositeType(GV);
600 }
601
602
603 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
604 /// See comments in DISubprogram for descriptions of these fields.  This
605 /// method does not unique the generated descriptors.
606 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context, 
607                                          const std::string &Name,
608                                          const std::string &DisplayName,
609                                          const std::string &LinkageName,
610                                          DICompileUnit CompileUnit,
611                                          unsigned LineNo, DIType Type,
612                                          bool isLocalToUnit,
613                                          bool isDefinition) {
614
615   Constant *Elts[] = {
616     GetTagConstant(dwarf::DW_TAG_subprogram),
617     getCastToEmpty(GetOrCreateSubprogramAnchor()),
618     getCastToEmpty(Context),
619     GetStringConstant(Name),
620     GetStringConstant(DisplayName),
621     GetStringConstant(LinkageName),
622     getCastToEmpty(CompileUnit),
623     ConstantInt::get(Type::Int32Ty, LineNo),
624     getCastToEmpty(Type),
625     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
626     ConstantInt::get(Type::Int1Ty, isDefinition)
627   };
628   
629   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
630   
631   M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
632   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
633                                           GlobalValue::InternalLinkage,
634                                           Init, "llvm.dbg.subprogram", &M);
635   GV->setSection("llvm.metadata");
636   return DISubprogram(GV);
637 }
638
639 /// CreateGlobalVariable - Create a new descriptor for the specified global.
640 DIGlobalVariable
641 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
642                                 const std::string &DisplayName,
643                                 const std::string &LinkageName,
644                                 DICompileUnit CompileUnit,
645                                 unsigned LineNo, DIType Type,bool isLocalToUnit,
646                                 bool isDefinition, llvm::GlobalVariable *Val) {
647   Constant *Elts[] = {
648     GetTagConstant(dwarf::DW_TAG_variable),
649     getCastToEmpty(GetOrCreateGlobalVariableAnchor()),
650     getCastToEmpty(Context),
651     GetStringConstant(Name),
652     GetStringConstant(DisplayName),
653     GetStringConstant(LinkageName),
654     getCastToEmpty(CompileUnit),
655     ConstantInt::get(Type::Int32Ty, LineNo),
656     getCastToEmpty(Type),
657     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
658     ConstantInt::get(Type::Int1Ty, isDefinition),
659     ConstantExpr::getBitCast(Val, EmptyStructPtr)
660   };
661   
662   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
663   
664   M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
665   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
666                                           GlobalValue::InternalLinkage,
667                                           Init, "llvm.dbg.global_variable", &M);
668   GV->setSection("llvm.metadata");
669   return DIGlobalVariable(GV);
670 }
671
672
673 /// CreateVariable - Create a new descriptor for the specified variable.
674 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
675                                      const std::string &Name,
676                                      DICompileUnit CompileUnit, unsigned LineNo,
677                                      DIType Type) {
678   Constant *Elts[] = {
679     GetTagConstant(Tag),
680     getCastToEmpty(Context),
681     GetStringConstant(Name),
682     getCastToEmpty(CompileUnit),
683     ConstantInt::get(Type::Int32Ty, LineNo),
684     getCastToEmpty(Type)
685   };
686   
687   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
688   
689   M.addTypeName("llvm.dbg.variable.type", Init->getType());
690   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
691                                           GlobalValue::InternalLinkage,
692                                           Init, "llvm.dbg.variable", &M);
693   GV->setSection("llvm.metadata");
694   return DIVariable(GV);
695 }
696
697
698 /// CreateBlock - This creates a descriptor for a lexical block with the
699 /// specified parent context.
700 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
701   Constant *Elts[] = {
702     GetTagConstant(dwarf::DW_TAG_lexical_block),
703     getCastToEmpty(Context)
704   };
705   
706   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
707   
708   M.addTypeName("llvm.dbg.block.type", Init->getType());
709   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
710                                           GlobalValue::InternalLinkage,
711                                           Init, "llvm.dbg.block", &M);
712   GV->setSection("llvm.metadata");
713   return DIBlock(GV);
714 }
715
716
717 //===----------------------------------------------------------------------===//
718 // DIFactory: Routines for inserting code into a function
719 //===----------------------------------------------------------------------===//
720
721 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
722 /// inserting it at the end of the specified basic block.
723 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
724                                 unsigned ColNo, BasicBlock *BB) {
725   
726   // Lazily construct llvm.dbg.stoppoint function.
727   if (!StopPointFn)
728     StopPointFn = llvm::Intrinsic::getDeclaration(&M, 
729                                               llvm::Intrinsic::dbg_stoppoint);
730   
731   // Invoke llvm.dbg.stoppoint
732   Value *Args[] = {
733     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo),
734     llvm::ConstantInt::get(llvm::Type::Int32Ty, ColNo),
735     getCastToEmpty(CU)
736   };
737   CallInst::Create(StopPointFn, Args, Args+3, "", BB);
738 }
739
740 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
741 /// mark the start of the specified subprogram.
742 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
743   // Lazily construct llvm.dbg.func.start.
744   if (!FuncStartFn)
745     FuncStartFn = llvm::Intrinsic::getDeclaration(&M, 
746                                               llvm::Intrinsic::dbg_func_start);
747   
748   // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
749   CallInst::Create(FuncStartFn, getCastToEmpty(SP), "", BB);
750 }
751
752 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
753 /// mark the start of a region for the specified scoping descriptor.
754 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
755   // Lazily construct llvm.dbg.region.start function.
756   if (!RegionStartFn)
757     RegionStartFn = llvm::Intrinsic::getDeclaration(&M, 
758                                             llvm::Intrinsic::dbg_region_start);
759   // Call llvm.dbg.func.start.
760   CallInst::Create(RegionStartFn, getCastToEmpty(D), "", BB);
761 }
762
763
764 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
765 /// mark the end of a region for the specified scoping descriptor.
766 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
767   // Lazily construct llvm.dbg.region.end function.
768   if (!RegionEndFn)
769     RegionEndFn = llvm::Intrinsic::getDeclaration(&M,
770                                                llvm::Intrinsic::dbg_region_end);
771   
772   CallInst::Create(RegionEndFn, getCastToEmpty(D), "", BB);
773 }
774
775 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
776 void DIFactory::InsertDeclare(llvm::Value *Storage, DIVariable D,
777                               BasicBlock *BB) {
778   // Cast the storage to a {}* for the call to llvm.dbg.declare.
779   Storage = new llvm::BitCastInst(Storage, EmptyStructPtr, "", BB);
780   
781   if (!DeclareFn)
782     DeclareFn = llvm::Intrinsic::getDeclaration(&M,
783                                                 llvm::Intrinsic::dbg_declare);
784   Value *Args[] = { Storage, getCastToEmpty(D) };
785   CallInst::Create(DeclareFn, Args, Args+2, "", BB);
786 }
787
788 namespace llvm {
789   /// Finds the stoppoint coressponding to this instruction, that is the
790   /// stoppoint that dominates this instruction 
791   const DbgStopPointInst *findStopPoint(const Instruction *Inst)
792   {
793     if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
794       return DSI;
795
796     const BasicBlock *BB = Inst->getParent();
797     BasicBlock::const_iterator I = Inst, B;
798     do {
799       B = BB->begin();
800       // A BB consisting only of a terminator can't have a stoppoint.
801       if (I != B) {
802         do {
803           --I;
804           if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
805             return DSI;
806         } while (I != B);
807       }
808       // This BB didn't have a stoppoint: if there is only one
809       // predecessor, look for a stoppoint there.
810       // We could use getIDom(), but that would require dominator info.
811       BB = I->getParent()->getUniquePredecessor();
812       if (BB)
813         I = BB->getTerminator();
814     } while (BB != 0);
815     return 0;
816   }
817
818   /// Finds the stoppoint corresponding to first real (non-debug intrinsic) 
819   /// instruction in this Basic Block, and returns the stoppoint for it.
820   const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB)
821   {
822     for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
823       if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
824         return DSI;
825     }
826     // Fallback to looking for stoppoint of unique predecessor.
827     // Useful if this BB contains no stoppoints, but unique predecessor does.
828     BB = BB->getUniquePredecessor();
829     if (BB)
830       return findStopPoint(BB->getTerminator());
831     return 0;
832   }
833
834   Value *findDbgGlobalDeclare(GlobalVariable *V)
835   {
836     const Module *M = V->getParent();
837     const Type *Ty = M->getTypeByName("llvm.dbg.global_variable.type");
838     if (!Ty)
839       return 0;
840     Ty = PointerType::get(Ty, 0);
841
842     Value *Val = V->stripPointerCasts();
843     for (Value::use_iterator I = Val->use_begin(), E =Val->use_end();
844          I != E; ++I) {
845       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I)) {
846         if (CE->getOpcode() == Instruction::BitCast) {
847           Value *VV = CE;
848           while (VV->hasOneUse()) {
849             VV = *VV->use_begin();
850           }
851           if (VV->getType() == Ty)
852             return VV;
853         }
854       }
855     }
856     
857     if (Val->getType() == Ty)
858       return Val;
859     return 0;
860   }
861
862   /// Finds the dbg.declare intrinsic corresponding to this value if any.
863   /// It looks through pointer casts too.
864   const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts)
865   {
866     if (stripCasts) {
867       V = V->stripPointerCasts();
868       // Look for the bitcast.
869       for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
870             I != E; ++I) {
871         if (isa<BitCastInst>(I))
872           return findDbgDeclare(*I, false);
873       }
874       return 0;
875     }
876
877     // Find dbg.declare among uses of the instruction.
878     for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
879           I != E; ++I) {
880       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
881         return DDI;
882     }
883     return 0;
884   }
885
886   bool getLocationInfo(const Value *V, std::string &DisplayName, std::string &Type,
887                        unsigned &LineNo, std::string &File, std::string &Dir) {
888     DICompileUnit Unit;
889     DIType TypeD;
890     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
891       Value *DIGV = findDbgGlobalDeclare(GV);
892       if (!DIGV)
893         return false;
894       DIGlobalVariable Var(cast<GlobalVariable>(DIGV));
895       const char *DN = Var.getDisplayName();
896       if (DN)
897         DisplayName = DN;
898       else
899         DisplayName.clear();
900       LineNo = Var.getLineNumber();
901       Unit = Var.getCompileUnit();
902       TypeD = Var.getType();
903     } else {
904       const DbgDeclareInst *DDI = findDbgDeclare(V);
905       if (!DDI)
906         return false;
907       DIVariable Var(cast<GlobalVariable>(DDI->getVariable()));
908       const char *DN = Var.getName();
909       if (DN)
910         DisplayName = DN;
911       else
912         DisplayName.clear();
913       LineNo = Var.getLineNumber();
914       Unit = Var.getCompileUnit();
915       TypeD = Var.getType();
916     }
917     Type.clear();
918     File.clear();
919     Dir.clear();
920     const char *Str = TypeD.getName();
921     if (Str) Type = Str;
922     Str = Unit.getFilename();
923     if (Str) File = Str;
924     Str = Unit.getDirectory();
925     if (Str) Dir = Str;
926     return true;
927   }
928 }
929
930 /// dump - print compile unit.
931 void DICompileUnit::dump() const {
932   if (getLanguage())
933     cerr << " [" << dwarf::LanguageString(getLanguage()) << "] ";
934
935   const char *Dir = getDirectory();
936   const char *FN = getFilename();
937   cerr << " [" << (Dir ? Dir : "") << "/" << (FN ? FN : "") << " ]";
938 }
939
940 /// dump - print type.
941 void DIType::dump() const {
942   if (isNull()) return;
943
944   if (const char *N = getName())
945     cerr << " [" << N << "] ";
946
947   unsigned Tag = getTag();
948   cerr << " [" << dwarf::TagString(Tag) << "] ";
949
950   // TODO : Print context
951   getCompileUnit().dump();
952   cerr << " [" 
953        << getLineNumber() << ", " 
954        << getSizeInBits() << ", "
955        << getAlignInBits() << ", "
956        << getOffsetInBits() 
957        << "] ";
958
959   if (isPrivate()) 
960     cerr << " [private] ";
961   else if (isProtected())
962     cerr << " [protected] ";
963
964   if (isForwardDecl())
965     cerr << " [fwd] ";
966
967   if (isBasicType(Tag))
968     DIBasicType(GV).dump();
969   else if (isDerivedType(Tag))
970     DIDerivedType(GV).dump();
971   else if (isCompositeType(Tag))
972     DICompositeType(GV).dump();
973   else {
974     cerr << "Invalid DIType\n";
975     return;
976   }
977
978   cerr << "\n";
979 }
980
981 /// dump - print basic type.
982 void DIBasicType::dump() const {
983   cerr << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
984
985 }
986
987 /// dump - print derived type.
988 void DIDerivedType::dump() const {
989   cerr << "\n\t Derived From: "; getTypeDerivedFrom().dump();
990 }
991
992 /// dump - print composite type.
993 void DICompositeType::dump() const {
994   DIArray A = getTypeArray();
995   if (A.isNull())
996     return;
997   cerr << " [" << A.getNumElements() << " elements]";
998 }
999
1000 /// dump - print global.
1001 void DIGlobal::dump() const {
1002   if (const char *N = getName())
1003     cerr << " [" << N << "] ";
1004
1005   unsigned Tag = getTag();
1006   cerr << " [" << dwarf::TagString(Tag) << "] ";
1007
1008   // TODO : Print context
1009   getCompileUnit().dump();
1010   cerr << " [" << getLineNumber() << "] ";
1011
1012   if (isLocalToUnit())
1013     cerr << " [local] ";
1014
1015   if (isDefinition())
1016     cerr << " [def] ";
1017
1018   if (isGlobalVariable(Tag))
1019     DIGlobalVariable(GV).dump();
1020
1021   cerr << "\n";
1022 }
1023
1024 /// dump - print subprogram.
1025 void DISubprogram::dump() const {
1026   DIGlobal::dump();
1027 }
1028
1029 /// dump - print global variable.
1030 void DIGlobalVariable::dump() const {
1031   cerr << " ["; getGlobal()->dump(); cerr << "] ";
1032 }
1033
1034 /// dump - print variable.
1035 void DIVariable::dump() const {
1036   if (const char *N = getName())
1037     cerr << " [" << N << "] ";
1038
1039   getCompileUnit().dump();
1040   cerr << " [" << getLineNumber() << "] ";
1041   getType().dump();
1042   cerr << "\n";
1043 }