Add classof() methods so that dwarf writer can decide what DIDescriptor is in its...
[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/Dwarf.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 DIDerivedType::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 DICompositeType::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 /// isSubrange - Return true if the specified tag is legal for DISubrange.
185 bool DISubrange::isSubrange(unsigned Tag) {
186   return Tag == dwarf::DW_TAG_subrange_type;
187 }
188
189 //===----------------------------------------------------------------------===//
190 // DIFactory: Basic Helpers
191 //===----------------------------------------------------------------------===//
192
193 DIFactory::DIFactory(Module &m) : M(m) {
194   StopPointFn = FuncStartFn = RegionStartFn = RegionEndFn = DeclareFn = 0;
195   EmptyStructPtr = PointerType::getUnqual(StructType::get(NULL, NULL));
196 }
197
198 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
199 /// This is only valid when the descriptor is non-null.
200 Constant *DIFactory::getCastToEmpty(DIDescriptor D) {
201   if (D.isNull()) return Constant::getNullValue(EmptyStructPtr);
202   return ConstantExpr::getBitCast(D.getGV(), EmptyStructPtr);
203 }
204
205 Constant *DIFactory::GetTagConstant(unsigned TAG) {
206   assert((TAG & DIDescriptor::VersionMask) == 0 &&
207          "Tag too large for debug encoding!");
208   return ConstantInt::get(Type::Int32Ty, TAG | DIDescriptor::Version7);
209 }
210
211 Constant *DIFactory::GetStringConstant(const std::string &String) {
212   // Check string cache for previous edition.
213   Constant *&Slot = StringCache[String];
214   
215   // Return Constant if previously defined.
216   if (Slot) return Slot;
217   
218   const PointerType *DestTy = PointerType::getUnqual(Type::Int8Ty);
219   
220   // If empty string then use a sbyte* null instead.
221   if (String.empty())
222     return Slot = ConstantPointerNull::get(DestTy);
223
224   // Construct string as an llvm constant.
225   Constant *ConstStr = ConstantArray::get(String);
226     
227   // Otherwise create and return a new string global.
228   GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
229                                              GlobalVariable::InternalLinkage,
230                                              ConstStr, ".str", &M);
231   StrGV->setSection("llvm.metadata");
232   return Slot = ConstantExpr::getBitCast(StrGV, DestTy);
233 }
234
235 /// GetOrCreateAnchor - Look up an anchor for the specified tag and name.  If it
236 /// already exists, return it.  If not, create a new one and return it.
237 DIAnchor DIFactory::GetOrCreateAnchor(unsigned TAG, const char *Name) {
238   const Type *EltTy = StructType::get(Type::Int32Ty, Type::Int32Ty, NULL);
239   
240   // Otherwise, create the global or return it if already in the module.
241   Constant *C = M.getOrInsertGlobal(Name, EltTy);
242   assert(isa<GlobalVariable>(C) && "Incorrectly typed anchor?");
243   GlobalVariable *GV = cast<GlobalVariable>(C);
244   
245   // If it has an initializer, it is already in the module.
246   if (GV->hasInitializer()) 
247     return SubProgramAnchor = DIAnchor(GV);
248   
249   GV->setLinkage(GlobalValue::LinkOnceLinkage);
250   GV->setSection("llvm.metadata");
251   GV->setConstant(true);
252   M.addTypeName("llvm.dbg.anchor.type", EltTy);
253   
254   // Otherwise, set the initializer.
255   Constant *Elts[] = {
256     GetTagConstant(dwarf::DW_TAG_anchor),
257     ConstantInt::get(Type::Int32Ty, TAG)
258   };
259   
260   GV->setInitializer(ConstantStruct::get(Elts, 2));
261   return DIAnchor(GV);
262 }
263
264
265
266 //===----------------------------------------------------------------------===//
267 // DIFactory: Primary Constructors
268 //===----------------------------------------------------------------------===//
269
270 /// GetOrCreateCompileUnitAnchor - Return the anchor for compile units,
271 /// creating a new one if there isn't already one in the module.
272 DIAnchor DIFactory::GetOrCreateCompileUnitAnchor() {
273   // If we already created one, just return it.
274   if (!CompileUnitAnchor.isNull())
275     return CompileUnitAnchor;
276   return CompileUnitAnchor = GetOrCreateAnchor(dwarf::DW_TAG_compile_unit,
277                                                "llvm.dbg.compile_units");
278 }
279
280 /// GetOrCreateSubprogramAnchor - Return the anchor for subprograms,
281 /// creating a new one if there isn't already one in the module.
282 DIAnchor DIFactory::GetOrCreateSubprogramAnchor() {
283   // If we already created one, just return it.
284   if (!SubProgramAnchor.isNull())
285     return SubProgramAnchor;
286   return SubProgramAnchor = GetOrCreateAnchor(dwarf::DW_TAG_subprogram,
287                                               "llvm.dbg.subprograms");
288 }
289
290 /// GetOrCreateGlobalVariableAnchor - Return the anchor for globals,
291 /// creating a new one if there isn't already one in the module.
292 DIAnchor DIFactory::GetOrCreateGlobalVariableAnchor() {
293   // If we already created one, just return it.
294   if (!GlobalVariableAnchor.isNull())
295     return GlobalVariableAnchor;
296   return GlobalVariableAnchor = GetOrCreateAnchor(dwarf::DW_TAG_variable,
297                                                   "llvm.dbg.global_variables");
298 }
299
300 /// GetOrCreateArray - Create an descriptor for an array of descriptors. 
301 /// This implicitly uniques the arrays created.
302 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
303   SmallVector<Constant*, 16> Elts;
304   
305   for (unsigned i = 0; i != NumTys; ++i)
306     Elts.push_back(getCastToEmpty(Tys[i]));
307   
308   Constant *Init = ConstantArray::get(ArrayType::get(EmptyStructPtr,
309                                                      Elts.size()),
310                                       &Elts[0], Elts.size());
311   // If we already have this array, just return the uniqued version.
312   DIDescriptor &Entry = SimpleConstantCache[Init];
313   if (!Entry.isNull()) return DIArray(Entry.getGV());
314   
315   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
316                                           GlobalValue::InternalLinkage,
317                                           Init, "llvm.dbg.array", &M);
318   GV->setSection("llvm.metadata");
319   Entry = DIDescriptor(GV);
320   return DIArray(GV);
321 }
322
323 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
324 /// implicitly uniques the values returned.
325 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
326   Constant *Elts[] = {
327     GetTagConstant(dwarf::DW_TAG_subrange_type),
328     ConstantInt::get(Type::Int64Ty, Lo),
329     ConstantInt::get(Type::Int64Ty, Hi)
330   };
331   
332   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
333
334   // If we already have this range, just return the uniqued version.
335   DIDescriptor &Entry = SimpleConstantCache[Init];
336   if (!Entry.isNull()) return DISubrange(Entry.getGV());
337   
338   M.addTypeName("llvm.dbg.subrange.type", Init->getType());
339
340   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
341                                           GlobalValue::InternalLinkage,
342                                           Init, "llvm.dbg.subrange", &M);
343   GV->setSection("llvm.metadata");
344   Entry = DIDescriptor(GV);
345   return DISubrange(GV);
346 }
347
348
349
350 /// CreateCompileUnit - Create a new descriptor for the specified compile
351 /// unit.  Note that this does not unique compile units within the module.
352 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
353                                            const std::string &Filename,
354                                            const std::string &Directory,
355                                            const std::string &Producer) {
356   Constant *Elts[] = {
357     GetTagConstant(dwarf::DW_TAG_compile_unit),
358     getCastToEmpty(GetOrCreateCompileUnitAnchor()),
359     ConstantInt::get(Type::Int32Ty, LangID),
360     GetStringConstant(Filename),
361     GetStringConstant(Directory),
362     GetStringConstant(Producer)
363   };
364   
365   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
366   
367   M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
368   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
369                                           GlobalValue::InternalLinkage,
370                                           Init, "llvm.dbg.compile_unit", &M);
371   GV->setSection("llvm.metadata");
372   return DICompileUnit(GV);
373 }
374
375 /// CreateEnumerator - Create a single enumerator value.
376 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
377   Constant *Elts[] = {
378     GetTagConstant(dwarf::DW_TAG_enumerator),
379     GetStringConstant(Name),
380     ConstantInt::get(Type::Int64Ty, Val)
381   };
382   
383   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
384   
385   M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
386   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
387                                           GlobalValue::InternalLinkage,
388                                           Init, "llvm.dbg.enumerator", &M);
389   GV->setSection("llvm.metadata");
390   return DIEnumerator(GV);
391 }
392
393
394 /// CreateBasicType - Create a basic type like int, float, etc.
395 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
396                                       const std::string &Name,
397                                        DICompileUnit CompileUnit,
398                                        unsigned LineNumber,
399                                        uint64_t SizeInBits,
400                                        uint64_t AlignInBits,
401                                        uint64_t OffsetInBits, unsigned Flags,
402                                        unsigned Encoding,
403                                        const std::string *FileName,
404                                        const std::string *Directory) {
405   Constant *Elts[] = {
406     GetTagConstant(dwarf::DW_TAG_base_type),
407     getCastToEmpty(Context),
408     GetStringConstant(Name),
409     getCastToEmpty(CompileUnit),
410     ConstantInt::get(Type::Int32Ty, LineNumber),
411     ConstantInt::get(Type::Int64Ty, SizeInBits),
412     ConstantInt::get(Type::Int64Ty, AlignInBits),
413     ConstantInt::get(Type::Int64Ty, OffsetInBits),
414     ConstantInt::get(Type::Int32Ty, Flags),
415     ConstantInt::get(Type::Int32Ty, Encoding),
416     GetStringConstant(FileName ? FileName->c_str() : ""),
417     GetStringConstant(Directory ? Directory->c_str() : "")
418   };
419   
420   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
421   
422   M.addTypeName("llvm.dbg.basictype.type", Init->getType());
423   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
424                                           GlobalValue::InternalLinkage,
425                                           Init, "llvm.dbg.basictype", &M);
426   GV->setSection("llvm.metadata");
427   return DIBasicType(GV);
428 }
429
430 /// CreateDerivedType - Create a derived type like const qualified type,
431 /// pointer, typedef, etc.
432 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
433                                            DIDescriptor Context,
434                                            const std::string &Name,
435                                            DICompileUnit CompileUnit,
436                                            unsigned LineNumber,
437                                            uint64_t SizeInBits,
438                                            uint64_t AlignInBits,
439                                            uint64_t OffsetInBits,
440                                            unsigned Flags,
441                                            DIType DerivedFrom,
442                                            const std::string *FileName,
443                                            const std::string *Directory) {
444   Constant *Elts[] = {
445     GetTagConstant(Tag),
446     getCastToEmpty(Context),
447     GetStringConstant(Name),
448     getCastToEmpty(CompileUnit),
449     ConstantInt::get(Type::Int32Ty, LineNumber),
450     ConstantInt::get(Type::Int64Ty, SizeInBits),
451     ConstantInt::get(Type::Int64Ty, AlignInBits),
452     ConstantInt::get(Type::Int64Ty, OffsetInBits),
453     ConstantInt::get(Type::Int32Ty, Flags),
454     getCastToEmpty(DerivedFrom),
455     GetStringConstant(FileName ? FileName->c_str() : ""),
456     GetStringConstant(Directory ? Directory->c_str() : "")
457   };
458   
459   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
460   
461   M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
462   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
463                                           GlobalValue::InternalLinkage,
464                                           Init, "llvm.dbg.derivedtype", &M);
465   GV->setSection("llvm.metadata");
466   return DIDerivedType(GV);
467 }
468
469 /// CreateCompositeType - Create a composite type like array, struct, etc.
470 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
471                                                DIDescriptor Context,
472                                                const std::string &Name,
473                                                DICompileUnit CompileUnit,
474                                                unsigned LineNumber,
475                                                uint64_t SizeInBits,
476                                                uint64_t AlignInBits,
477                                                uint64_t OffsetInBits,
478                                                unsigned Flags,
479                                                DIType DerivedFrom,
480                                                DIArray Elements,
481                                                const std::string *FileName,
482                                                const std::string *Directory) {
483
484   Constant *Elts[] = {
485     GetTagConstant(Tag),
486     getCastToEmpty(Context),
487     GetStringConstant(Name),
488     getCastToEmpty(CompileUnit),
489     ConstantInt::get(Type::Int32Ty, LineNumber),
490     ConstantInt::get(Type::Int64Ty, SizeInBits),
491     ConstantInt::get(Type::Int64Ty, AlignInBits),
492     ConstantInt::get(Type::Int64Ty, OffsetInBits),
493     ConstantInt::get(Type::Int32Ty, Flags),
494     getCastToEmpty(DerivedFrom),
495     getCastToEmpty(Elements),
496     GetStringConstant(FileName ? FileName->c_str() : ""),
497     GetStringConstant(Directory ? Directory->c_str() : "")
498   };
499   
500   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
501   
502   M.addTypeName("llvm.dbg.composite.type", Init->getType());
503   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
504                                           GlobalValue::InternalLinkage,
505                                           Init, "llvm.dbg.composite", &M);
506   GV->setSection("llvm.metadata");
507   return DICompositeType(GV);
508 }
509
510
511 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
512 /// See comments in DISubprogram for descriptions of these fields.  This
513 /// method does not unique the generated descriptors.
514 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context, 
515                                          const std::string &Name,
516                                          const std::string &DisplayName,
517                                          const std::string &LinkageName,
518                                          DICompileUnit CompileUnit,
519                                          unsigned LineNo, DIType Type,
520                                          bool isLocalToUnit,
521                                          bool isDefinition,
522                                          const std::string *FileName,
523                                          const std::string *Directory) {
524
525   Constant *Elts[] = {
526     GetTagConstant(dwarf::DW_TAG_subprogram),
527     getCastToEmpty(GetOrCreateSubprogramAnchor()),
528     getCastToEmpty(Context),
529     GetStringConstant(Name),
530     GetStringConstant(DisplayName),
531     GetStringConstant(LinkageName),
532     getCastToEmpty(CompileUnit),
533     ConstantInt::get(Type::Int32Ty, LineNo),
534     getCastToEmpty(Type),
535     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
536     ConstantInt::get(Type::Int1Ty, isDefinition),
537     GetStringConstant(FileName ? FileName->c_str() : ""),
538     GetStringConstant(Directory ? Directory->c_str() : "")
539   };
540   
541   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
542   
543   M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
544   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
545                                           GlobalValue::InternalLinkage,
546                                           Init, "llvm.dbg.subprogram", &M);
547   GV->setSection("llvm.metadata");
548   return DISubprogram(GV);
549 }
550
551 /// CreateGlobalVariable - Create a new descriptor for the specified global.
552 DIGlobalVariable
553 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
554                                 const std::string &DisplayName,
555                                 const std::string &LinkageName,
556                                 DICompileUnit CompileUnit,
557                                 unsigned LineNo, DIType Type,bool isLocalToUnit,
558                                 bool isDefinition, llvm::GlobalVariable *Val,
559                                 const std::string *FileName,
560                                 const std::string *Directory) {
561   Constant *Elts[] = {
562     GetTagConstant(dwarf::DW_TAG_variable),
563     getCastToEmpty(GetOrCreateGlobalVariableAnchor()),
564     getCastToEmpty(Context),
565     GetStringConstant(Name),
566     GetStringConstant(DisplayName),
567     GetStringConstant(LinkageName),
568     getCastToEmpty(CompileUnit),
569     ConstantInt::get(Type::Int32Ty, LineNo),
570     getCastToEmpty(Type),
571     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
572     ConstantInt::get(Type::Int1Ty, isDefinition),
573     ConstantExpr::getBitCast(Val, EmptyStructPtr),
574     GetStringConstant(FileName ? FileName->c_str() : ""),
575     GetStringConstant(Directory ? Directory->c_str() : "")
576   };
577   
578   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
579   
580   M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
581   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
582                                           GlobalValue::InternalLinkage,
583                                           Init, "llvm.dbg.global_variable", &M);
584   GV->setSection("llvm.metadata");
585   return DIGlobalVariable(GV);
586 }
587
588
589 /// CreateVariable - Create a new descriptor for the specified variable.
590 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
591                                      const std::string &Name,
592                                      DICompileUnit CompileUnit, unsigned LineNo,
593                                      DIType Type,
594                                      const std::string *FileName,
595                                      const std::string *Directory) {
596
597   
598   Constant *Elts[] = {
599     GetTagConstant(Tag),
600     getCastToEmpty(Context),
601     GetStringConstant(Name),
602     getCastToEmpty(CompileUnit),
603     ConstantInt::get(Type::Int32Ty, LineNo),
604     getCastToEmpty(Type),
605     GetStringConstant(FileName ? FileName->c_str() : ""),
606     GetStringConstant(Directory ? Directory->c_str() : "")
607   };
608   
609   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
610   
611   M.addTypeName("llvm.dbg.variable.type", Init->getType());
612   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
613                                           GlobalValue::InternalLinkage,
614                                           Init, "llvm.dbg.variable", &M);
615   GV->setSection("llvm.metadata");
616   return DIVariable(GV);
617 }
618
619
620 /// CreateBlock - This creates a descriptor for a lexical block with the
621 /// specified parent context.
622 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
623   Constant *Elts[] = {
624     GetTagConstant(dwarf::DW_TAG_lexical_block),
625     getCastToEmpty(Context)
626   };
627   
628   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
629   
630   M.addTypeName("llvm.dbg.block.type", Init->getType());
631   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
632                                           GlobalValue::InternalLinkage,
633                                           Init, "llvm.dbg.block", &M);
634   GV->setSection("llvm.metadata");
635   return DIBlock(GV);
636 }
637
638
639 //===----------------------------------------------------------------------===//
640 // DIFactory: Routines for inserting code into a function
641 //===----------------------------------------------------------------------===//
642
643 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
644 /// inserting it at the end of the specified basic block.
645 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
646                                 unsigned ColNo, BasicBlock *BB) {
647   
648   // Lazily construct llvm.dbg.stoppoint function.
649   if (!StopPointFn)
650     StopPointFn = llvm::Intrinsic::getDeclaration(&M, 
651                                               llvm::Intrinsic::dbg_stoppoint);
652   
653   // Invoke llvm.dbg.stoppoint
654   Value *Args[] = {
655     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo),
656     llvm::ConstantInt::get(llvm::Type::Int32Ty, ColNo),
657     getCastToEmpty(CU)
658   };
659   CallInst::Create(StopPointFn, Args, Args+3, "", BB);
660 }
661
662 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
663 /// mark the start of the specified subprogram.
664 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
665   // Lazily construct llvm.dbg.func.start.
666   if (!FuncStartFn)
667     FuncStartFn = llvm::Intrinsic::getDeclaration(&M, 
668                                               llvm::Intrinsic::dbg_func_start);
669   
670   // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
671   CallInst::Create(FuncStartFn, getCastToEmpty(SP), "", BB);
672 }
673
674 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
675 /// mark the start of a region for the specified scoping descriptor.
676 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
677   // Lazily construct llvm.dbg.region.start function.
678   if (!RegionStartFn)
679     RegionStartFn = llvm::Intrinsic::getDeclaration(&M, 
680                                             llvm::Intrinsic::dbg_region_start);
681   // Call llvm.dbg.func.start.
682   CallInst::Create(RegionStartFn, getCastToEmpty(D), "", BB);
683 }
684
685
686 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
687 /// mark the end of a region for the specified scoping descriptor.
688 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
689   // Lazily construct llvm.dbg.region.end function.
690   if (!RegionEndFn)
691     RegionEndFn = llvm::Intrinsic::getDeclaration(&M,
692                                                llvm::Intrinsic::dbg_region_end);
693   
694   CallInst::Create(RegionEndFn, getCastToEmpty(D), "", BB);
695 }
696
697 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
698 void DIFactory::InsertDeclare(llvm::Value *Storage, DIVariable D,
699                               BasicBlock *BB) {
700   // Cast the storage to a {}* for the call to llvm.dbg.declare.
701   Storage = new llvm::BitCastInst(Storage, EmptyStructPtr, "", BB);
702   
703   if (!DeclareFn)
704     DeclareFn = llvm::Intrinsic::getDeclaration(&M,
705                                                 llvm::Intrinsic::dbg_declare);
706   Value *Args[] = { Storage, getCastToEmpty(D) };
707   CallInst::Create(DeclareFn, Args, Args+2, "", BB);
708 }
709
710 namespace llvm {
711   /// Finds the stoppoint coressponding to this instruction, that is the
712   /// stoppoint that dominates this instruction 
713   const DbgStopPointInst *findStopPoint(const Instruction *Inst)
714   {
715     if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
716       return DSI;
717
718     const BasicBlock *BB = Inst->getParent();
719     BasicBlock::const_iterator I = Inst, B;
720     do {
721       B = BB->begin();
722       // A BB consisting only of a terminator can't have a stoppoint.
723       if (I != B) {
724         do {
725           --I;
726           if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
727             return DSI;
728         } while (I != B);
729       }
730       // This BB didn't have a stoppoint: if there is only one
731       // predecessor, look for a stoppoint there.
732       // We could use getIDom(), but that would require dominator info.
733       BB = I->getParent()->getUniquePredecessor();
734       if (BB)
735         I = BB->getTerminator();
736     } while (BB != 0);
737     return 0;
738   }
739
740   /// Finds the stoppoint corresponding to first real (non-debug intrinsic) 
741   /// instruction in this Basic Block, and returns the stoppoint for it.
742   const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB)
743   {
744     for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
745       if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
746         return DSI;
747     }
748     // Fallback to looking for stoppoint of unique predecessor.
749     // Useful if this BB contains no stoppoints, but unique predecessor does.
750     BB = BB->getUniquePredecessor();
751     if (BB)
752       return findStopPoint(BB->getTerminator());
753     return 0;
754   }
755
756   /// Finds the dbg.declare intrinsic corresponding to this value if any.
757   /// It looks through pointer casts too.
758   const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts)
759   {
760     if (stripCasts) {
761       V = V->stripPointerCasts();
762       // Look for the bitcast.
763       for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
764             I != E; ++I) {
765         if (isa<BitCastInst>(I))
766           return findDbgDeclare(*I, false);
767       }
768       return 0;
769     }
770
771     // Find dbg.declare among uses of the instruction.
772     for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
773           I != E; ++I) {
774       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
775         return DDI;
776     }
777     return 0;
778   }
779 }
780