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