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