Emit debug info for bitfields.
[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
39 std::string DIDescriptor::getStringField(unsigned Elt) const {
40   if (GV == 0) return "";
41   Constant *C = GV->getInitializer();
42   if (C == 0 || Elt >= C->getNumOperands())
43     return "";
44   
45   std::string Result;
46   // Fills in the string if it succeeds
47   if (!GetConstantStringInfo(C->getOperand(Elt), Result))
48     Result.clear();
49   return Result;
50 }
51
52 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
53   if (GV == 0) return 0;
54   Constant *C = GV->getInitializer();
55   if (C == 0 || Elt >= C->getNumOperands())
56     return 0;
57   if (ConstantInt *CI = dyn_cast<ConstantInt>(C->getOperand(Elt)))
58     return CI->getZExtValue();
59   return 0;
60 }
61
62
63 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
64   if (GV == 0) return DIDescriptor();
65   Constant *C = GV->getInitializer();
66   if (C == 0 || Elt >= C->getNumOperands())
67     return DIDescriptor();
68   C = C->getOperand(Elt);
69   return DIDescriptor(dyn_cast<GlobalVariable>(C->stripPointerCasts()));
70 }
71
72 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
73   if (GV == 0) return 0;
74   Constant *C = GV->getInitializer();
75   if (C == 0 || Elt >= C->getNumOperands())
76     return 0;
77   C = C->getOperand(Elt);
78   
79   return dyn_cast<GlobalVariable>(C->stripPointerCasts());
80 }
81
82
83
84 //===----------------------------------------------------------------------===//
85 // Simple Descriptor Constructors and other Methods
86 //===----------------------------------------------------------------------===//
87
88 DIAnchor::DIAnchor(GlobalVariable *GV)
89   : DIDescriptor(GV, dwarf::DW_TAG_anchor) {}
90 DIEnumerator::DIEnumerator(GlobalVariable *GV)
91   : DIDescriptor(GV, dwarf::DW_TAG_enumerator) {}
92 DISubrange::DISubrange(GlobalVariable *GV)
93   : DIDescriptor(GV, dwarf::DW_TAG_subrange_type) {}
94 DICompileUnit::DICompileUnit(GlobalVariable *GV)
95   : DIDescriptor(GV, dwarf::DW_TAG_compile_unit) {}
96 DIBasicType::DIBasicType(GlobalVariable *GV)
97   : DIType(GV, dwarf::DW_TAG_base_type) {}
98 DISubprogram::DISubprogram(GlobalVariable *GV)
99   : DIGlobal(GV, dwarf::DW_TAG_subprogram) {}
100 DIGlobalVariable::DIGlobalVariable(GlobalVariable *GV)
101   : DIGlobal(GV, dwarf::DW_TAG_variable) {}
102 DIBlock::DIBlock(GlobalVariable *GV)
103   : DIDescriptor(GV, dwarf::DW_TAG_lexical_block) {}
104 // needed by DIVariable::getType()
105 DIType::DIType(GlobalVariable *gv) : DIDescriptor(gv) {
106   if (!gv) return;
107   unsigned tag = getTag();
108   if (tag != dwarf::DW_TAG_base_type && !DIDerivedType::isDerivedType(tag) &&
109       !DICompositeType::isCompositeType(tag))
110     GV = 0;
111 }
112
113 /// isDerivedType - Return true if the specified tag is legal for
114 /// DIDerivedType.
115 bool DIType::isDerivedType(unsigned Tag) {
116   switch (Tag) {
117   case dwarf::DW_TAG_typedef:
118   case dwarf::DW_TAG_pointer_type:
119   case dwarf::DW_TAG_reference_type:
120   case dwarf::DW_TAG_const_type:
121   case dwarf::DW_TAG_volatile_type:
122   case dwarf::DW_TAG_restrict_type:
123   case dwarf::DW_TAG_member:
124   case dwarf::DW_TAG_inheritance:
125     return true;
126   default:
127     // FIXME: Even though it doesn't make sense, CompositeTypes are current
128     // modelled as DerivedTypes, this should return true for them as well.
129     return false;
130   }
131 }
132
133 DIDerivedType::DIDerivedType(GlobalVariable *GV) : DIType(GV, true, true) {
134   if (GV && !isDerivedType(getTag()))
135     GV = 0;
136 }
137
138 /// isCompositeType - Return true if the specified tag is legal for
139 /// DICompositeType.
140 bool DIType::isCompositeType(unsigned TAG) {
141   switch (TAG) {
142   case dwarf::DW_TAG_array_type:
143   case dwarf::DW_TAG_structure_type:
144   case dwarf::DW_TAG_union_type:
145   case dwarf::DW_TAG_enumeration_type:
146   case dwarf::DW_TAG_vector_type:
147   case dwarf::DW_TAG_subroutine_type:
148     return true;
149   default:
150     return false;
151   }
152 }
153
154 DICompositeType::DICompositeType(GlobalVariable *GV)
155   : DIDerivedType(GV, true, true) {
156   if (GV && !isCompositeType(getTag()))
157     GV = 0;
158 }
159
160 /// isVariable - Return true if the specified tag is legal for DIVariable.
161 bool DIVariable::isVariable(unsigned Tag) {
162   switch (Tag) {
163   case dwarf::DW_TAG_auto_variable:
164   case dwarf::DW_TAG_arg_variable:
165   case dwarf::DW_TAG_return_variable:
166     return true;
167   default:
168     return false;
169   }
170 }
171
172 DIVariable::DIVariable(GlobalVariable *gv) : DIDescriptor(gv) {
173   if (gv && !isVariable(getTag()))
174     GV = 0;
175 }
176
177 unsigned DIArray::getNumElements() const {
178   assert (GV && "Invalid DIArray");
179   Constant *C = GV->getInitializer();
180   assert (C && "Invalid DIArray initializer");
181   return C->getNumOperands();
182 }
183
184 /// Verify - Verify that a compile unit is well formed.
185 bool DICompileUnit::Verify() const {
186   if (isNull()) 
187     return false;
188   if (getFilename().empty()) 
189     return false;
190   // It is possible that directory and produce string is empty.
191   return true;
192 }
193
194 /// Verify - Verify that a type descriptor is well formed.
195 bool DIType::Verify() const {
196   if (isNull()) 
197     return false;
198   if (getContext().isNull()) 
199     return false;
200
201   DICompileUnit CU = getCompileUnit();
202   if (!CU.isNull() && !CU.Verify()) 
203     return false;
204   return true;
205 }
206
207 /// Verify - Verify that a composite type descriptor is well formed.
208 bool DICompositeType::Verify() const {
209   if (isNull()) 
210     return false;
211   if (getContext().isNull()) 
212     return false;
213
214   DICompileUnit CU = getCompileUnit();
215   if (!CU.isNull() && !CU.Verify()) 
216     return false;
217   return true;
218 }
219
220 /// Verify - Verify that a subprogram descriptor is well formed.
221 bool DISubprogram::Verify() const {
222   if (isNull())
223     return false;
224   
225   if (getContext().isNull())
226     return false;
227
228   DICompileUnit CU = getCompileUnit();
229   if (!CU.Verify()) 
230     return false;
231
232   DICompositeType Ty = getType();
233   if (!Ty.isNull() && !Ty.Verify())
234     return false;
235   return true;
236 }
237
238 /// Verify - Verify that a global variable descriptor is well formed.
239 bool DIGlobalVariable::Verify() const {
240   if (isNull())
241     return false;
242   
243   if (getContext().isNull())
244     return false;
245
246   DICompileUnit CU = getCompileUnit();
247   if (!CU.Verify()) 
248     return false;
249
250   DIType Ty = getType();
251   if (!Ty.Verify())
252     return false;
253
254   if (!getGlobal())
255     return false;
256
257   return true;
258 }
259
260 /// Verify - Verify that a variable descriptor is well formed.
261 bool DIVariable::Verify() const {
262   if (isNull())
263     return false;
264   
265   if (getContext().isNull())
266     return false;
267
268   DIType Ty = getType();
269   if (!Ty.Verify())
270     return false;
271
272
273   return true;
274 }
275
276 /// getOriginalTypeSize - If this type is derived from a base type then
277 /// return base type size.
278 uint64_t DIDerivedType::getOriginalTypeSize() const {
279   if (getTag() != dwarf::DW_TAG_member)
280     return getSizeInBits();
281   DIType BT = getTypeDerivedFrom();
282   if (BT.getTag() != dwarf::DW_TAG_base_type)
283     return getSizeInBits();
284   return BT.getSizeInBits();
285 }
286
287 //===----------------------------------------------------------------------===//
288 // DIFactory: Basic Helpers
289 //===----------------------------------------------------------------------===//
290
291 DIFactory::DIFactory(Module &m) : M(m) {
292   StopPointFn = FuncStartFn = RegionStartFn = RegionEndFn = DeclareFn = 0;
293   EmptyStructPtr = PointerType::getUnqual(StructType::get(NULL, NULL));
294 }
295
296 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
297 /// This is only valid when the descriptor is non-null.
298 Constant *DIFactory::getCastToEmpty(DIDescriptor D) {
299   if (D.isNull()) return Constant::getNullValue(EmptyStructPtr);
300   return ConstantExpr::getBitCast(D.getGV(), EmptyStructPtr);
301 }
302
303 Constant *DIFactory::GetTagConstant(unsigned TAG) {
304   assert((TAG & LLVMDebugVersionMask) == 0 &&
305          "Tag too large for debug encoding!");
306   return ConstantInt::get(Type::Int32Ty, TAG | LLVMDebugVersion);
307 }
308
309 Constant *DIFactory::GetStringConstant(const std::string &String) {
310   // Check string cache for previous edition.
311   Constant *&Slot = StringCache[String];
312   
313   // Return Constant if previously defined.
314   if (Slot) return Slot;
315   
316   const PointerType *DestTy = PointerType::getUnqual(Type::Int8Ty);
317   
318   // If empty string then use a sbyte* null instead.
319   if (String.empty())
320     return Slot = ConstantPointerNull::get(DestTy);
321
322   // Construct string as an llvm constant.
323   Constant *ConstStr = ConstantArray::get(String);
324     
325   // Otherwise create and return a new string global.
326   GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
327                                              GlobalVariable::InternalLinkage,
328                                              ConstStr, ".str", &M);
329   StrGV->setSection("llvm.metadata");
330   return Slot = ConstantExpr::getBitCast(StrGV, DestTy);
331 }
332
333 /// GetOrCreateAnchor - Look up an anchor for the specified tag and name.  If it
334 /// already exists, return it.  If not, create a new one and return it.
335 DIAnchor DIFactory::GetOrCreateAnchor(unsigned TAG, const char *Name) {
336   const Type *EltTy = StructType::get(Type::Int32Ty, Type::Int32Ty, NULL);
337   
338   // Otherwise, create the global or return it if already in the module.
339   Constant *C = M.getOrInsertGlobal(Name, EltTy);
340   assert(isa<GlobalVariable>(C) && "Incorrectly typed anchor?");
341   GlobalVariable *GV = cast<GlobalVariable>(C);
342   
343   // If it has an initializer, it is already in the module.
344   if (GV->hasInitializer()) 
345     return SubProgramAnchor = DIAnchor(GV);
346   
347   GV->setLinkage(GlobalValue::LinkOnceLinkage);
348   GV->setSection("llvm.metadata");
349   GV->setConstant(true);
350   M.addTypeName("llvm.dbg.anchor.type", EltTy);
351   
352   // Otherwise, set the initializer.
353   Constant *Elts[] = {
354     GetTagConstant(dwarf::DW_TAG_anchor),
355     ConstantInt::get(Type::Int32Ty, TAG)
356   };
357   
358   GV->setInitializer(ConstantStruct::get(Elts, 2));
359   return DIAnchor(GV);
360 }
361
362
363
364 //===----------------------------------------------------------------------===//
365 // DIFactory: Primary Constructors
366 //===----------------------------------------------------------------------===//
367
368 /// GetOrCreateCompileUnitAnchor - Return the anchor for compile units,
369 /// creating a new one if there isn't already one in the module.
370 DIAnchor DIFactory::GetOrCreateCompileUnitAnchor() {
371   // If we already created one, just return it.
372   if (!CompileUnitAnchor.isNull())
373     return CompileUnitAnchor;
374   return CompileUnitAnchor = GetOrCreateAnchor(dwarf::DW_TAG_compile_unit,
375                                                "llvm.dbg.compile_units");
376 }
377
378 /// GetOrCreateSubprogramAnchor - Return the anchor for subprograms,
379 /// creating a new one if there isn't already one in the module.
380 DIAnchor DIFactory::GetOrCreateSubprogramAnchor() {
381   // If we already created one, just return it.
382   if (!SubProgramAnchor.isNull())
383     return SubProgramAnchor;
384   return SubProgramAnchor = GetOrCreateAnchor(dwarf::DW_TAG_subprogram,
385                                               "llvm.dbg.subprograms");
386 }
387
388 /// GetOrCreateGlobalVariableAnchor - Return the anchor for globals,
389 /// creating a new one if there isn't already one in the module.
390 DIAnchor DIFactory::GetOrCreateGlobalVariableAnchor() {
391   // If we already created one, just return it.
392   if (!GlobalVariableAnchor.isNull())
393     return GlobalVariableAnchor;
394   return GlobalVariableAnchor = GetOrCreateAnchor(dwarf::DW_TAG_variable,
395                                                   "llvm.dbg.global_variables");
396 }
397
398 /// GetOrCreateArray - Create an descriptor for an array of descriptors. 
399 /// This implicitly uniques the arrays created.
400 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
401   SmallVector<Constant*, 16> Elts;
402   
403   for (unsigned i = 0; i != NumTys; ++i)
404     Elts.push_back(getCastToEmpty(Tys[i]));
405   
406   Constant *Init = ConstantArray::get(ArrayType::get(EmptyStructPtr,
407                                                      Elts.size()),
408                                       &Elts[0], Elts.size());
409   // If we already have this array, just return the uniqued version.
410   DIDescriptor &Entry = SimpleConstantCache[Init];
411   if (!Entry.isNull()) return DIArray(Entry.getGV());
412   
413   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
414                                           GlobalValue::InternalLinkage,
415                                           Init, "llvm.dbg.array", &M);
416   GV->setSection("llvm.metadata");
417   Entry = DIDescriptor(GV);
418   return DIArray(GV);
419 }
420
421 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
422 /// implicitly uniques the values returned.
423 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
424   Constant *Elts[] = {
425     GetTagConstant(dwarf::DW_TAG_subrange_type),
426     ConstantInt::get(Type::Int64Ty, Lo),
427     ConstantInt::get(Type::Int64Ty, Hi)
428   };
429   
430   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
431
432   // If we already have this range, just return the uniqued version.
433   DIDescriptor &Entry = SimpleConstantCache[Init];
434   if (!Entry.isNull()) return DISubrange(Entry.getGV());
435   
436   M.addTypeName("llvm.dbg.subrange.type", Init->getType());
437
438   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
439                                           GlobalValue::InternalLinkage,
440                                           Init, "llvm.dbg.subrange", &M);
441   GV->setSection("llvm.metadata");
442   Entry = DIDescriptor(GV);
443   return DISubrange(GV);
444 }
445
446
447
448 /// CreateCompileUnit - Create a new descriptor for the specified compile
449 /// unit.  Note that this does not unique compile units within the module.
450 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
451                                            const std::string &Filename,
452                                            const std::string &Directory,
453                                            const std::string &Producer,
454                                            bool isMain,
455                                            bool isOptimized,
456                                            const char *Flags) {
457   Constant *Elts[] = {
458     GetTagConstant(dwarf::DW_TAG_compile_unit),
459     getCastToEmpty(GetOrCreateCompileUnitAnchor()),
460     ConstantInt::get(Type::Int32Ty, LangID),
461     GetStringConstant(Filename),
462     GetStringConstant(Directory),
463     GetStringConstant(Producer),
464     ConstantInt::get(Type::Int1Ty, isMain),
465     ConstantInt::get(Type::Int1Ty, isOptimized),
466     GetStringConstant(Flags)
467   };
468   
469   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
470   
471   M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
472   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
473                                           GlobalValue::InternalLinkage,
474                                           Init, "llvm.dbg.compile_unit", &M);
475   GV->setSection("llvm.metadata");
476   return DICompileUnit(GV);
477 }
478
479 /// CreateEnumerator - Create a single enumerator value.
480 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
481   Constant *Elts[] = {
482     GetTagConstant(dwarf::DW_TAG_enumerator),
483     GetStringConstant(Name),
484     ConstantInt::get(Type::Int64Ty, Val)
485   };
486   
487   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
488   
489   M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
490   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
491                                           GlobalValue::InternalLinkage,
492                                           Init, "llvm.dbg.enumerator", &M);
493   GV->setSection("llvm.metadata");
494   return DIEnumerator(GV);
495 }
496
497
498 /// CreateBasicType - Create a basic type like int, float, etc.
499 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
500                                       const std::string &Name,
501                                        DICompileUnit CompileUnit,
502                                        unsigned LineNumber,
503                                        uint64_t SizeInBits,
504                                        uint64_t AlignInBits,
505                                        uint64_t OffsetInBits, unsigned Flags,
506                                        unsigned Encoding) {
507   Constant *Elts[] = {
508     GetTagConstant(dwarf::DW_TAG_base_type),
509     getCastToEmpty(Context),
510     GetStringConstant(Name),
511     getCastToEmpty(CompileUnit),
512     ConstantInt::get(Type::Int32Ty, LineNumber),
513     ConstantInt::get(Type::Int64Ty, SizeInBits),
514     ConstantInt::get(Type::Int64Ty, AlignInBits),
515     ConstantInt::get(Type::Int64Ty, OffsetInBits),
516     ConstantInt::get(Type::Int32Ty, Flags),
517     ConstantInt::get(Type::Int32Ty, Encoding)
518   };
519   
520   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
521   
522   M.addTypeName("llvm.dbg.basictype.type", Init->getType());
523   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
524                                           GlobalValue::InternalLinkage,
525                                           Init, "llvm.dbg.basictype", &M);
526   GV->setSection("llvm.metadata");
527   return DIBasicType(GV);
528 }
529
530 /// CreateDerivedType - Create a derived type like const qualified type,
531 /// pointer, typedef, etc.
532 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
533                                            DIDescriptor Context,
534                                            const std::string &Name,
535                                            DICompileUnit CompileUnit,
536                                            unsigned LineNumber,
537                                            uint64_t SizeInBits,
538                                            uint64_t AlignInBits,
539                                            uint64_t OffsetInBits,
540                                            unsigned Flags,
541                                            DIType DerivedFrom) {
542   Constant *Elts[] = {
543     GetTagConstant(Tag),
544     getCastToEmpty(Context),
545     GetStringConstant(Name),
546     getCastToEmpty(CompileUnit),
547     ConstantInt::get(Type::Int32Ty, LineNumber),
548     ConstantInt::get(Type::Int64Ty, SizeInBits),
549     ConstantInt::get(Type::Int64Ty, AlignInBits),
550     ConstantInt::get(Type::Int64Ty, OffsetInBits),
551     ConstantInt::get(Type::Int32Ty, Flags),
552     getCastToEmpty(DerivedFrom)
553   };
554   
555   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
556   
557   M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
558   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
559                                           GlobalValue::InternalLinkage,
560                                           Init, "llvm.dbg.derivedtype", &M);
561   GV->setSection("llvm.metadata");
562   return DIDerivedType(GV);
563 }
564
565 /// CreateCompositeType - Create a composite type like array, struct, etc.
566 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
567                                                DIDescriptor Context,
568                                                const std::string &Name,
569                                                DICompileUnit CompileUnit,
570                                                unsigned LineNumber,
571                                                uint64_t SizeInBits,
572                                                uint64_t AlignInBits,
573                                                uint64_t OffsetInBits,
574                                                unsigned Flags,
575                                                DIType DerivedFrom,
576                                                DIArray Elements) {
577
578   Constant *Elts[] = {
579     GetTagConstant(Tag),
580     getCastToEmpty(Context),
581     GetStringConstant(Name),
582     getCastToEmpty(CompileUnit),
583     ConstantInt::get(Type::Int32Ty, LineNumber),
584     ConstantInt::get(Type::Int64Ty, SizeInBits),
585     ConstantInt::get(Type::Int64Ty, AlignInBits),
586     ConstantInt::get(Type::Int64Ty, OffsetInBits),
587     ConstantInt::get(Type::Int32Ty, Flags),
588     getCastToEmpty(DerivedFrom),
589     getCastToEmpty(Elements)
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   /// Finds the dbg.declare intrinsic corresponding to this value if any.
835   /// It looks through pointer casts too.
836   const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts)
837   {
838     if (stripCasts) {
839       V = V->stripPointerCasts();
840       // Look for the bitcast.
841       for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
842             I != E; ++I) {
843         if (isa<BitCastInst>(I))
844           return findDbgDeclare(*I, false);
845       }
846       return 0;
847     }
848
849     // Find dbg.declare among uses of the instruction.
850     for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
851           I != E; ++I) {
852       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
853         return DDI;
854     }
855     return 0;
856   }
857 }
858
859 /// dump - print compile unit.
860 void DICompileUnit::dump() const {
861   cerr << " [" << dwarf::LanguageString(getLanguage()) << "] ";
862   cerr << " [" << getDirectory() << "/" << getFilename() << " ]";
863 }
864
865 /// dump - print type.
866 void DIType::dump() const {
867   if (isNull()) return;
868   if (!getName().empty())
869     cerr << " [" << getName() << "] ";
870   unsigned Tag = getTag();
871   cerr << " [" << dwarf::TagString(Tag) << "] ";
872   // TODO : Print context
873   getCompileUnit().dump();
874   cerr << " [" 
875        << getLineNumber() << ", " 
876        << getSizeInBits() << ", "
877        << getAlignInBits() << ", "
878        << getOffsetInBits() 
879        << "] ";
880   if (isPrivate()) 
881     cerr << " [private] ";
882   else if (isProtected())
883     cerr << " [protected] ";
884   if (isForwardDecl())
885     cerr << " [fwd] ";
886
887   if (isBasicType(Tag))
888     DIBasicType(GV).dump();
889   else if (isDerivedType(Tag))
890     DIDerivedType(GV).dump();
891   else if (isCompositeType(Tag))
892     DICompositeType(GV).dump();
893   else {
894     cerr << "Invalid DIType\n";
895     return;
896   }
897   cerr << "\n";
898 }
899
900 /// dump - print basic type.
901 void DIBasicType::dump() const {
902   cerr << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
903
904 }
905
906 /// dump - print derived type.
907 void DIDerivedType::dump() const {
908   cerr << "\n\t Derived From: "; getTypeDerivedFrom().dump();
909 }
910
911 /// dump - print composite type.
912 void DICompositeType::dump() const {
913   DIArray A = getTypeArray();
914   if (A.isNull())
915     return;
916   cerr << " [" << A.getNumElements() << " elements]";
917 }
918
919 /// dump - print global.
920 void DIGlobal::dump() const {
921
922   if (!getName().empty())
923     cerr << " [" << getName() << "] ";
924   unsigned Tag = getTag();
925   cerr << " [" << dwarf::TagString(Tag) << "] ";
926   // TODO : Print context
927   getCompileUnit().dump();
928   cerr << " [" << getLineNumber() << "] ";
929   if (isLocalToUnit())
930     cerr << " [local] ";
931   if (isDefinition())
932     cerr << " [def] ";
933
934   if (isGlobalVariable(Tag))
935     DIGlobalVariable(GV).dump();
936
937   cerr << "\n";
938 }
939
940 /// dump - print subprogram.
941 void DISubprogram::dump() const {
942   DIGlobal::dump();
943 }
944
945 /// dump - print global variable.
946 void DIGlobalVariable::dump() const {
947   cerr << " ["; getGlobal()->dump(); cerr << "] ";
948 }
949
950 /// dump - print variable.
951 void DIVariable::dump() const {
952   if (!getName().empty())
953     cerr << " [" << getName() << "] ";
954   getCompileUnit().dump();
955   cerr << " [" << getLineNumber() << "] ";
956   getType().dump();
957   cerr << "\n";
958 }