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