]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/CodeGen/CGDebugInfo.cpp
Import Clang, at r72805.
[FreeBSD/FreeBSD.git] / lib / CodeGen / CGDebugInfo.cpp
1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
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 coordinates the debug information generation while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CGDebugInfo.h"
15 #include "CodeGenModule.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/RecordLayout.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/FileManager.h"
22 #include "clang/Frontend/CompileOptions.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/Module.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/System/Path.h"
32 #include "llvm/Target/TargetMachine.h"
33 using namespace clang;
34 using namespace clang::CodeGen;
35
36 CGDebugInfo::CGDebugInfo(CodeGenModule *m)
37   : M(m), isMainCompileUnitCreated(false), DebugFactory(M->getModule()),
38     BlockLiteralGenericSet(false) {
39 }
40
41 CGDebugInfo::~CGDebugInfo() {
42   assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
43 }
44
45 void CGDebugInfo::setLocation(SourceLocation Loc) {
46   if (Loc.isValid())
47     CurLoc = M->getContext().getSourceManager().getInstantiationLoc(Loc);
48 }
49
50 /// getOrCreateCompileUnit - Get the compile unit from the cache or create a new
51 /// one if necessary. This returns null for invalid source locations.
52 llvm::DICompileUnit CGDebugInfo::getOrCreateCompileUnit(SourceLocation Loc) {
53   // Get source file information.
54   const char *FileName =  "<unknown>";
55   SourceManager &SM = M->getContext().getSourceManager();
56   unsigned FID = 0;
57   if (Loc.isValid()) {
58     PresumedLoc PLoc = SM.getPresumedLoc(Loc);
59     FileName = PLoc.getFilename();
60     FID = PLoc.getIncludeLoc().getRawEncoding();
61   }
62    
63   // See if this compile unit has been used before.
64   llvm::DICompileUnit &Unit = CompileUnitCache[FID];
65   if (!Unit.isNull()) return Unit;
66
67   // Get absolute path name.
68   llvm::sys::Path AbsFileName(FileName);
69   if (!AbsFileName.isAbsolute()) {
70     llvm::sys::Path tmp = llvm::sys::Path::GetCurrentDirectory();
71     tmp.appendComponent(FileName);
72     AbsFileName = tmp;
73   }
74
75   // See if thie compile unit is representing main source file. Each source
76   // file has corresponding compile unit. There is only one main source
77   // file at a time.
78   bool isMain = false;
79   const LangOptions &LO = M->getLangOptions();
80   const char *MainFileName = LO.getMainFileName();
81   if (isMainCompileUnitCreated == false) {
82     if (MainFileName) {
83       if (!strcmp(AbsFileName.getLast().c_str(), MainFileName))
84         isMain = true;
85     } else {
86       if (Loc.isValid() && SM.isFromMainFile(Loc))
87         isMain = true;
88     }
89     if (isMain)
90       isMainCompileUnitCreated = true;
91   }
92
93   unsigned LangTag;
94   if (LO.CPlusPlus) {
95     if (LO.ObjC1)
96       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
97     else
98       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
99   } else if (LO.ObjC1) {
100     LangTag = llvm::dwarf::DW_LANG_ObjC;
101   } else if (LO.C99) {
102     LangTag = llvm::dwarf::DW_LANG_C99;
103   } else {
104     LangTag = llvm::dwarf::DW_LANG_C89;
105   }
106
107   std::string Producer = "clang 1.0";// FIXME: clang version.
108   bool isOptimized = LO.Optimize;
109   const char *Flags = "";   // FIXME: Encode command line options.
110
111   // Figure out which version of the ObjC runtime we have.
112   unsigned RuntimeVers = 0;
113   if (LO.ObjC1)
114     RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
115   
116   // Create new compile unit.
117   return Unit = DebugFactory.CreateCompileUnit(LangTag, AbsFileName.getLast(),
118                                                AbsFileName.getDirname(), 
119                                                Producer, isMain, isOptimized,
120                                                Flags, RuntimeVers);
121 }
122
123 /// CreateType - Get the Basic type from the cache or create a new
124 /// one if necessary.
125 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
126                                      llvm::DICompileUnit Unit) {
127   unsigned Encoding = 0;
128   switch (BT->getKind()) {
129   default:
130   case BuiltinType::Void:
131     return llvm::DIType();
132   case BuiltinType::UChar:
133   case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
134   case BuiltinType::Char_S:
135   case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
136   case BuiltinType::UShort:
137   case BuiltinType::UInt:
138   case BuiltinType::ULong:
139   case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
140   case BuiltinType::Short:
141   case BuiltinType::Int:
142   case BuiltinType::Long:
143   case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
144   case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
145   case BuiltinType::Float:
146   case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
147   } 
148   // Bit size, align and offset of the type.
149   uint64_t Size = M->getContext().getTypeSize(BT);
150   uint64_t Align = M->getContext().getTypeAlign(BT);
151   uint64_t Offset = 0;
152   
153   return DebugFactory.CreateBasicType(Unit, 
154                       BT->getName(M->getContext().getLangOptions().CPlusPlus),
155                                       Unit, 0, Size, Align,
156                                       Offset, /*flags*/ 0, Encoding);
157 }
158
159 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty,
160                                      llvm::DICompileUnit Unit) {
161   // Bit size, align and offset of the type.
162   unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
163   if (Ty->isComplexIntegerType())
164     Encoding = llvm::dwarf::DW_ATE_lo_user;
165   
166   uint64_t Size = M->getContext().getTypeSize(Ty);
167   uint64_t Align = M->getContext().getTypeAlign(Ty);
168   uint64_t Offset = 0;
169   
170   return DebugFactory.CreateBasicType(Unit, "complex",
171                                       Unit, 0, Size, Align,
172                                       Offset, /*flags*/ 0, Encoding);
173 }
174
175 /// getOrCreateCVRType - Get the CVR qualified type from the cache or create 
176 /// a new one if necessary.
177 llvm::DIType CGDebugInfo::CreateCVRType(QualType Ty, llvm::DICompileUnit Unit) {
178   // We will create one Derived type for one qualifier and recurse to handle any
179   // additional ones.
180   llvm::DIType FromTy;
181   unsigned Tag;
182   if (Ty.isConstQualified()) {
183     Tag = llvm::dwarf::DW_TAG_const_type;
184     Ty.removeConst(); 
185     FromTy = getOrCreateType(Ty, Unit);
186   } else if (Ty.isVolatileQualified()) {
187     Tag = llvm::dwarf::DW_TAG_volatile_type;
188     Ty.removeVolatile(); 
189     FromTy = getOrCreateType(Ty, Unit);
190   } else {
191     assert(Ty.isRestrictQualified() && "Unknown type qualifier for debug info");
192     Tag = llvm::dwarf::DW_TAG_restrict_type;
193     Ty.removeRestrict(); 
194     FromTy = getOrCreateType(Ty, Unit);
195   }
196   
197   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
198   // CVR derived types.
199   return DebugFactory.CreateDerivedType(Tag, Unit, "", llvm::DICompileUnit(),
200                                         0, 0, 0, 0, 0, FromTy);
201 }
202
203 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
204                                      llvm::DICompileUnit Unit) {
205   llvm::DIType EltTy = getOrCreateType(Ty->getPointeeType(), Unit);
206  
207   // Bit size, align and offset of the type.
208   uint64_t Size = M->getContext().getTypeSize(Ty);
209   uint64_t Align = M->getContext().getTypeAlign(Ty);
210                                                                                
211   return DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
212                                         "", llvm::DICompileUnit(),
213                                         0, Size, Align, 0, 0, EltTy);
214 }
215
216 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
217                                      llvm::DICompileUnit Unit) {
218   if (BlockLiteralGenericSet)
219     return BlockLiteralGeneric;
220
221   llvm::DICompileUnit DefUnit;
222   unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
223
224   llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
225
226   llvm::DIType FieldTy;
227
228   QualType FType;
229   uint64_t FieldSize, FieldOffset;
230   unsigned FieldAlign;
231
232   llvm::DIArray Elements;
233   llvm::DIType EltTy, DescTy;
234
235   FieldOffset = 0;
236   FType = M->getContext().UnsignedLongTy;
237   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
238   FieldSize = M->getContext().getTypeSize(FType);
239   FieldAlign = M->getContext().getTypeAlign(FType);
240   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
241                                            "reserved", DefUnit,
242                                            0, FieldSize, FieldAlign,
243                                            FieldOffset, 0, FieldTy);
244   EltTys.push_back(FieldTy);
245
246   FieldOffset += FieldSize;
247   FType = M->getContext().UnsignedLongTy;
248   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
249   FieldSize = M->getContext().getTypeSize(FType);
250   FieldAlign = M->getContext().getTypeAlign(FType);
251   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
252                                            "Size", DefUnit,
253                                            0, FieldSize, FieldAlign,
254                                            FieldOffset, 0, FieldTy);
255   EltTys.push_back(FieldTy);
256
257   FieldOffset += FieldSize;
258   Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
259   EltTys.clear();
260
261   EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor",
262                                            DefUnit, 0, FieldOffset, 0, 0, 0,
263                                            llvm::DIType(), Elements);
264   
265   // Bit size, align and offset of the type.
266   uint64_t Size = M->getContext().getTypeSize(Ty);
267   uint64_t Align = M->getContext().getTypeAlign(Ty);
268                                                                                
269   DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
270                                           Unit, "", llvm::DICompileUnit(),
271                                           0, Size, Align, 0, 0, EltTy);
272
273   FieldOffset = 0;
274   FType = M->getContext().getPointerType(M->getContext().VoidTy);
275   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
276   FieldSize = M->getContext().getTypeSize(FType);
277   FieldAlign = M->getContext().getTypeAlign(FType);
278   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
279                                            "__isa", DefUnit,
280                                            0, FieldSize, FieldAlign,
281                                            FieldOffset, 0, FieldTy);
282   EltTys.push_back(FieldTy);
283
284   FieldOffset += FieldSize;
285   FType = M->getContext().IntTy;
286   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
287   FieldSize = M->getContext().getTypeSize(FType);
288   FieldAlign = M->getContext().getTypeAlign(FType);
289   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
290                                            "__flags", DefUnit,
291                                            0, FieldSize, FieldAlign,
292                                            FieldOffset, 0, FieldTy);
293   EltTys.push_back(FieldTy);
294
295   FieldOffset += FieldSize;
296   FType = M->getContext().IntTy;
297   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
298   FieldSize = M->getContext().getTypeSize(FType);
299   FieldAlign = M->getContext().getTypeAlign(FType);
300   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
301                                            "__reserved", DefUnit,
302                                            0, FieldSize, FieldAlign,
303                                            FieldOffset, 0, FieldTy);
304   EltTys.push_back(FieldTy);
305
306   FieldOffset += FieldSize;
307   FType = M->getContext().getPointerType(M->getContext().VoidTy);
308   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
309   FieldSize = M->getContext().getTypeSize(FType);
310   FieldAlign = M->getContext().getTypeAlign(FType);
311   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
312                                            "__FuncPtr", DefUnit,
313                                            0, FieldSize, FieldAlign,
314                                            FieldOffset, 0, FieldTy);
315   EltTys.push_back(FieldTy);
316
317   FieldOffset += FieldSize;
318   FType = M->getContext().getPointerType(M->getContext().VoidTy);
319   FieldTy = DescTy;
320   FieldSize = M->getContext().getTypeSize(Ty);
321   FieldAlign = M->getContext().getTypeAlign(Ty);
322   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
323                                            "__descriptor", DefUnit,
324                                            0, FieldSize, FieldAlign,
325                                            FieldOffset, 0, FieldTy);
326   EltTys.push_back(FieldTy);
327
328   FieldOffset += FieldSize;
329   Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
330
331   EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic",
332                                            DefUnit, 0, FieldOffset, 0, 0, 0,
333                                            llvm::DIType(), Elements);
334   
335   BlockLiteralGenericSet = true;
336   BlockLiteralGeneric
337     = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
338                                      "", llvm::DICompileUnit(),
339                                      0, Size, Align, 0, 0, EltTy);
340   return BlockLiteralGeneric;
341 }
342
343 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
344                                      llvm::DICompileUnit Unit) {
345   // Typedefs are derived from some other type.  If we have a typedef of a
346   // typedef, make sure to emit the whole chain.
347   llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
348   
349   // We don't set size information, but do specify where the typedef was
350   // declared.
351   std::string TyName = Ty->getDecl()->getNameAsString();
352   SourceLocation DefLoc = Ty->getDecl()->getLocation();
353   llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc);
354
355   SourceManager &SM = M->getContext().getSourceManager();
356   PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
357   unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
358
359   return DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef, Unit,
360                                         TyName, DefUnit, Line, 0, 0, 0, 0, Src);
361 }
362
363 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
364                                      llvm::DICompileUnit Unit) {
365   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
366
367   // Add the result type at least.
368   EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
369   
370   // Set up remainder of arguments if there is a prototype.
371   // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
372   if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
373     for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
374       EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
375   } else {
376     // FIXME: Handle () case in C.  llvm-gcc doesn't do it either.
377   }
378
379   llvm::DIArray EltTypeArray =
380     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
381   
382   return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
383                                           Unit, "", llvm::DICompileUnit(),
384                                           0, 0, 0, 0, 0,
385                                           llvm::DIType(), EltTypeArray);
386 }
387
388 /// CreateType - get structure or union type.
389 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
390                                      llvm::DICompileUnit Unit) {
391   RecordDecl *Decl = Ty->getDecl();
392   
393   unsigned Tag;
394   if (Decl->isStruct())
395     Tag = llvm::dwarf::DW_TAG_structure_type;
396   else if (Decl->isUnion())
397     Tag = llvm::dwarf::DW_TAG_union_type;
398   else {
399     assert(Decl->isClass() && "Unknown RecordType!");
400     Tag = llvm::dwarf::DW_TAG_class_type;
401   }
402
403   SourceManager &SM = M->getContext().getSourceManager();
404
405   // Get overall information about the record type for the debug info.
406   std::string Name = Decl->getNameAsString();
407
408   PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
409   llvm::DICompileUnit DefUnit;
410   unsigned Line = 0;
411   if (!PLoc.isInvalid()) {
412     DefUnit = getOrCreateCompileUnit(Decl->getLocation());
413     Line = PLoc.getLine();
414   }
415   
416   // Records and classes and unions can all be recursive.  To handle them, we
417   // first generate a debug descriptor for the struct as a forward declaration.
418   // Then (if it is a definition) we go through and get debug info for all of
419   // its members.  Finally, we create a descriptor for the complete type (which
420   // may refer to the forward decl if the struct is recursive) and replace all
421   // uses of the forward declaration with the final definition.
422   llvm::DIType FwdDecl =
423     DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, 0, 0, 0, 0,
424                                      llvm::DIType(), llvm::DIArray());
425   
426   // If this is just a forward declaration, return it.
427   if (!Decl->getDefinition(M->getContext()))
428     return FwdDecl;
429
430   // Otherwise, insert it into the TypeCache so that recursive uses will find
431   // it.
432   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
433
434   // Convert all the elements.
435   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
436
437   const ASTRecordLayout &RL = M->getContext().getASTRecordLayout(Decl);
438
439   unsigned FieldNo = 0;
440   for (RecordDecl::field_iterator I = Decl->field_begin(M->getContext()),
441                                   E = Decl->field_end(M->getContext()); 
442        I != E; ++I, ++FieldNo) {
443     FieldDecl *Field = *I;
444     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
445
446     std::string FieldName = Field->getNameAsString();
447
448     // Ignore unnamed fields.
449     if (FieldName.empty())
450       continue;
451
452     // Get the location for the field.
453     SourceLocation FieldDefLoc = Field->getLocation();
454     PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
455     llvm::DICompileUnit FieldDefUnit;
456     unsigned FieldLine = 0;
457     
458     if (!PLoc.isInvalid()) {
459       FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc);
460       FieldLine = PLoc.getLine();
461     }
462
463     QualType FType = Field->getType();
464     uint64_t FieldSize = 0;
465     unsigned FieldAlign = 0;
466     if (!FType->isIncompleteArrayType()) {
467     
468       // Bit size, align and offset of the type.
469       FieldSize = M->getContext().getTypeSize(FType);
470       Expr *BitWidth = Field->getBitWidth();
471       if (BitWidth)
472         FieldSize = BitWidth->EvaluateAsInt(M->getContext()).getZExtValue();
473       
474       FieldAlign =  M->getContext().getTypeAlign(FType);
475     }
476
477     uint64_t FieldOffset = RL.getFieldOffset(FieldNo);    
478     
479     // Create a DW_TAG_member node to remember the offset of this field in the
480     // struct.  FIXME: This is an absolutely insane way to capture this
481     // information.  When we gut debug info, this should be fixed.
482     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
483                                              FieldName, FieldDefUnit,
484                                              FieldLine, FieldSize, FieldAlign,
485                                              FieldOffset, 0, FieldTy);
486     EltTys.push_back(FieldTy);
487   }
488   
489   llvm::DIArray Elements =
490     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
491
492   // Bit size, align and offset of the type.
493   uint64_t Size = M->getContext().getTypeSize(Ty);
494   uint64_t Align = M->getContext().getTypeAlign(Ty);
495   
496   llvm::DIType RealDecl =
497     DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, Size,
498                                      Align, 0, 0, llvm::DIType(), Elements);
499
500   // Now that we have a real decl for the struct, replace anything using the
501   // old decl with the new one.  This will recursively update the debug info.
502   FwdDecl.getGV()->replaceAllUsesWith(RealDecl.getGV());
503   FwdDecl.getGV()->eraseFromParent();
504   
505   return RealDecl;
506 }
507
508 /// CreateType - get objective-c interface type.
509 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
510                                      llvm::DICompileUnit Unit) {
511   ObjCInterfaceDecl *Decl = Ty->getDecl();
512   
513   unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
514   SourceManager &SM = M->getContext().getSourceManager();
515
516   // Get overall information about the record type for the debug info.
517   std::string Name = Decl->getNameAsString();
518
519   llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(Decl->getLocation());
520   PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
521   unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
522
523   
524   unsigned RuntimeLang = DefUnit.getLanguage();
525
526   // To handle recursive interface, we
527   // first generate a debug descriptor for the struct as a forward declaration.
528   // Then (if it is a definition) we go through and get debug info for all of
529   // its members.  Finally, we create a descriptor for the complete type (which
530   // may refer to the forward decl if the struct is recursive) and replace all
531   // uses of the forward declaration with the final definition.
532   llvm::DIType FwdDecl =
533     DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, 0, 0, 0, 0,
534                                      llvm::DIType(), llvm::DIArray(),
535                                      RuntimeLang);
536   
537   // If this is just a forward declaration, return it.
538   if (Decl->isForwardDecl())
539     return FwdDecl;
540
541   // Otherwise, insert it into the TypeCache so that recursive uses will find
542   // it.
543   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
544
545   // Convert all the elements.
546   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
547
548   ObjCInterfaceDecl *SClass = Decl->getSuperClass();
549   if (SClass) {
550     llvm::DIType SClassTy = 
551       getOrCreateType(M->getContext().getObjCInterfaceType(SClass), Unit);
552     llvm::DIType InhTag = 
553       DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
554                                      Unit, "", llvm::DICompileUnit(), 0, 0, 0,
555                                      0 /* offset */, 0, SClassTy);
556     EltTys.push_back(InhTag);
557   }
558
559   const ASTRecordLayout &RL = M->getContext().getASTObjCInterfaceLayout(Decl);
560
561   unsigned FieldNo = 0;
562   for (ObjCInterfaceDecl::ivar_iterator I = Decl->ivar_begin(),
563          E = Decl->ivar_end();  I != E; ++I, ++FieldNo) {
564     ObjCIvarDecl *Field = *I;
565     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
566
567     std::string FieldName = Field->getNameAsString();
568
569     // Ignore unnamed fields.
570     if (FieldName.empty())
571       continue;
572
573     // Get the location for the field.
574     SourceLocation FieldDefLoc = Field->getLocation();
575     llvm::DICompileUnit FieldDefUnit = getOrCreateCompileUnit(FieldDefLoc);
576     PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
577     unsigned FieldLine = PLoc.isInvalid() ? 0 : PLoc.getLine();
578
579  
580     QualType FType = Field->getType();
581     uint64_t FieldSize = 0;
582     unsigned FieldAlign = 0;
583
584     if (!FType->isIncompleteArrayType()) {
585     
586       // Bit size, align and offset of the type.
587       FieldSize = M->getContext().getTypeSize(FType);
588       Expr *BitWidth = Field->getBitWidth();
589       if (BitWidth)
590         FieldSize = BitWidth->EvaluateAsInt(M->getContext()).getZExtValue();
591
592       FieldAlign =  M->getContext().getTypeAlign(FType);
593     }
594
595     uint64_t FieldOffset = RL.getFieldOffset(FieldNo);    
596     
597     unsigned Flags = 0;
598     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
599       Flags = llvm::DIType::FlagProtected;
600     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
601       Flags = llvm::DIType::FlagPrivate;
602       
603     // Create a DW_TAG_member node to remember the offset of this field in the
604     // struct.  FIXME: This is an absolutely insane way to capture this
605     // information.  When we gut debug info, this should be fixed.
606     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
607                                              FieldName, FieldDefUnit,
608                                              FieldLine, FieldSize, FieldAlign,
609                                              FieldOffset, Flags, FieldTy);
610     EltTys.push_back(FieldTy);
611   }
612   
613   llvm::DIArray Elements =
614     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
615
616   // Bit size, align and offset of the type.
617   uint64_t Size = M->getContext().getTypeSize(Ty);
618   uint64_t Align = M->getContext().getTypeAlign(Ty);
619   
620   llvm::DIType RealDecl =
621     DebugFactory.CreateCompositeType(Tag, Unit, Name, DefUnit, Line, Size,
622                                      Align, 0, 0, llvm::DIType(), Elements,
623                                      RuntimeLang);
624
625   // Now that we have a real decl for the struct, replace anything using the
626   // old decl with the new one.  This will recursively update the debug info.
627   FwdDecl.getGV()->replaceAllUsesWith(RealDecl.getGV());
628   FwdDecl.getGV()->eraseFromParent();
629   
630   return RealDecl;
631 }
632
633 llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
634                                      llvm::DICompileUnit Unit) {
635   EnumDecl *Decl = Ty->getDecl();
636
637   llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
638
639   // Create DIEnumerator elements for each enumerator.
640   for (EnumDecl::enumerator_iterator 
641          Enum = Decl->enumerator_begin(M->getContext()),
642          EnumEnd = Decl->enumerator_end(M->getContext());
643        Enum != EnumEnd; ++Enum) {
644     Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getNameAsString(),
645                                             Enum->getInitVal().getZExtValue()));
646   }
647   
648   // Return a CompositeType for the enum itself.
649   llvm::DIArray EltArray =
650     DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
651
652   std::string EnumName = Decl->getNameAsString();
653   SourceLocation DefLoc = Decl->getLocation();
654   llvm::DICompileUnit DefUnit = getOrCreateCompileUnit(DefLoc);
655   SourceManager &SM = M->getContext().getSourceManager();
656   PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
657   unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
658
659   
660   // Size and align of the type.
661   uint64_t Size = 0;
662   unsigned Align = 0;
663   if (!Ty->isIncompleteType()) {
664     Size = M->getContext().getTypeSize(Ty);
665     Align = M->getContext().getTypeAlign(Ty);
666   }
667   
668   return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
669                                           Unit, EnumName, DefUnit, Line,
670                                           Size, Align, 0, 0,
671                                           llvm::DIType(), EltArray);
672 }
673
674 llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
675                                      llvm::DICompileUnit Unit) {
676   if (const RecordType *RT = dyn_cast<RecordType>(Ty))
677     return CreateType(RT, Unit);
678   else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
679     return CreateType(ET, Unit);
680   
681   return llvm::DIType();
682 }
683
684 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
685                                      llvm::DICompileUnit Unit) {
686   uint64_t Size;
687   uint64_t Align;
688   
689   
690   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
691   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
692     Size = 0;
693     Align =
694       M->getContext().getTypeAlign(M->getContext().getBaseElementType(VAT));
695   } else if (Ty->isIncompleteArrayType()) {
696     Size = 0;
697     Align = M->getContext().getTypeAlign(Ty->getElementType());
698   } else {
699     // Size and align of the whole array, not the element type.
700     Size = M->getContext().getTypeSize(Ty);
701     Align = M->getContext().getTypeAlign(Ty);
702   }
703   
704   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
705   // interior arrays, do we care?  Why aren't nested arrays represented the
706   // obvious/recursive way?
707   llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
708   QualType EltTy(Ty, 0);
709   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
710     uint64_t Upper = 0;
711     if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
712       Upper = CAT->getSize().getZExtValue() - 1;
713     // FIXME: Verify this is right for VLAs.
714     Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
715     EltTy = Ty->getElementType();
716   }
717   
718   llvm::DIArray SubscriptArray =
719     DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
720
721   return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
722                                           Unit, "", llvm::DICompileUnit(),
723                                           0, Size, Align, 0, 0,
724                                           getOrCreateType(EltTy, Unit),
725                                           SubscriptArray);
726 }
727
728
729 /// getOrCreateType - Get the type from the cache or create a new
730 /// one if necessary.
731 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
732                                           llvm::DICompileUnit Unit) {
733   if (Ty.isNull())
734     return llvm::DIType();
735   
736   // Check to see if the compile unit already has created this type.
737   llvm::DIType &Slot = TypeCache[Ty.getAsOpaquePtr()];
738   if (!Slot.isNull()) return Slot;
739
740   // Handle CVR qualifiers, which recursively handles what they refer to.
741   if (Ty.getCVRQualifiers())
742     return Slot = CreateCVRType(Ty, Unit);
743
744   // Work out details of type.
745   switch (Ty->getTypeClass()) {
746 #define TYPE(Class, Base)
747 #define ABSTRACT_TYPE(Class, Base)
748 #define NON_CANONICAL_TYPE(Class, Base)
749 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
750 #include "clang/AST/TypeNodes.def"
751     assert(false && "Dependent types cannot show up in debug information");
752     
753   case Type::LValueReference:
754   case Type::RValueReference:
755   case Type::Vector:
756   case Type::ExtVector:
757   case Type::ExtQual:
758   case Type::FixedWidthInt:
759   case Type::MemberPointer:
760   case Type::TemplateSpecialization:
761   case Type::QualifiedName:
762     // Unsupported types
763     return llvm::DIType();
764   case Type::ObjCQualifiedId:   // Encode id<p> in debug info just like id.
765     return Slot = getOrCreateType(M->getContext().getObjCIdType(), Unit);
766       
767   case Type::ObjCQualifiedInterface:  // Drop protocols from interface.
768   case Type::ObjCInterface: 
769     return Slot = CreateType(cast<ObjCInterfaceType>(Ty), Unit);
770   case Type::Builtin: return Slot = CreateType(cast<BuiltinType>(Ty), Unit);
771   case Type::Complex: return Slot = CreateType(cast<ComplexType>(Ty), Unit);
772   case Type::Pointer: return Slot = CreateType(cast<PointerType>(Ty), Unit);
773   case Type::BlockPointer:
774     return Slot = CreateType(cast<BlockPointerType>(Ty), Unit);
775   case Type::Typedef: return Slot = CreateType(cast<TypedefType>(Ty), Unit);
776   case Type::Record:
777   case Type::Enum:
778     return Slot = CreateType(cast<TagType>(Ty), Unit); 
779   case Type::FunctionProto:
780   case Type::FunctionNoProto:
781     return Slot = CreateType(cast<FunctionType>(Ty), Unit);
782     
783   case Type::ConstantArray:
784   case Type::VariableArray:
785   case Type::IncompleteArray:
786     return Slot = CreateType(cast<ArrayType>(Ty), Unit);
787   case Type::TypeOfExpr:
788     return Slot = getOrCreateType(cast<TypeOfExprType>(Ty)->getUnderlyingExpr()
789                                   ->getType(), Unit);
790   case Type::TypeOf:
791     return Slot = getOrCreateType(cast<TypeOfType>(Ty)->getUnderlyingType(),
792                                   Unit);
793   }
794   
795   return Slot;
796 }
797
798 /// EmitFunctionStart - Constructs the debug code for entering a function -
799 /// "llvm.dbg.func.start.".
800 void CGDebugInfo::EmitFunctionStart(const char *Name, QualType ReturnType,
801                                     llvm::Function *Fn,
802                                     CGBuilderTy &Builder) {
803   const char *LinkageName = Name;
804   
805   // Skip the asm prefix if it exists.
806   //
807   // FIXME: This should probably be the unmangled name?
808   if (Name[0] == '\01')
809     ++Name;
810   
811   // FIXME: Why is this using CurLoc???
812   llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
813   SourceManager &SM = M->getContext().getSourceManager();
814   unsigned LineNo = SM.getPresumedLoc(CurLoc).getLine();
815   
816   llvm::DISubprogram SP =
817     DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
818                                   getOrCreateType(ReturnType, Unit),
819                                   Fn->hasInternalLinkage(), true/*definition*/);
820   
821   DebugFactory.InsertSubprogramStart(SP, Builder.GetInsertBlock());
822                                                         
823   // Push function on region stack.
824   RegionStack.push_back(SP);
825 }
826
827
828 void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) {
829   if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
830   
831   // Don't bother if things are the same as last time.
832   SourceManager &SM = M->getContext().getSourceManager();
833   if (CurLoc == PrevLoc 
834        || (SM.getInstantiationLineNumber(CurLoc) ==
835            SM.getInstantiationLineNumber(PrevLoc)
836            && SM.isFromSameFile(CurLoc, PrevLoc)))
837     return;
838
839   // Update last state.
840   PrevLoc = CurLoc;
841
842   // Get the appropriate compile unit.
843   llvm::DICompileUnit Unit = getOrCreateCompileUnit(CurLoc);
844   PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
845   DebugFactory.InsertStopPoint(Unit, PLoc.getLine(), PLoc.getColumn(),
846                                Builder.GetInsertBlock()); 
847 }
848
849 /// EmitRegionStart- Constructs the debug code for entering a declarative
850 /// region - "llvm.dbg.region.start.".
851 void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) {
852   llvm::DIDescriptor D;
853   if (!RegionStack.empty())
854     D = RegionStack.back();
855   D = DebugFactory.CreateBlock(D);
856   RegionStack.push_back(D);
857   DebugFactory.InsertRegionStart(D, Builder.GetInsertBlock());
858 }
859
860 /// EmitRegionEnd - Constructs the debug code for exiting a declarative
861 /// region - "llvm.dbg.region.end."
862 void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) {
863   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
864
865   // Provide an region stop point.
866   EmitStopPoint(Fn, Builder);
867   
868   DebugFactory.InsertRegionEnd(RegionStack.back(), Builder.GetInsertBlock());
869   RegionStack.pop_back();
870 }
871
872 /// EmitDeclare - Emit local variable declaration debug info.
873 void CGDebugInfo::EmitDeclare(const VarDecl *Decl, unsigned Tag,
874                               llvm::Value *Storage, CGBuilderTy &Builder) {
875   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
876
877   // Do not emit variable debug information while generating optimized code.
878   // The llvm optimizer and code generator are not yet ready to support
879   // optimized code debugging.
880   const CompileOptions &CO = M->getCompileOpts();
881   if (CO.OptimizationLevel)
882     return;
883
884   llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
885   llvm::DIType Ty = getOrCreateType(Decl->getType(), Unit);
886
887   // Get location information.
888   SourceManager &SM = M->getContext().getSourceManager();
889   PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
890   unsigned Line = 0;
891   if (!PLoc.isInvalid())
892     Line = PLoc.getLine();
893   else
894     Unit = llvm::DICompileUnit();
895
896   
897   // Create the descriptor for the variable.
898   llvm::DIVariable D = 
899     DebugFactory.CreateVariable(Tag, RegionStack.back(),Decl->getNameAsString(),
900                                 Unit, Line, Ty);
901   // Insert an llvm.dbg.declare into the current block.
902   DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
903 }
904
905 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *Decl,
906                                             llvm::Value *Storage,
907                                             CGBuilderTy &Builder) {
908   EmitDeclare(Decl, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
909 }
910
911 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
912 /// variable declaration.
913 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI,
914                                            CGBuilderTy &Builder) {
915   EmitDeclare(Decl, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
916 }
917
918
919
920 /// EmitGlobalVariable - Emit information about a global variable.
921 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 
922                                      const VarDecl *Decl) {
923
924   // Do not emit variable debug information while generating optimized code.
925   // The llvm optimizer and code generator are not yet ready to support
926   // optimized code debugging.
927   const CompileOptions &CO = M->getCompileOpts();
928   if (CO.OptimizationLevel)
929     return;
930
931   // Create global variable debug descriptor.
932   llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
933   SourceManager &SM = M->getContext().getSourceManager();
934   PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
935   unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
936
937   std::string Name = Decl->getNameAsString();
938
939   QualType T = Decl->getType();
940   if (T->isIncompleteArrayType()) {
941     
942     // CodeGen turns int[] into int[1] so we'll do the same here.
943     llvm::APSInt ConstVal(32);
944     
945     ConstVal = 1;
946     QualType ET = M->getContext().getAsArrayType(T)->getElementType();
947     
948     T = M->getContext().getConstantArrayType(ET, ConstVal, 
949                                            ArrayType::Normal, 0);
950   }
951
952   DebugFactory.CreateGlobalVariable(Unit, Name, Name, "", Unit, LineNo,
953                                     getOrCreateType(T, Unit),
954                                     Var->hasInternalLinkage(),
955                                     true/*definition*/, Var);
956 }
957
958 /// EmitGlobalVariable - Emit information about an objective-c interface.
959 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, 
960                                      ObjCInterfaceDecl *Decl) {
961   // Create global variable debug descriptor.
962   llvm::DICompileUnit Unit = getOrCreateCompileUnit(Decl->getLocation());
963   SourceManager &SM = M->getContext().getSourceManager();
964   PresumedLoc PLoc = SM.getPresumedLoc(Decl->getLocation());
965   unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
966
967   std::string Name = Decl->getNameAsString();
968
969   QualType T = M->getContext().getObjCInterfaceType(Decl);
970   if (T->isIncompleteArrayType()) {
971     
972     // CodeGen turns int[] into int[1] so we'll do the same here.
973     llvm::APSInt ConstVal(32);
974     
975     ConstVal = 1;
976     QualType ET = M->getContext().getAsArrayType(T)->getElementType();
977     
978     T = M->getContext().getConstantArrayType(ET, ConstVal, 
979                                            ArrayType::Normal, 0);
980   }
981
982   DebugFactory.CreateGlobalVariable(Unit, Name, Name, "", Unit, LineNo,
983                                     getOrCreateType(T, Unit),
984                                     Var->hasInternalLinkage(),
985                                     true/*definition*/, Var);
986 }
987