Temporarily revert r71158. It was causing a failure during a full bootstrap:
[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 #include "llvm/Support/Streams.h"
25 using namespace llvm;
26 using namespace llvm::dwarf;
27
28 //===----------------------------------------------------------------------===//
29 // DIDescriptor
30 //===----------------------------------------------------------------------===//
31
32 /// ValidDebugInfo - Return true if V represents valid debug info value.
33 bool DIDescriptor::ValidDebugInfo(Value *V, CodeGenOpt::Level OptLevel) {
34   if (!V)
35     return false;
36
37   GlobalVariable *GV = dyn_cast<GlobalVariable>(V->stripPointerCasts());
38   if (!GV)
39     return false;
40
41   if (!GV->hasInternalLinkage () && !GV->hasLinkOnceLinkage())
42     return false;
43
44   DIDescriptor DI(GV);
45
46   // Check current version. Allow Version6 for now.
47   unsigned Version = DI.getVersion();
48   if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
49     return false;
50
51   unsigned Tag = DI.getTag();
52   switch (Tag) {
53   case DW_TAG_variable:
54     assert(DIVariable(GV).Verify() && "Invalid DebugInfo value");
55     break;
56   case DW_TAG_compile_unit:
57     assert(DICompileUnit(GV).Verify() && "Invalid DebugInfo value");
58     break;
59   case DW_TAG_subprogram:
60     assert(DISubprogram(GV).Verify() && "Invalid DebugInfo value");
61     break;
62   case DW_TAG_inlined_subroutine:
63     assert(DIInlinedSubprogram(GV).Verify() && "Invalid DebugInfo value");
64     break;
65   case DW_TAG_lexical_block:
66     /// FIXME. This interfers with the quality of generated code when
67     /// during optimization.
68     if (OptLevel != CodeGenOpt::None)
69       return false;
70   default:
71     break;
72   }
73
74   return true;
75 }
76
77 DIDescriptor::DIDescriptor(GlobalVariable *gv, unsigned RequiredTag) {
78   GV = gv;
79   
80   // If this is non-null, check to see if the Tag matches.  If not, set to null.
81   if (GV && getTag() != RequiredTag)
82     GV = 0;
83 }
84
85 const std::string &
86 DIDescriptor::getStringField(unsigned Elt, std::string &Result) const {
87   if (GV == 0) {
88     Result.clear();
89     return Result;
90   }
91
92   Constant *C = GV->getInitializer();
93   if (C == 0 || Elt >= C->getNumOperands()) {
94     Result.clear();
95     return Result;
96   }
97   
98   // Fills in the string if it succeeds
99   if (!GetConstantStringInfo(C->getOperand(Elt), Result))
100     Result.clear();
101
102   return Result;
103 }
104
105 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
106   if (GV == 0) return 0;
107   Constant *C = GV->getInitializer();
108   if (C == 0 || Elt >= C->getNumOperands())
109     return 0;
110   if (ConstantInt *CI = dyn_cast<ConstantInt>(C->getOperand(Elt)))
111     return CI->getZExtValue();
112   return 0;
113 }
114
115 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
116   if (GV == 0) return DIDescriptor();
117   Constant *C = GV->getInitializer();
118   if (C == 0 || Elt >= C->getNumOperands())
119     return DIDescriptor();
120   C = C->getOperand(Elt);
121   return DIDescriptor(dyn_cast<GlobalVariable>(C->stripPointerCasts()));
122 }
123
124 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
125   if (GV == 0) return 0;
126   Constant *C = GV->getInitializer();
127   if (C == 0 || Elt >= C->getNumOperands())
128     return 0;
129   C = C->getOperand(Elt);
130   
131   return dyn_cast<GlobalVariable>(C->stripPointerCasts());
132 }
133
134
135
136 //===----------------------------------------------------------------------===//
137 // Simple Descriptor Constructors and other Methods
138 //===----------------------------------------------------------------------===//
139
140 DIAnchor::DIAnchor(GlobalVariable *GV)
141   : DIDescriptor(GV, dwarf::DW_TAG_anchor) {}
142 DIEnumerator::DIEnumerator(GlobalVariable *GV)
143   : DIDescriptor(GV, dwarf::DW_TAG_enumerator) {}
144 DISubrange::DISubrange(GlobalVariable *GV)
145   : DIDescriptor(GV, dwarf::DW_TAG_subrange_type) {}
146 DICompileUnit::DICompileUnit(GlobalVariable *GV)
147   : DIDescriptor(GV, dwarf::DW_TAG_compile_unit) {}
148 DIBasicType::DIBasicType(GlobalVariable *GV)
149   : DIType(GV, dwarf::DW_TAG_base_type) {}
150 DISubprogram::DISubprogram(GlobalVariable *GV)
151   : DIGlobal(GV, dwarf::DW_TAG_subprogram) {}
152 DIInlinedSubprogram::DIInlinedSubprogram(GlobalVariable *GV)
153   : DIGlobal(GV, dwarf::DW_TAG_inlined_subroutine) {}
154 DIGlobalVariable::DIGlobalVariable(GlobalVariable *GV)
155   : DIGlobal(GV, dwarf::DW_TAG_variable) {}
156 DIBlock::DIBlock(GlobalVariable *GV)
157   : DIDescriptor(GV, dwarf::DW_TAG_lexical_block) {}
158 // needed by DIVariable::getType()
159 DIType::DIType(GlobalVariable *gv) : DIDescriptor(gv) {
160   if (!gv) return;
161   unsigned tag = getTag();
162   if (tag != dwarf::DW_TAG_base_type && !DIDerivedType::isDerivedType(tag) &&
163       !DICompositeType::isCompositeType(tag))
164     GV = 0;
165 }
166
167 /// isDerivedType - Return true if the specified tag is legal for
168 /// DIDerivedType.
169 bool DIType::isDerivedType(unsigned Tag) {
170   switch (Tag) {
171   case dwarf::DW_TAG_typedef:
172   case dwarf::DW_TAG_pointer_type:
173   case dwarf::DW_TAG_reference_type:
174   case dwarf::DW_TAG_const_type:
175   case dwarf::DW_TAG_volatile_type:
176   case dwarf::DW_TAG_restrict_type:
177   case dwarf::DW_TAG_member:
178   case dwarf::DW_TAG_inheritance:
179     return true;
180   default:
181     // FIXME: Even though it doesn't make sense, CompositeTypes are current
182     // modelled as DerivedTypes, this should return true for them as well.
183     return false;
184   }
185 }
186
187 DIDerivedType::DIDerivedType(GlobalVariable *GV) : DIType(GV, true, true) {
188   if (GV && !isDerivedType(getTag()))
189     GV = 0;
190 }
191
192 /// isCompositeType - Return true if the specified tag is legal for
193 /// DICompositeType.
194 bool DIType::isCompositeType(unsigned TAG) {
195   switch (TAG) {
196   case dwarf::DW_TAG_array_type:
197   case dwarf::DW_TAG_structure_type:
198   case dwarf::DW_TAG_union_type:
199   case dwarf::DW_TAG_enumeration_type:
200   case dwarf::DW_TAG_vector_type:
201   case dwarf::DW_TAG_subroutine_type:
202   case dwarf::DW_TAG_class_type:
203     return true;
204   default:
205     return false;
206   }
207 }
208
209 DICompositeType::DICompositeType(GlobalVariable *GV)
210   : DIDerivedType(GV, true, true) {
211   if (GV && !isCompositeType(getTag()))
212     GV = 0;
213 }
214
215 /// isVariable - Return true if the specified tag is legal for DIVariable.
216 bool DIVariable::isVariable(unsigned Tag) {
217   switch (Tag) {
218   case dwarf::DW_TAG_auto_variable:
219   case dwarf::DW_TAG_arg_variable:
220   case dwarf::DW_TAG_return_variable:
221     return true;
222   default:
223     return false;
224   }
225 }
226
227 DIVariable::DIVariable(GlobalVariable *gv) : DIDescriptor(gv) {
228   if (gv && !isVariable(getTag()))
229     GV = 0;
230 }
231
232 unsigned DIArray::getNumElements() const {
233   assert (GV && "Invalid DIArray");
234   Constant *C = GV->getInitializer();
235   assert (C && "Invalid DIArray initializer");
236   return C->getNumOperands();
237 }
238
239 /// Verify - Verify that a compile unit is well formed.
240 bool DICompileUnit::Verify() const {
241   if (isNull()) 
242     return false;
243   std::string Res;
244   if (getFilename(Res).empty()) 
245     return false;
246   // It is possible that directory and produce string is empty.
247   return true;
248 }
249
250 /// Verify - Verify that a type descriptor is well formed.
251 bool DIType::Verify() const {
252   if (isNull()) 
253     return false;
254   if (getContext().isNull()) 
255     return false;
256
257   DICompileUnit CU = getCompileUnit();
258   if (!CU.isNull() && !CU.Verify()) 
259     return false;
260   return true;
261 }
262
263 /// Verify - Verify that a composite type descriptor is well formed.
264 bool DICompositeType::Verify() const {
265   if (isNull()) 
266     return false;
267   if (getContext().isNull()) 
268     return false;
269
270   DICompileUnit CU = getCompileUnit();
271   if (!CU.isNull() && !CU.Verify()) 
272     return false;
273   return true;
274 }
275
276 /// Verify - Verify that a subprogram descriptor is well formed.
277 bool DISubprogram::Verify() const {
278   if (isNull())
279     return false;
280   
281   if (getContext().isNull())
282     return false;
283
284   DICompileUnit CU = getCompileUnit();
285   if (!CU.Verify()) 
286     return false;
287
288   DICompositeType Ty = getType();
289   if (!Ty.isNull() && !Ty.Verify())
290     return false;
291   return true;
292 }
293
294 /// Verify - Verify that an inlined subprogram descriptor is well formed.
295 bool DIInlinedSubprogram::Verify() const {
296   if (isNull())
297     return false;
298   
299   if (getContext().isNull())
300     return false;
301
302   DICompileUnit CU = getCompileUnit();
303   if (!CU.Verify()) 
304     return false;
305
306   DICompositeType Ty = getType();
307   if (!Ty.isNull() && !Ty.Verify())
308     return false;
309
310   return true;
311 }
312
313 /// Verify - Verify that a global variable descriptor is well formed.
314 bool DIGlobalVariable::Verify() const {
315   if (isNull())
316     return false;
317   
318   if (getContext().isNull())
319     return false;
320
321   DICompileUnit CU = getCompileUnit();
322   if (!CU.isNull() && !CU.Verify()) 
323     return false;
324
325   DIType Ty = getType();
326   if (!Ty.Verify())
327     return false;
328
329   if (!getGlobal())
330     return false;
331
332   return true;
333 }
334
335 /// Verify - Verify that a variable descriptor is well formed.
336 bool DIVariable::Verify() const {
337   if (isNull())
338     return false;
339   
340   if (getContext().isNull())
341     return false;
342
343   DIType Ty = getType();
344   if (!Ty.Verify())
345     return false;
346
347   return true;
348 }
349
350 /// getOriginalTypeSize - If this type is derived from a base type then
351 /// return base type size.
352 uint64_t DIDerivedType::getOriginalTypeSize() const {
353   if (getTag() != dwarf::DW_TAG_member)
354     return getSizeInBits();
355   DIType BT = getTypeDerivedFrom();
356   if (BT.getTag() != dwarf::DW_TAG_base_type)
357     return getSizeInBits();
358   return BT.getSizeInBits();
359 }
360
361 /// describes - Return true if this subprogram provides debugging
362 /// information for the function F.
363 bool DISubprogram::describes(const Function *F) {
364   assert (F && "Invalid function");
365   std::string Name;
366   getLinkageName(Name);
367   if (Name.empty())
368     getName(Name);
369   if (!Name.empty() && (strcmp(Name.c_str(), F->getNameStart()) == false))
370     return true;
371   return false;
372 }
373
374 //===----------------------------------------------------------------------===//
375 // DIFactory: Basic Helpers
376 //===----------------------------------------------------------------------===//
377
378 DIFactory::DIFactory(Module &m) : M(m) {
379   StopPointFn = FuncStartFn = RegionStartFn = RegionEndFn = DeclareFn = 0;
380   EmptyStructPtr = PointerType::getUnqual(StructType::get(NULL, NULL));
381 }
382
383 /// getCastToEmpty - Return this descriptor as a Constant* with type '{}*'.
384 /// This is only valid when the descriptor is non-null.
385 Constant *DIFactory::getCastToEmpty(DIDescriptor D) {
386   if (D.isNull()) return Constant::getNullValue(EmptyStructPtr);
387   return ConstantExpr::getBitCast(D.getGV(), EmptyStructPtr);
388 }
389
390 Constant *DIFactory::GetTagConstant(unsigned TAG) {
391   assert((TAG & LLVMDebugVersionMask) == 0 &&
392          "Tag too large for debug encoding!");
393   return ConstantInt::get(Type::Int32Ty, TAG | LLVMDebugVersion);
394 }
395
396 Constant *DIFactory::GetStringConstant(const std::string &String) {
397   // Check string cache for previous edition.
398   Constant *&Slot = StringCache[String];
399   
400   // Return Constant if previously defined.
401   if (Slot) return Slot;
402   
403   const PointerType *DestTy = PointerType::getUnqual(Type::Int8Ty);
404   
405   // If empty string then use a sbyte* null instead.
406   if (String.empty())
407     return Slot = ConstantPointerNull::get(DestTy);
408
409   // Construct string as an llvm constant.
410   Constant *ConstStr = ConstantArray::get(String);
411     
412   // Otherwise create and return a new string global.
413   GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
414                                              GlobalVariable::InternalLinkage,
415                                              ConstStr, ".str", &M);
416   StrGV->setSection("llvm.metadata");
417   return Slot = ConstantExpr::getBitCast(StrGV, DestTy);
418 }
419
420 /// GetOrCreateAnchor - Look up an anchor for the specified tag and name.  If it
421 /// already exists, return it.  If not, create a new one and return it.
422 DIAnchor DIFactory::GetOrCreateAnchor(unsigned TAG, const char *Name) {
423   const Type *EltTy = StructType::get(Type::Int32Ty, Type::Int32Ty, NULL);
424   
425   // Otherwise, create the global or return it if already in the module.
426   Constant *C = M.getOrInsertGlobal(Name, EltTy);
427   assert(isa<GlobalVariable>(C) && "Incorrectly typed anchor?");
428   GlobalVariable *GV = cast<GlobalVariable>(C);
429   
430   // If it has an initializer, it is already in the module.
431   if (GV->hasInitializer()) 
432     return SubProgramAnchor = DIAnchor(GV);
433   
434   GV->setLinkage(GlobalValue::LinkOnceAnyLinkage);
435   GV->setSection("llvm.metadata");
436   GV->setConstant(true);
437   M.addTypeName("llvm.dbg.anchor.type", EltTy);
438   
439   // Otherwise, set the initializer.
440   Constant *Elts[] = {
441     GetTagConstant(dwarf::DW_TAG_anchor),
442     ConstantInt::get(Type::Int32Ty, TAG)
443   };
444   
445   GV->setInitializer(ConstantStruct::get(Elts, 2));
446   return DIAnchor(GV);
447 }
448
449
450
451 //===----------------------------------------------------------------------===//
452 // DIFactory: Primary Constructors
453 //===----------------------------------------------------------------------===//
454
455 /// GetOrCreateCompileUnitAnchor - Return the anchor for compile units,
456 /// creating a new one if there isn't already one in the module.
457 DIAnchor DIFactory::GetOrCreateCompileUnitAnchor() {
458   // If we already created one, just return it.
459   if (!CompileUnitAnchor.isNull())
460     return CompileUnitAnchor;
461   return CompileUnitAnchor = GetOrCreateAnchor(dwarf::DW_TAG_compile_unit,
462                                                "llvm.dbg.compile_units");
463 }
464
465 /// GetOrCreateSubprogramAnchor - Return the anchor for subprograms,
466 /// creating a new one if there isn't already one in the module.
467 DIAnchor DIFactory::GetOrCreateSubprogramAnchor() {
468   // If we already created one, just return it.
469   if (!SubProgramAnchor.isNull())
470     return SubProgramAnchor;
471   return SubProgramAnchor = GetOrCreateAnchor(dwarf::DW_TAG_subprogram,
472                                               "llvm.dbg.subprograms");
473 }
474
475 /// GetOrCreateGlobalVariableAnchor - Return the anchor for globals,
476 /// creating a new one if there isn't already one in the module.
477 DIAnchor DIFactory::GetOrCreateGlobalVariableAnchor() {
478   // If we already created one, just return it.
479   if (!GlobalVariableAnchor.isNull())
480     return GlobalVariableAnchor;
481   return GlobalVariableAnchor = GetOrCreateAnchor(dwarf::DW_TAG_variable,
482                                                   "llvm.dbg.global_variables");
483 }
484
485 /// GetOrCreateArray - Create an descriptor for an array of descriptors. 
486 /// This implicitly uniques the arrays created.
487 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
488   SmallVector<Constant*, 16> Elts;
489   
490   for (unsigned i = 0; i != NumTys; ++i)
491     Elts.push_back(getCastToEmpty(Tys[i]));
492   
493   Constant *Init = ConstantArray::get(ArrayType::get(EmptyStructPtr,
494                                                      Elts.size()),
495                                       &Elts[0], Elts.size());
496   // If we already have this array, just return the uniqued version.
497   DIDescriptor &Entry = SimpleConstantCache[Init];
498   if (!Entry.isNull()) return DIArray(Entry.getGV());
499   
500   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
501                                           GlobalValue::InternalLinkage,
502                                           Init, "llvm.dbg.array", &M);
503   GV->setSection("llvm.metadata");
504   Entry = DIDescriptor(GV);
505   return DIArray(GV);
506 }
507
508 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
509 /// implicitly uniques the values returned.
510 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
511   Constant *Elts[] = {
512     GetTagConstant(dwarf::DW_TAG_subrange_type),
513     ConstantInt::get(Type::Int64Ty, Lo),
514     ConstantInt::get(Type::Int64Ty, Hi)
515   };
516   
517   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
518
519   // If we already have this range, just return the uniqued version.
520   DIDescriptor &Entry = SimpleConstantCache[Init];
521   if (!Entry.isNull()) return DISubrange(Entry.getGV());
522   
523   M.addTypeName("llvm.dbg.subrange.type", Init->getType());
524
525   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
526                                           GlobalValue::InternalLinkage,
527                                           Init, "llvm.dbg.subrange", &M);
528   GV->setSection("llvm.metadata");
529   Entry = DIDescriptor(GV);
530   return DISubrange(GV);
531 }
532
533
534
535 /// CreateCompileUnit - Create a new descriptor for the specified compile
536 /// unit.  Note that this does not unique compile units within the module.
537 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
538                                            const std::string &Filename,
539                                            const std::string &Directory,
540                                            const std::string &Producer,
541                                            bool isMain,
542                                            bool isOptimized,
543                                            const char *Flags,
544                                            unsigned RunTimeVer) {
545   Constant *Elts[] = {
546     GetTagConstant(dwarf::DW_TAG_compile_unit),
547     getCastToEmpty(GetOrCreateCompileUnitAnchor()),
548     ConstantInt::get(Type::Int32Ty, LangID),
549     GetStringConstant(Filename),
550     GetStringConstant(Directory),
551     GetStringConstant(Producer),
552     ConstantInt::get(Type::Int1Ty, isMain),
553     ConstantInt::get(Type::Int1Ty, isOptimized),
554     GetStringConstant(Flags),
555     ConstantInt::get(Type::Int32Ty, RunTimeVer)
556   };
557   
558   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
559   
560   M.addTypeName("llvm.dbg.compile_unit.type", Init->getType());
561   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
562                                           GlobalValue::InternalLinkage,
563                                           Init, "llvm.dbg.compile_unit", &M);
564   GV->setSection("llvm.metadata");
565   return DICompileUnit(GV);
566 }
567
568 /// CreateEnumerator - Create a single enumerator value.
569 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
570   Constant *Elts[] = {
571     GetTagConstant(dwarf::DW_TAG_enumerator),
572     GetStringConstant(Name),
573     ConstantInt::get(Type::Int64Ty, Val)
574   };
575   
576   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
577   
578   M.addTypeName("llvm.dbg.enumerator.type", Init->getType());
579   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
580                                           GlobalValue::InternalLinkage,
581                                           Init, "llvm.dbg.enumerator", &M);
582   GV->setSection("llvm.metadata");
583   return DIEnumerator(GV);
584 }
585
586
587 /// CreateBasicType - Create a basic type like int, float, etc.
588 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
589                                       const std::string &Name,
590                                        DICompileUnit CompileUnit,
591                                        unsigned LineNumber,
592                                        uint64_t SizeInBits,
593                                        uint64_t AlignInBits,
594                                        uint64_t OffsetInBits, unsigned Flags,
595                                        unsigned Encoding) {
596   Constant *Elts[] = {
597     GetTagConstant(dwarf::DW_TAG_base_type),
598     getCastToEmpty(Context),
599     GetStringConstant(Name),
600     getCastToEmpty(CompileUnit),
601     ConstantInt::get(Type::Int32Ty, LineNumber),
602     ConstantInt::get(Type::Int64Ty, SizeInBits),
603     ConstantInt::get(Type::Int64Ty, AlignInBits),
604     ConstantInt::get(Type::Int64Ty, OffsetInBits),
605     ConstantInt::get(Type::Int32Ty, Flags),
606     ConstantInt::get(Type::Int32Ty, Encoding)
607   };
608   
609   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
610   
611   M.addTypeName("llvm.dbg.basictype.type", Init->getType());
612   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
613                                           GlobalValue::InternalLinkage,
614                                           Init, "llvm.dbg.basictype", &M);
615   GV->setSection("llvm.metadata");
616   return DIBasicType(GV);
617 }
618
619 /// CreateDerivedType - Create a derived type like const qualified type,
620 /// pointer, typedef, etc.
621 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
622                                            DIDescriptor Context,
623                                            const std::string &Name,
624                                            DICompileUnit CompileUnit,
625                                            unsigned LineNumber,
626                                            uint64_t SizeInBits,
627                                            uint64_t AlignInBits,
628                                            uint64_t OffsetInBits,
629                                            unsigned Flags,
630                                            DIType DerivedFrom) {
631   Constant *Elts[] = {
632     GetTagConstant(Tag),
633     getCastToEmpty(Context),
634     GetStringConstant(Name),
635     getCastToEmpty(CompileUnit),
636     ConstantInt::get(Type::Int32Ty, LineNumber),
637     ConstantInt::get(Type::Int64Ty, SizeInBits),
638     ConstantInt::get(Type::Int64Ty, AlignInBits),
639     ConstantInt::get(Type::Int64Ty, OffsetInBits),
640     ConstantInt::get(Type::Int32Ty, Flags),
641     getCastToEmpty(DerivedFrom)
642   };
643   
644   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
645   
646   M.addTypeName("llvm.dbg.derivedtype.type", Init->getType());
647   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
648                                           GlobalValue::InternalLinkage,
649                                           Init, "llvm.dbg.derivedtype", &M);
650   GV->setSection("llvm.metadata");
651   return DIDerivedType(GV);
652 }
653
654 /// CreateCompositeType - Create a composite type like array, struct, etc.
655 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
656                                                DIDescriptor Context,
657                                                const std::string &Name,
658                                                DICompileUnit CompileUnit,
659                                                unsigned LineNumber,
660                                                uint64_t SizeInBits,
661                                                uint64_t AlignInBits,
662                                                uint64_t OffsetInBits,
663                                                unsigned Flags,
664                                                DIType DerivedFrom,
665                                                DIArray Elements,
666                                                unsigned RuntimeLang) {
667
668   Constant *Elts[] = {
669     GetTagConstant(Tag),
670     getCastToEmpty(Context),
671     GetStringConstant(Name),
672     getCastToEmpty(CompileUnit),
673     ConstantInt::get(Type::Int32Ty, LineNumber),
674     ConstantInt::get(Type::Int64Ty, SizeInBits),
675     ConstantInt::get(Type::Int64Ty, AlignInBits),
676     ConstantInt::get(Type::Int64Ty, OffsetInBits),
677     ConstantInt::get(Type::Int32Ty, Flags),
678     getCastToEmpty(DerivedFrom),
679     getCastToEmpty(Elements),
680     ConstantInt::get(Type::Int32Ty, RuntimeLang)
681   };
682   
683   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
684   
685   M.addTypeName("llvm.dbg.composite.type", Init->getType());
686   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
687                                           GlobalValue::InternalLinkage,
688                                           Init, "llvm.dbg.composite", &M);
689   GV->setSection("llvm.metadata");
690   return DICompositeType(GV);
691 }
692
693
694 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
695 /// See comments in DISubprogram for descriptions of these fields.  This
696 /// method does not unique the generated descriptors.
697 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context, 
698                                          const std::string &Name,
699                                          const std::string &DisplayName,
700                                          const std::string &LinkageName,
701                                          DICompileUnit CompileUnit,
702                                          unsigned LineNo, DIType Type,
703                                          bool isLocalToUnit,
704                                          bool isDefinition) {
705
706   Constant *Elts[] = {
707     GetTagConstant(dwarf::DW_TAG_subprogram),
708     getCastToEmpty(GetOrCreateSubprogramAnchor()),
709     getCastToEmpty(Context),
710     GetStringConstant(Name),
711     GetStringConstant(DisplayName),
712     GetStringConstant(LinkageName),
713     getCastToEmpty(CompileUnit),
714     ConstantInt::get(Type::Int32Ty, LineNo),
715     getCastToEmpty(Type),
716     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
717     ConstantInt::get(Type::Int1Ty, isDefinition)
718   };
719   
720   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
721   
722   M.addTypeName("llvm.dbg.subprogram.type", Init->getType());
723   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
724                                           GlobalValue::InternalLinkage,
725                                           Init, "llvm.dbg.subprogram", &M);
726   GV->setSection("llvm.metadata");
727   return DISubprogram(GV);
728 }
729
730 /// CreateGlobalVariable - Create a new descriptor for the specified global.
731 DIGlobalVariable
732 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
733                                 const std::string &DisplayName,
734                                 const std::string &LinkageName,
735                                 DICompileUnit CompileUnit,
736                                 unsigned LineNo, DIType Type,bool isLocalToUnit,
737                                 bool isDefinition, llvm::GlobalVariable *Val) {
738   Constant *Elts[] = {
739     GetTagConstant(dwarf::DW_TAG_variable),
740     getCastToEmpty(GetOrCreateGlobalVariableAnchor()),
741     getCastToEmpty(Context),
742     GetStringConstant(Name),
743     GetStringConstant(DisplayName),
744     GetStringConstant(LinkageName),
745     getCastToEmpty(CompileUnit),
746     ConstantInt::get(Type::Int32Ty, LineNo),
747     getCastToEmpty(Type),
748     ConstantInt::get(Type::Int1Ty, isLocalToUnit),
749     ConstantInt::get(Type::Int1Ty, isDefinition),
750     ConstantExpr::getBitCast(Val, EmptyStructPtr)
751   };
752   
753   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
754   
755   M.addTypeName("llvm.dbg.global_variable.type", Init->getType());
756   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
757                                           GlobalValue::InternalLinkage,
758                                           Init, "llvm.dbg.global_variable", &M);
759   GV->setSection("llvm.metadata");
760   return DIGlobalVariable(GV);
761 }
762
763
764 /// CreateVariable - Create a new descriptor for the specified variable.
765 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
766                                      const std::string &Name,
767                                      DICompileUnit CompileUnit, unsigned LineNo,
768                                      DIType Type) {
769   Constant *Elts[] = {
770     GetTagConstant(Tag),
771     getCastToEmpty(Context),
772     GetStringConstant(Name),
773     getCastToEmpty(CompileUnit),
774     ConstantInt::get(Type::Int32Ty, LineNo),
775     getCastToEmpty(Type)
776   };
777   
778   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
779   
780   M.addTypeName("llvm.dbg.variable.type", Init->getType());
781   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
782                                           GlobalValue::InternalLinkage,
783                                           Init, "llvm.dbg.variable", &M);
784   GV->setSection("llvm.metadata");
785   return DIVariable(GV);
786 }
787
788
789 /// CreateBlock - This creates a descriptor for a lexical block with the
790 /// specified parent context.
791 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
792   Constant *Elts[] = {
793     GetTagConstant(dwarf::DW_TAG_lexical_block),
794     getCastToEmpty(Context)
795   };
796   
797   Constant *Init = ConstantStruct::get(Elts, sizeof(Elts)/sizeof(Elts[0]));
798   
799   M.addTypeName("llvm.dbg.block.type", Init->getType());
800   GlobalVariable *GV = new GlobalVariable(Init->getType(), true,
801                                           GlobalValue::InternalLinkage,
802                                           Init, "llvm.dbg.block", &M);
803   GV->setSection("llvm.metadata");
804   return DIBlock(GV);
805 }
806
807
808 //===----------------------------------------------------------------------===//
809 // DIFactory: Routines for inserting code into a function
810 //===----------------------------------------------------------------------===//
811
812 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
813 /// inserting it at the end of the specified basic block.
814 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
815                                 unsigned ColNo, BasicBlock *BB) {
816   
817   // Lazily construct llvm.dbg.stoppoint function.
818   if (!StopPointFn)
819     StopPointFn = llvm::Intrinsic::getDeclaration(&M, 
820                                               llvm::Intrinsic::dbg_stoppoint);
821   
822   // Invoke llvm.dbg.stoppoint
823   Value *Args[] = {
824     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo),
825     llvm::ConstantInt::get(llvm::Type::Int32Ty, ColNo),
826     getCastToEmpty(CU)
827   };
828   CallInst::Create(StopPointFn, Args, Args+3, "", BB);
829 }
830
831 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
832 /// mark the start of the specified subprogram.
833 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
834   // Lazily construct llvm.dbg.func.start.
835   if (!FuncStartFn)
836     FuncStartFn = llvm::Intrinsic::getDeclaration(&M, 
837                                               llvm::Intrinsic::dbg_func_start);
838   
839   // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
840   CallInst::Create(FuncStartFn, getCastToEmpty(SP), "", BB);
841 }
842
843 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
844 /// mark the start of a region for the specified scoping descriptor.
845 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
846   // Lazily construct llvm.dbg.region.start function.
847   if (!RegionStartFn)
848     RegionStartFn = llvm::Intrinsic::getDeclaration(&M, 
849                                             llvm::Intrinsic::dbg_region_start);
850   // Call llvm.dbg.func.start.
851   CallInst::Create(RegionStartFn, getCastToEmpty(D), "", BB);
852 }
853
854
855 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
856 /// mark the end of a region for the specified scoping descriptor.
857 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
858   // Lazily construct llvm.dbg.region.end function.
859   if (!RegionEndFn)
860     RegionEndFn = llvm::Intrinsic::getDeclaration(&M,
861                                                llvm::Intrinsic::dbg_region_end);
862   
863   CallInst::Create(RegionEndFn, getCastToEmpty(D), "", BB);
864 }
865
866 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
867 void DIFactory::InsertDeclare(llvm::Value *Storage, DIVariable D,
868                               BasicBlock *BB) {
869   // Cast the storage to a {}* for the call to llvm.dbg.declare.
870   Storage = new llvm::BitCastInst(Storage, EmptyStructPtr, "", BB);
871   
872   if (!DeclareFn)
873     DeclareFn = llvm::Intrinsic::getDeclaration(&M,
874                                                 llvm::Intrinsic::dbg_declare);
875   Value *Args[] = { Storage, getCastToEmpty(D) };
876   CallInst::Create(DeclareFn, Args, Args+2, "", BB);
877 }
878
879 namespace llvm {
880   /// Finds the stoppoint coressponding to this instruction, that is the
881   /// stoppoint that dominates this instruction 
882   const DbgStopPointInst *findStopPoint(const Instruction *Inst)
883   {
884     if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
885       return DSI;
886
887     const BasicBlock *BB = Inst->getParent();
888     BasicBlock::const_iterator I = Inst, B;
889     do {
890       B = BB->begin();
891       // A BB consisting only of a terminator can't have a stoppoint.
892       if (I != B) {
893         do {
894           --I;
895           if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
896             return DSI;
897         } while (I != B);
898       }
899       // This BB didn't have a stoppoint: if there is only one
900       // predecessor, look for a stoppoint there.
901       // We could use getIDom(), but that would require dominator info.
902       BB = I->getParent()->getUniquePredecessor();
903       if (BB)
904         I = BB->getTerminator();
905     } while (BB != 0);
906     return 0;
907   }
908
909   /// Finds the stoppoint corresponding to first real (non-debug intrinsic) 
910   /// instruction in this Basic Block, and returns the stoppoint for it.
911   const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB)
912   {
913     for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
914       if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
915         return DSI;
916     }
917     // Fallback to looking for stoppoint of unique predecessor.
918     // Useful if this BB contains no stoppoints, but unique predecessor does.
919     BB = BB->getUniquePredecessor();
920     if (BB)
921       return findStopPoint(BB->getTerminator());
922     return 0;
923   }
924
925   Value *findDbgGlobalDeclare(GlobalVariable *V)
926   {
927     const Module *M = V->getParent();
928     const Type *Ty = M->getTypeByName("llvm.dbg.global_variable.type");
929     if (!Ty)
930       return 0;
931     Ty = PointerType::get(Ty, 0);
932
933     Value *Val = V->stripPointerCasts();
934     for (Value::use_iterator I = Val->use_begin(), E =Val->use_end();
935          I != E; ++I) {
936       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I)) {
937         if (CE->getOpcode() == Instruction::BitCast) {
938           Value *VV = CE;
939           while (VV->hasOneUse()) {
940             VV = *VV->use_begin();
941           }
942           if (VV->getType() == Ty)
943             return VV;
944         }
945       }
946     }
947     
948     if (Val->getType() == Ty)
949       return Val;
950     return 0;
951   }
952
953   /// Finds the dbg.declare intrinsic corresponding to this value if any.
954   /// It looks through pointer casts too.
955   const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts)
956   {
957     if (stripCasts) {
958       V = V->stripPointerCasts();
959       // Look for the bitcast.
960       for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
961             I != E; ++I) {
962         if (isa<BitCastInst>(I))
963           return findDbgDeclare(*I, false);
964       }
965       return 0;
966     }
967
968     // Find dbg.declare among uses of the instruction.
969     for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
970           I != E; ++I) {
971       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
972         return DDI;
973     }
974     return 0;
975   }
976
977   bool getLocationInfo(const Value *V, std::string &DisplayName, std::string &Type,
978                        unsigned &LineNo, std::string &File, std::string &Dir)
979   {
980     DICompileUnit Unit;
981     DIType TypeD;
982     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
983       Value *DIGV = findDbgGlobalDeclare(GV);
984       if (!DIGV)
985         return false;
986       DIGlobalVariable Var(cast<GlobalVariable>(DIGV));
987       Var.getDisplayName(DisplayName);
988       LineNo = Var.getLineNumber();
989       Unit = Var.getCompileUnit();
990       TypeD = Var.getType();
991     } else {
992       const DbgDeclareInst *DDI = findDbgDeclare(V);
993       if (!DDI)
994         return false;
995       DIVariable Var(cast<GlobalVariable>(DDI->getVariable()));
996       Var.getName(DisplayName);
997       LineNo = Var.getLineNumber();
998       Unit = Var.getCompileUnit();
999       TypeD = Var.getType();
1000     }
1001     TypeD.getName(Type);
1002     Unit.getFilename(File);
1003     Unit.getDirectory(Dir);
1004     return true;
1005   }
1006 }
1007
1008 /// dump - print descriptor.
1009 void DIDescriptor::dump() const {
1010   cerr << "[" << dwarf::TagString(getTag()) << "] ";
1011   cerr << std::hex << "[GV:" << GV << "]" << std::dec;
1012 }
1013
1014 /// dump - print compile unit.
1015 void DICompileUnit::dump() const {
1016   if (getLanguage())
1017     cerr << " [" << dwarf::LanguageString(getLanguage()) << "] ";
1018
1019   std::string Res1, Res2;
1020   cerr << " [" << getDirectory(Res1) << "/" << getFilename(Res2) << " ]";
1021 }
1022
1023 /// dump - print type.
1024 void DIType::dump() const {
1025   if (isNull()) return;
1026
1027   std::string Res;
1028   if (!getName(Res).empty())
1029     cerr << " [" << Res << "] ";
1030
1031   unsigned Tag = getTag();
1032   cerr << " [" << dwarf::TagString(Tag) << "] ";
1033
1034   // TODO : Print context
1035   getCompileUnit().dump();
1036   cerr << " [" 
1037        << getLineNumber() << ", " 
1038        << getSizeInBits() << ", "
1039        << getAlignInBits() << ", "
1040        << getOffsetInBits() 
1041        << "] ";
1042
1043   if (isPrivate()) 
1044     cerr << " [private] ";
1045   else if (isProtected())
1046     cerr << " [protected] ";
1047
1048   if (isForwardDecl())
1049     cerr << " [fwd] ";
1050
1051   if (isBasicType(Tag))
1052     DIBasicType(GV).dump();
1053   else if (isDerivedType(Tag))
1054     DIDerivedType(GV).dump();
1055   else if (isCompositeType(Tag))
1056     DICompositeType(GV).dump();
1057   else {
1058     cerr << "Invalid DIType\n";
1059     return;
1060   }
1061
1062   cerr << "\n";
1063 }
1064
1065 /// dump - print basic type.
1066 void DIBasicType::dump() const {
1067   cerr << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
1068 }
1069
1070 /// dump - print derived type.
1071 void DIDerivedType::dump() const {
1072   cerr << "\n\t Derived From: "; getTypeDerivedFrom().dump();
1073 }
1074
1075 /// dump - print composite type.
1076 void DICompositeType::dump() const {
1077   DIArray A = getTypeArray();
1078   if (A.isNull())
1079     return;
1080   cerr << " [" << A.getNumElements() << " elements]";
1081 }
1082
1083 /// dump - print global.
1084 void DIGlobal::dump() const {
1085   std::string Res;
1086   if (!getName(Res).empty())
1087     cerr << " [" << Res << "] ";
1088
1089   unsigned Tag = getTag();
1090   cerr << " [" << dwarf::TagString(Tag) << "] ";
1091
1092   // TODO : Print context
1093   getCompileUnit().dump();
1094   cerr << " [" << getLineNumber() << "] ";
1095
1096   if (isLocalToUnit())
1097     cerr << " [local] ";
1098
1099   if (isDefinition())
1100     cerr << " [def] ";
1101
1102   if (isGlobalVariable(Tag))
1103     DIGlobalVariable(GV).dump();
1104
1105   cerr << "\n";
1106 }
1107
1108 /// dump - print subprogram.
1109 void DISubprogram::dump() const {
1110   DIGlobal::dump();
1111 }
1112
1113 /// dump - print subprogram.
1114 void DIInlinedSubprogram::dump() const {
1115   DIGlobal::dump();
1116 }
1117
1118 /// dump - print global variable.
1119 void DIGlobalVariable::dump() const {
1120   cerr << " ["; getGlobal()->dump(); cerr << "] ";
1121 }
1122
1123 /// dump - print variable.
1124 void DIVariable::dump() const {
1125   std::string Res;
1126   if (!getName(Res).empty())
1127     cerr << " [" << Res << "] ";
1128
1129   getCompileUnit().dump();
1130   cerr << " [" << getLineNumber() << "] ";
1131   getType().dump();
1132   cerr << "\n";
1133 }