Add dump() routines to help debug debug info :)
[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
277
278 //===----------------------------------------------------------------------===//
279 // DIFactory: Basic Helpers
280 //===----------------------------------------------------------------------===//
281
282 DIFactory::DIFactory(Module &m) : M(m) {
283   StopPointFn = FuncStartFn = RegionStartFn = RegionEndFn = DeclareFn = 0;
284   EmptyStructPtr = PointerType::getUnqual(StructType::get(NULL, NULL));
285 }
286
287 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
288 /// This is only valid when the descriptor is non-null.
289 Constant *DIFactory::getCastToEmpty(DIDescriptor D) {
290   if (D.isNull()) return Constant::getNullValue(EmptyStructPtr);
291   return ConstantExpr::getBitCast(D.getGV(), EmptyStructPtr);
292 }
293
294 Constant *DIFactory::GetTagConstant(unsigned TAG) {
295   assert((TAG & LLVMDebugVersionMask) == 0 &&
296          "Tag too large for debug encoding!");
297   return ConstantInt::get(Type::Int32Ty, TAG | LLVMDebugVersion);
298 }
299
300 Constant *DIFactory::GetStringConstant(const std::string &String) {
301   // Check string cache for previous edition.
302   Constant *&Slot = StringCache[String];
303   
304   // Return Constant if previously defined.
305   if (Slot) return Slot;
306   
307   const PointerType *DestTy = PointerType::getUnqual(Type::Int8Ty);
308   
309   // If empty string then use a sbyte* null instead.
310   if (String.empty())
311     return Slot = ConstantPointerNull::get(DestTy);
312
313   // Construct string as an llvm constant.
314   Constant *ConstStr = ConstantArray::get(String);
315     
316   // Otherwise create and return a new string global.
317   GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
318                                              GlobalVariable::InternalLinkage,
319                                              ConstStr, ".str", &M);
320   StrGV->setSection("llvm.metadata");
321   return Slot = ConstantExpr::getBitCast(StrGV, DestTy);
322 }
323
324 /// GetOrCreateAnchor - Look up an anchor for the specified tag and name.  If it
325 /// already exists, return it.  If not, create a new one and return it.
326 DIAnchor DIFactory::GetOrCreateAnchor(unsigned TAG, const char *Name) {
327   const Type *EltTy = StructType::get(Type::Int32Ty, Type::Int32Ty, NULL);
328   
329   // Otherwise, create the global or return it if already in the module.
330   Constant *C = M.getOrInsertGlobal(Name, EltTy);
331   assert(isa<GlobalVariable>(C) && "Incorrectly typed anchor?");
332   GlobalVariable *GV = cast<GlobalVariable>(C);
333   
334   // If it has an initializer, it is already in the module.
335   if (GV->hasInitializer()) 
336     return SubProgramAnchor = DIAnchor(GV);
337   
338   GV->setLinkage(GlobalValue::LinkOnceLinkage);
339   GV->setSection("llvm.metadata");
340   GV->setConstant(true);
341   M.addTypeName("llvm.dbg.anchor.type", EltTy);
342   
343   // Otherwise, set the initializer.
344   Constant *Elts[] = {
345     GetTagConstant(dwarf::DW_TAG_anchor),
346     ConstantInt::get(Type::Int32Ty, TAG)
347   };
348   
349   GV->setInitializer(ConstantStruct::get(Elts, 2));
350   return DIAnchor(GV);
351 }
352
353
354
355 //===----------------------------------------------------------------------===//
356 // DIFactory: Primary Constructors
357 //===----------------------------------------------------------------------===//
358
359 /// GetOrCreateCompileUnitAnchor - Return the anchor for compile units,
360 /// creating a new one if there isn't already one in the module.
361 DIAnchor DIFactory::GetOrCreateCompileUnitAnchor() {
362   // If we already created one, just return it.
363   if (!CompileUnitAnchor.isNull())
364     return CompileUnitAnchor;
365   return CompileUnitAnchor = GetOrCreateAnchor(dwarf::DW_TAG_compile_unit,
366                                                "llvm.dbg.compile_units");
367 }
368
369 /// GetOrCreateSubprogramAnchor - Return the anchor for subprograms,
370 /// creating a new one if there isn't already one in the module.
371 DIAnchor DIFactory::GetOrCreateSubprogramAnchor() {
372   // If we already created one, just return it.
373   if (!SubProgramAnchor.isNull())
374     return SubProgramAnchor;
375   return SubProgramAnchor = GetOrCreateAnchor(dwarf::DW_TAG_subprogram,
376                                               "llvm.dbg.subprograms");
377 }
378
379 /// GetOrCreateGlobalVariableAnchor - Return the anchor for globals,
380 /// creating a new one if there isn't already one in the module.
381 DIAnchor DIFactory::GetOrCreateGlobalVariableAnchor() {
382   // If we already created one, just return it.
383   if (!GlobalVariableAnchor.isNull())
384     return GlobalVariableAnchor;
385   return GlobalVariableAnchor = GetOrCreateAnchor(dwarf::DW_TAG_variable,
386                                                   "llvm.dbg.global_variables");
387 }
388
389 /// GetOrCreateArray - Create an descriptor for an array of descriptors. 
390 /// This implicitly uniques the arrays created.
391 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
392   SmallVector<Constant*, 16> Elts;
393   
394   for (unsigned i = 0; i != NumTys; ++i)
395     Elts.push_back(getCastToEmpty(Tys[i]));
396   
397   Constant *Init = ConstantArray::get(ArrayType::get(EmptyStructPtr,
398                                                      Elts.size()),
399                                       &Elts[0], Elts.size());
400   // If we already have this array, just return the uniqued version.
401   DIDescriptor &Entry = SimpleConstantCache[Init];
402   if (!Entry.isNull()) return DIArray(Entry.getGV());
403   
404   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
405                                           GlobalValue::InternalLinkage,
406                                           Init, "llvm.dbg.array", &M);
407   GV->setSection("llvm.metadata");
408   Entry = DIDescriptor(GV);
409   return DIArray(GV);
410 }
411
412 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
413 /// implicitly uniques the values returned.
414 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
415   Constant *Elts[] = {
416     GetTagConstant(dwarf::DW_TAG_subrange_type),
417     ConstantInt::get(Type::Int64Ty, Lo),
418     ConstantInt::get(Type::Int64Ty, Hi)
419   };
420   
421   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
422
423   // If we already have this range, just return the uniqued version.
424   DIDescriptor &Entry = SimpleConstantCache[Init];
425   if (!Entry.isNull()) return DISubrange(Entry.getGV());
426   
427   M.addTypeName("llvm.dbg.subrange.type", Init->getType());
428
429   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
430                                           GlobalValue::InternalLinkage,
431                                           Init, "llvm.dbg.subrange", &M);
432   GV->setSection("llvm.metadata");
433   Entry = DIDescriptor(GV);
434   return DISubrange(GV);
435 }
436
437
438
439 /// CreateCompileUnit - Create a new descriptor for the specified compile
440 /// unit.  Note that this does not unique compile units within the module.
441 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
442                                            const std::string &Filename,
443                                            const std::string &Directory,
444                                            const std::string &Producer,
445                                            bool isOptimized,
446                                            const char *Flags) {
447   Constant *Elts[] = {
448     GetTagConstant(dwarf::DW_TAG_compile_unit),
449     getCastToEmpty(GetOrCreateCompileUnitAnchor()),
450     ConstantInt::get(Type::Int32Ty, LangID),
451     GetStringConstant(Filename),
452     GetStringConstant(Directory),
453     GetStringConstant(Producer),
454     ConstantInt::get(Type::Int1Ty, isOptimized),
455     GetStringConstant(Flags)
456   };
457   
458   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
459   
460   M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
461   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
462                                           GlobalValue::InternalLinkage,
463                                           Init, "llvm.dbg.compile_unit", &M);
464   GV->setSection("llvm.metadata");
465   return DICompileUnit(GV);
466 }
467
468 /// CreateEnumerator - Create a single enumerator value.
469 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
470   Constant *Elts[] = {
471     GetTagConstant(dwarf::DW_TAG_enumerator),
472     GetStringConstant(Name),
473     ConstantInt::get(Type::Int64Ty, Val)
474   };
475   
476   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
477   
478   M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
479   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
480                                           GlobalValue::InternalLinkage,
481                                           Init, "llvm.dbg.enumerator", &M);
482   GV->setSection("llvm.metadata");
483   return DIEnumerator(GV);
484 }
485
486
487 /// CreateBasicType - Create a basic type like int, float, etc.
488 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
489                                       const std::string &Name,
490                                        DICompileUnit CompileUnit,
491                                        unsigned LineNumber,
492                                        uint64_t SizeInBits,
493                                        uint64_t AlignInBits,
494                                        uint64_t OffsetInBits, unsigned Flags,
495                                        unsigned Encoding,
496                                        const std::string *FileName,
497                                        const std::string *Directory) {
498   Constant *Elts[] = {
499     GetTagConstant(dwarf::DW_TAG_base_type),
500     getCastToEmpty(Context),
501     GetStringConstant(Name),
502     getCastToEmpty(CompileUnit),
503     ConstantInt::get(Type::Int32Ty, LineNumber),
504     ConstantInt::get(Type::Int64Ty, SizeInBits),
505     ConstantInt::get(Type::Int64Ty, AlignInBits),
506     ConstantInt::get(Type::Int64Ty, OffsetInBits),
507     ConstantInt::get(Type::Int32Ty, Flags),
508     ConstantInt::get(Type::Int32Ty, Encoding),
509     GetStringConstant(FileName ? FileName->c_str() : ""),
510     GetStringConstant(Directory ? Directory->c_str() : "")
511   };
512   
513   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
514   
515   M.addTypeName("llvm.dbg.basictype.type", Init->getType());
516   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
517                                           GlobalValue::InternalLinkage,
518                                           Init, "llvm.dbg.basictype", &M);
519   GV->setSection("llvm.metadata");
520   return DIBasicType(GV);
521 }
522
523 /// CreateDerivedType - Create a derived type like const qualified type,
524 /// pointer, typedef, etc.
525 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
526                                            DIDescriptor Context,
527                                            const std::string &Name,
528                                            DICompileUnit CompileUnit,
529                                            unsigned LineNumber,
530                                            uint64_t SizeInBits,
531                                            uint64_t AlignInBits,
532                                            uint64_t OffsetInBits,
533                                            unsigned Flags,
534                                            DIType DerivedFrom,
535                                            const std::string *FileName,
536                                            const std::string *Directory) {
537   Constant *Elts[] = {
538     GetTagConstant(Tag),
539     getCastToEmpty(Context),
540     GetStringConstant(Name),
541     getCastToEmpty(CompileUnit),
542     ConstantInt::get(Type::Int32Ty, LineNumber),
543     ConstantInt::get(Type::Int64Ty, SizeInBits),
544     ConstantInt::get(Type::Int64Ty, AlignInBits),
545     ConstantInt::get(Type::Int64Ty, OffsetInBits),
546     ConstantInt::get(Type::Int32Ty, Flags),
547     getCastToEmpty(DerivedFrom),
548     GetStringConstant(FileName ? FileName->c_str() : ""),
549     GetStringConstant(Directory ? Directory->c_str() : "")
550   };
551   
552   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
553   
554   M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
555   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
556                                           GlobalValue::InternalLinkage,
557                                           Init, "llvm.dbg.derivedtype", &M);
558   GV->setSection("llvm.metadata");
559   return DIDerivedType(GV);
560 }
561
562 /// CreateCompositeType - Create a composite type like array, struct, etc.
563 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
564                                                DIDescriptor Context,
565                                                const std::string &Name,
566                                                DICompileUnit CompileUnit,
567                                                unsigned LineNumber,
568                                                uint64_t SizeInBits,
569                                                uint64_t AlignInBits,
570                                                uint64_t OffsetInBits,
571                                                unsigned Flags,
572                                                DIType DerivedFrom,
573                                                DIArray Elements,
574                                                const std::string *FileName,
575                                                const std::string *Directory) {
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     GetStringConstant(FileName ? FileName->c_str() : ""),
590     GetStringConstant(Directory ? Directory->c_str() : "")
591   };
592   
593   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
594   
595   M.addTypeName("llvm.dbg.composite.type", Init->getType());
596   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
597                                           GlobalValue::InternalLinkage,
598                                           Init, "llvm.dbg.composite", &M);
599   GV->setSection("llvm.metadata");
600   return DICompositeType(GV);
601 }
602
603
604 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
605 /// See comments in DISubprogram for descriptions of these fields.  This
606 /// method does not unique the generated descriptors.
607 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context, 
608                                          const std::string &Name,
609                                          const std::string &DisplayName,
610                                          const std::string &LinkageName,
611                                          DICompileUnit CompileUnit,
612                                          unsigned LineNo, DIType Type,
613                                          bool isLocalToUnit,
614                                          bool isDefinition,
615                                          const std::string *FileName,
616                                          const std::string *Directory) {
617
618   Constant *Elts[] = {
619     GetTagConstant(dwarf::DW_TAG_subprogram),
620     getCastToEmpty(GetOrCreateSubprogramAnchor()),
621     getCastToEmpty(Context),
622     GetStringConstant(Name),
623     GetStringConstant(DisplayName),
624     GetStringConstant(LinkageName),
625     getCastToEmpty(CompileUnit),
626     ConstantInt::get(Type::Int32Ty, LineNo),
627     getCastToEmpty(Type),
628     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
629     ConstantInt::get(Type::Int1Ty, isDefinition),
630     GetStringConstant(FileName ? FileName->c_str() : ""),
631     GetStringConstant(Directory ? Directory->c_str() : "")
632   };
633   
634   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
635   
636   M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
637   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
638                                           GlobalValue::InternalLinkage,
639                                           Init, "llvm.dbg.subprogram", &M);
640   GV->setSection("llvm.metadata");
641   return DISubprogram(GV);
642 }
643
644 /// CreateGlobalVariable - Create a new descriptor for the specified global.
645 DIGlobalVariable
646 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
647                                 const std::string &DisplayName,
648                                 const std::string &LinkageName,
649                                 DICompileUnit CompileUnit,
650                                 unsigned LineNo, DIType Type,bool isLocalToUnit,
651                                 bool isDefinition, llvm::GlobalVariable *Val,
652                                 const std::string *FileName,
653                                 const std::string *Directory) {
654   Constant *Elts[] = {
655     GetTagConstant(dwarf::DW_TAG_variable),
656     getCastToEmpty(GetOrCreateGlobalVariableAnchor()),
657     getCastToEmpty(Context),
658     GetStringConstant(Name),
659     GetStringConstant(DisplayName),
660     GetStringConstant(LinkageName),
661     getCastToEmpty(CompileUnit),
662     ConstantInt::get(Type::Int32Ty, LineNo),
663     getCastToEmpty(Type),
664     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
665     ConstantInt::get(Type::Int1Ty, isDefinition),
666     ConstantExpr::getBitCast(Val, EmptyStructPtr),
667     GetStringConstant(FileName ? FileName->c_str() : ""),
668     GetStringConstant(Directory ? Directory->c_str() : "")
669   };
670   
671   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
672   
673   M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
674   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
675                                           GlobalValue::InternalLinkage,
676                                           Init, "llvm.dbg.global_variable", &M);
677   GV->setSection("llvm.metadata");
678   return DIGlobalVariable(GV);
679 }
680
681
682 /// CreateVariable - Create a new descriptor for the specified variable.
683 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
684                                      const std::string &Name,
685                                      DICompileUnit CompileUnit, unsigned LineNo,
686                                      DIType Type,
687                                      const std::string *FileName,
688                                      const std::string *Directory) {
689
690   
691   Constant *Elts[] = {
692     GetTagConstant(Tag),
693     getCastToEmpty(Context),
694     GetStringConstant(Name),
695     getCastToEmpty(CompileUnit),
696     ConstantInt::get(Type::Int32Ty, LineNo),
697     getCastToEmpty(Type),
698     GetStringConstant(FileName ? FileName->c_str() : ""),
699     GetStringConstant(Directory ? Directory->c_str() : "")
700   };
701   
702   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
703   
704   M.addTypeName("llvm.dbg.variable.type", Init->getType());
705   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
706                                           GlobalValue::InternalLinkage,
707                                           Init, "llvm.dbg.variable", &M);
708   GV->setSection("llvm.metadata");
709   return DIVariable(GV);
710 }
711
712
713 /// CreateBlock - This creates a descriptor for a lexical block with the
714 /// specified parent context.
715 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
716   Constant *Elts[] = {
717     GetTagConstant(dwarf::DW_TAG_lexical_block),
718     getCastToEmpty(Context)
719   };
720   
721   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
722   
723   M.addTypeName("llvm.dbg.block.type", Init->getType());
724   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
725                                           GlobalValue::InternalLinkage,
726                                           Init, "llvm.dbg.block", &M);
727   GV->setSection("llvm.metadata");
728   return DIBlock(GV);
729 }
730
731
732 //===----------------------------------------------------------------------===//
733 // DIFactory: Routines for inserting code into a function
734 //===----------------------------------------------------------------------===//
735
736 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
737 /// inserting it at the end of the specified basic block.
738 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
739                                 unsigned ColNo, BasicBlock *BB) {
740   
741   // Lazily construct llvm.dbg.stoppoint function.
742   if (!StopPointFn)
743     StopPointFn = llvm::Intrinsic::getDeclaration(&M, 
744                                               llvm::Intrinsic::dbg_stoppoint);
745   
746   // Invoke llvm.dbg.stoppoint
747   Value *Args[] = {
748     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo),
749     llvm::ConstantInt::get(llvm::Type::Int32Ty, ColNo),
750     getCastToEmpty(CU)
751   };
752   CallInst::Create(StopPointFn, Args, Args+3, "", BB);
753 }
754
755 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
756 /// mark the start of the specified subprogram.
757 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
758   // Lazily construct llvm.dbg.func.start.
759   if (!FuncStartFn)
760     FuncStartFn = llvm::Intrinsic::getDeclaration(&M, 
761                                               llvm::Intrinsic::dbg_func_start);
762   
763   // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
764   CallInst::Create(FuncStartFn, getCastToEmpty(SP), "", BB);
765 }
766
767 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
768 /// mark the start of a region for the specified scoping descriptor.
769 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
770   // Lazily construct llvm.dbg.region.start function.
771   if (!RegionStartFn)
772     RegionStartFn = llvm::Intrinsic::getDeclaration(&M, 
773                                             llvm::Intrinsic::dbg_region_start);
774   // Call llvm.dbg.func.start.
775   CallInst::Create(RegionStartFn, getCastToEmpty(D), "", BB);
776 }
777
778
779 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
780 /// mark the end of a region for the specified scoping descriptor.
781 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
782   // Lazily construct llvm.dbg.region.end function.
783   if (!RegionEndFn)
784     RegionEndFn = llvm::Intrinsic::getDeclaration(&M,
785                                                llvm::Intrinsic::dbg_region_end);
786   
787   CallInst::Create(RegionEndFn, getCastToEmpty(D), "", BB);
788 }
789
790 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
791 void DIFactory::InsertDeclare(llvm::Value *Storage, DIVariable D,
792                               BasicBlock *BB) {
793   // Cast the storage to a {}* for the call to llvm.dbg.declare.
794   Storage = new llvm::BitCastInst(Storage, EmptyStructPtr, "", BB);
795   
796   if (!DeclareFn)
797     DeclareFn = llvm::Intrinsic::getDeclaration(&M,
798                                                 llvm::Intrinsic::dbg_declare);
799   Value *Args[] = { Storage, getCastToEmpty(D) };
800   CallInst::Create(DeclareFn, Args, Args+2, "", BB);
801 }
802
803 namespace llvm {
804   /// Finds the stoppoint coressponding to this instruction, that is the
805   /// stoppoint that dominates this instruction 
806   const DbgStopPointInst *findStopPoint(const Instruction *Inst)
807   {
808     if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
809       return DSI;
810
811     const BasicBlock *BB = Inst->getParent();
812     BasicBlock::const_iterator I = Inst, B;
813     do {
814       B = BB->begin();
815       // A BB consisting only of a terminator can't have a stoppoint.
816       if (I != B) {
817         do {
818           --I;
819           if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
820             return DSI;
821         } while (I != B);
822       }
823       // This BB didn't have a stoppoint: if there is only one
824       // predecessor, look for a stoppoint there.
825       // We could use getIDom(), but that would require dominator info.
826       BB = I->getParent()->getUniquePredecessor();
827       if (BB)
828         I = BB->getTerminator();
829     } while (BB != 0);
830     return 0;
831   }
832
833   /// Finds the stoppoint corresponding to first real (non-debug intrinsic) 
834   /// instruction in this Basic Block, and returns the stoppoint for it.
835   const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB)
836   {
837     for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
838       if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
839         return DSI;
840     }
841     // Fallback to looking for stoppoint of unique predecessor.
842     // Useful if this BB contains no stoppoints, but unique predecessor does.
843     BB = BB->getUniquePredecessor();
844     if (BB)
845       return findStopPoint(BB->getTerminator());
846     return 0;
847   }
848
849   /// Finds the dbg.declare intrinsic corresponding to this value if any.
850   /// It looks through pointer casts too.
851   const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts)
852   {
853     if (stripCasts) {
854       V = V->stripPointerCasts();
855       // Look for the bitcast.
856       for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
857             I != E; ++I) {
858         if (isa<BitCastInst>(I))
859           return findDbgDeclare(*I, false);
860       }
861       return 0;
862     }
863
864     // Find dbg.declare among uses of the instruction.
865     for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
866           I != E; ++I) {
867       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
868         return DDI;
869     }
870     return 0;
871   }
872 }
873
874 /// dump - print compile unit.
875 void DICompileUnit::dump() const {
876   cerr << " [" << dwarf::LanguageString(getLanguage()) << "] ";
877   cerr << " [" << getDirectory() << "/" << getFilename() << " ]";
878 }
879
880 /// dump - print type.
881 void DIType::dump() const {
882   if (isNull()) return;
883   if (!getName().empty())
884     cerr << " [" << getName() << "] ";
885   unsigned Tag = getTag();
886   cerr << " [" << dwarf::TagString(Tag) << "] ";
887   // TODO : Print context
888   getCompileUnit().dump();
889   cerr << " [" 
890        << getLineNumber() << ", " 
891        << getSizeInBits() << ", "
892        << getAlignInBits() << ", "
893        << getOffsetInBits() 
894        << "] ";
895   if (isPrivate()) 
896     cerr << " [private] ";
897   else if (isProtected())
898     cerr << " [protected] ";
899   if (isForwardDecl())
900     cerr << " [fwd] ";
901
902   if (isBasicType(Tag))
903     DIBasicType(GV).dump();
904   else if (isDerivedType(Tag))
905     DIDerivedType(GV).dump();
906   else if (isCompositeType(Tag))
907     DICompositeType(GV).dump();
908   else {
909     cerr << "Invalid DIType\n";
910     return;
911   }
912   cerr << "\n";
913 }
914
915 /// dump - print basic type.
916 void DIBasicType::dump() const {
917   cerr << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
918
919 }
920
921 /// dump - print derived type.
922 void DIDerivedType::dump() const {
923   cerr << "\n\t Derived From: "; getTypeDerivedFrom().dump();
924 }
925
926 /// dump - print composite type.
927 void DICompositeType::dump() const {
928   DIArray A = getTypeArray();
929   if (A.isNull())
930     return;
931   cerr << " [" << A.getNumElements() << " elements]";
932 }
933
934 /// dump - print global.
935 void DIGlobal::dump() const {
936
937   if (!getName().empty())
938     cerr << " [" << getName() << "] ";
939   unsigned Tag = getTag();
940   cerr << " [" << dwarf::TagString(Tag) << "] ";
941   // TODO : Print context
942   getCompileUnit().dump();
943   cerr << " [" << getLineNumber() << "] ";
944   if (isLocalToUnit())
945     cerr << " [local] ";
946   if (isDefinition())
947     cerr << " [def] ";
948
949   if (isGlobalVariable(Tag))
950     DIGlobalVariable(GV).dump();
951
952   cerr << "\n";
953 }
954
955 /// dump - print subprogram.
956 void DISubprogram::dump() const {
957   DIGlobal::dump();
958 }
959
960 /// dump - print global variable.
961 void DIGlobalVariable::dump() const {
962   cerr << " ["; getGlobal()->dump(); cerr << "] ";
963 }
964
965 /// dump - print variable.
966 void DIVariable::dump() const {
967   if (!getName().empty())
968     cerr << " [" << getName() << "] ";
969   getCompileUnit().dump();
970   cerr << " [" << getLineNumber() << "] ";
971   getType().dump();
972   cerr << "\n";
973 }