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