]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/CodeGen/CGDebugInfo.cpp
Update clang to r98631.
[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 "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/RecordLayout.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/FileManager.h"
23 #include "clang/Basic/Version.h"
24 #include "clang/CodeGen/CodeGenOptions.h"
25 #include "llvm/Constants.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Module.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/Support/Dwarf.h"
33 #include "llvm/System/Path.h"
34 #include "llvm/Target/TargetMachine.h"
35 using namespace clang;
36 using namespace clang::CodeGen;
37
38 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
39   : CGM(CGM), DebugFactory(CGM.getModule()),
40     FwdDeclCount(0), BlockLiteralGenericSet(false) {
41   CreateCompileUnit();
42 }
43
44 CGDebugInfo::~CGDebugInfo() {
45   assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
46 }
47
48 void CGDebugInfo::setLocation(SourceLocation Loc) {
49   if (Loc.isValid())
50     CurLoc = CGM.getContext().getSourceManager().getInstantiationLoc(Loc);
51 }
52
53 /// getContextDescriptor - Get context info for the decl.
54 llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context,
55                                               llvm::DIDescriptor &CompileUnit) {
56   if (!Context)
57     return CompileUnit;
58
59   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
60     I = RegionMap.find(Context);
61   if (I != RegionMap.end())
62     return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(I->second));
63
64   // Check namespace.
65   if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
66     return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl, CompileUnit));
67   
68   return CompileUnit;
69 }
70
71 /// getFunctionName - Get function name for the given FunctionDecl. If the
72 /// name is constructred on demand (e.g. C++ destructor) then the name
73 /// is stored on the side.
74 llvm::StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
75   assert (FD && "Invalid FunctionDecl!");
76   IdentifierInfo *FII = FD->getIdentifier();
77   if (FII)
78     return FII->getName();
79
80   // Otherwise construct human readable name for debug info.
81   std::string NS = FD->getNameAsString();
82
83   // Copy this name on the side and use its reference.
84   char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
85   memcpy(StrPtr, NS.data(), NS.length());
86   return llvm::StringRef(StrPtr, NS.length());
87 }
88
89 /// getOrCreateFile - Get the file debug info descriptor for the input location.
90 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
91   if (!Loc.isValid()) 
92     // If Location is not valid then use main input file.
93     return DebugFactory.CreateFile(TheCU.getFilename(), TheCU.getDirectory(),
94                                    TheCU);
95   SourceManager &SM = CGM.getContext().getSourceManager();
96   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
97   llvm::sys::Path AbsFileName(PLoc.getFilename());
98   AbsFileName.makeAbsolute();
99
100   return DebugFactory.CreateFile(AbsFileName.getLast(),
101                                  AbsFileName.getDirname(), TheCU);
102 }
103 /// CreateCompileUnit - Create new compile unit.
104 void CGDebugInfo::CreateCompileUnit() {
105
106   // Get absolute path name.
107   std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
108   if (MainFileName.empty())
109     MainFileName = "<unknown>";
110   llvm::sys::Path AbsFileName(MainFileName);
111   AbsFileName.makeAbsolute();
112
113   unsigned LangTag;
114   const LangOptions &LO = CGM.getLangOptions();
115   if (LO.CPlusPlus) {
116     if (LO.ObjC1)
117       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
118     else
119       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
120   } else if (LO.ObjC1) {
121     LangTag = llvm::dwarf::DW_LANG_ObjC;
122   } else if (LO.C99) {
123     LangTag = llvm::dwarf::DW_LANG_C99;
124   } else {
125     LangTag = llvm::dwarf::DW_LANG_C89;
126   }
127
128   const char *Producer =
129 #ifdef CLANG_VENDOR
130     CLANG_VENDOR
131 #endif
132     "clang " CLANG_VERSION_STRING;
133
134   // Figure out which version of the ObjC runtime we have.
135   unsigned RuntimeVers = 0;
136   if (LO.ObjC1)
137     RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
138
139   // Create new compile unit.
140   TheCU = DebugFactory.CreateCompileUnit(
141     LangTag, AbsFileName.getLast(), AbsFileName.getDirname(), Producer, true,
142     LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
143 }
144
145 /// CreateType - Get the Basic type from the cache or create a new
146 /// one if necessary.
147 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT,
148                                      llvm::DIFile Unit) {
149   unsigned Encoding = 0;
150   switch (BT->getKind()) {
151   default:
152   case BuiltinType::Void:
153     return llvm::DIType();
154   case BuiltinType::UChar:
155   case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
156   case BuiltinType::Char_S:
157   case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
158   case BuiltinType::UShort:
159   case BuiltinType::UInt:
160   case BuiltinType::ULong:
161   case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
162   case BuiltinType::Short:
163   case BuiltinType::Int:
164   case BuiltinType::Long:
165   case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
166   case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
167   case BuiltinType::Float:
168   case BuiltinType::LongDouble:
169   case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
170   }
171   // Bit size, align and offset of the type.
172   uint64_t Size = CGM.getContext().getTypeSize(BT);
173   uint64_t Align = CGM.getContext().getTypeAlign(BT);
174   uint64_t Offset = 0;
175
176   llvm::DIType DbgTy = 
177     DebugFactory.CreateBasicType(Unit,
178                                  BT->getName(CGM.getContext().getLangOptions()),
179                                  Unit, 0, Size, Align,
180                                  Offset, /*flags*/ 0, Encoding);
181   return DbgTy;
182 }
183
184 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty,
185                                      llvm::DIFile Unit) {
186   // Bit size, align and offset of the type.
187   unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
188   if (Ty->isComplexIntegerType())
189     Encoding = llvm::dwarf::DW_ATE_lo_user;
190
191   uint64_t Size = CGM.getContext().getTypeSize(Ty);
192   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
193   uint64_t Offset = 0;
194
195   llvm::DIType DbgTy = 
196     DebugFactory.CreateBasicType(Unit, "complex",
197                                  Unit, 0, Size, Align,
198                                  Offset, /*flags*/ 0, Encoding);
199   return DbgTy;
200 }
201
202 /// CreateCVRType - Get the qualified type from the cache or create
203 /// a new one if necessary.
204 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
205   QualifierCollector Qc;
206   const Type *T = Qc.strip(Ty);
207
208   // Ignore these qualifiers for now.
209   Qc.removeObjCGCAttr();
210   Qc.removeAddressSpace();
211
212   // We will create one Derived type for one qualifier and recurse to handle any
213   // additional ones.
214   unsigned Tag;
215   if (Qc.hasConst()) {
216     Tag = llvm::dwarf::DW_TAG_const_type;
217     Qc.removeConst();
218   } else if (Qc.hasVolatile()) {
219     Tag = llvm::dwarf::DW_TAG_volatile_type;
220     Qc.removeVolatile();
221   } else if (Qc.hasRestrict()) {
222     Tag = llvm::dwarf::DW_TAG_restrict_type;
223     Qc.removeRestrict();
224   } else {
225     assert(Qc.empty() && "Unknown type qualifier for debug info");
226     return getOrCreateType(QualType(T, 0), Unit);
227   }
228
229   llvm::DIType FromTy = getOrCreateType(Qc.apply(T), Unit);
230
231   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
232   // CVR derived types.
233   llvm::DIType DbgTy =
234     DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
235                                    0, 0, 0, 0, 0, FromTy);
236   return DbgTy;
237 }
238
239 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
240                                      llvm::DIFile Unit) {
241   llvm::DIType DbgTy =
242     CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 
243                           Ty->getPointeeType(), Unit);
244   return DbgTy;
245 }
246
247 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
248                                      llvm::DIFile Unit) {
249   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 
250                                Ty->getPointeeType(), Unit);
251 }
252
253 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
254                                                 const Type *Ty, 
255                                                 QualType PointeeTy,
256                                                 llvm::DIFile Unit) {
257   llvm::DIType EltTy = getOrCreateType(PointeeTy, Unit);
258
259   // Bit size, align and offset of the type.
260   
261   // Size is always the size of a pointer. We can't use getTypeSize here
262   // because that does not return the correct value for references.
263   uint64_t Size = 
264     CGM.getContext().Target.getPointerWidth(PointeeTy.getAddressSpace());
265   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
266
267   return
268     DebugFactory.CreateDerivedType(Tag, Unit, "", Unit,
269                                    0, Size, Align, 0, 0, EltTy);
270   
271 }
272
273 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
274                                      llvm::DIFile Unit) {
275   if (BlockLiteralGenericSet)
276     return BlockLiteralGeneric;
277
278   unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
279
280   llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
281
282   llvm::DIType FieldTy;
283
284   QualType FType;
285   uint64_t FieldSize, FieldOffset;
286   unsigned FieldAlign;
287
288   llvm::DIArray Elements;
289   llvm::DIType EltTy, DescTy;
290
291   FieldOffset = 0;
292   FType = CGM.getContext().UnsignedLongTy;
293   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
294   FieldSize = CGM.getContext().getTypeSize(FType);
295   FieldAlign = CGM.getContext().getTypeAlign(FType);
296   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
297                                            "reserved", Unit,
298                                            0, FieldSize, FieldAlign,
299                                            FieldOffset, 0, FieldTy);
300   EltTys.push_back(FieldTy);
301
302   FieldOffset += FieldSize;
303   FType = CGM.getContext().UnsignedLongTy;
304   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
305   FieldSize = CGM.getContext().getTypeSize(FType);
306   FieldAlign = CGM.getContext().getTypeAlign(FType);
307   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
308                                            "Size", Unit,
309                                            0, FieldSize, FieldAlign,
310                                            FieldOffset, 0, FieldTy);
311   EltTys.push_back(FieldTy);
312
313   FieldOffset += FieldSize;
314   Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
315   EltTys.clear();
316
317   unsigned Flags = llvm::DIType::FlagAppleBlock;
318
319   EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_descriptor",
320                                            Unit, 0, FieldOffset, 0, 0, Flags,
321                                            llvm::DIType(), Elements);
322
323   // Bit size, align and offset of the type.
324   uint64_t Size = CGM.getContext().getTypeSize(Ty);
325   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
326
327   DescTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
328                                           Unit, "", Unit,
329                                           0, Size, Align, 0, 0, EltTy);
330
331   FieldOffset = 0;
332   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
333   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
334   FieldSize = CGM.getContext().getTypeSize(FType);
335   FieldAlign = CGM.getContext().getTypeAlign(FType);
336   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
337                                            "__isa", Unit,
338                                            0, FieldSize, FieldAlign,
339                                            FieldOffset, 0, FieldTy);
340   EltTys.push_back(FieldTy);
341
342   FieldOffset += FieldSize;
343   FType = CGM.getContext().IntTy;
344   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
345   FieldSize = CGM.getContext().getTypeSize(FType);
346   FieldAlign = CGM.getContext().getTypeAlign(FType);
347   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
348                                            "__flags", Unit,
349                                            0, FieldSize, FieldAlign,
350                                            FieldOffset, 0, FieldTy);
351   EltTys.push_back(FieldTy);
352
353   FieldOffset += FieldSize;
354   FType = CGM.getContext().IntTy;
355   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
356   FieldSize = CGM.getContext().getTypeSize(FType);
357   FieldAlign = CGM.getContext().getTypeAlign(FType);
358   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
359                                            "__reserved", Unit,
360                                            0, FieldSize, FieldAlign,
361                                            FieldOffset, 0, FieldTy);
362   EltTys.push_back(FieldTy);
363
364   FieldOffset += FieldSize;
365   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
366   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
367   FieldSize = CGM.getContext().getTypeSize(FType);
368   FieldAlign = CGM.getContext().getTypeAlign(FType);
369   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
370                                            "__FuncPtr", Unit,
371                                            0, FieldSize, FieldAlign,
372                                            FieldOffset, 0, FieldTy);
373   EltTys.push_back(FieldTy);
374
375   FieldOffset += FieldSize;
376   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
377   FieldTy = DescTy;
378   FieldSize = CGM.getContext().getTypeSize(Ty);
379   FieldAlign = CGM.getContext().getTypeAlign(Ty);
380   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
381                                            "__descriptor", Unit,
382                                            0, FieldSize, FieldAlign,
383                                            FieldOffset, 0, FieldTy);
384   EltTys.push_back(FieldTy);
385
386   FieldOffset += FieldSize;
387   Elements = DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
388
389   EltTy = DebugFactory.CreateCompositeType(Tag, Unit, "__block_literal_generic",
390                                            Unit, 0, FieldOffset, 0, 0, Flags,
391                                            llvm::DIType(), Elements);
392
393   BlockLiteralGenericSet = true;
394   BlockLiteralGeneric
395     = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type, Unit,
396                                      "", Unit,
397                                      0, Size, Align, 0, 0, EltTy);
398   return BlockLiteralGeneric;
399 }
400
401 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
402                                      llvm::DIFile Unit) {
403   // Typedefs are derived from some other type.  If we have a typedef of a
404   // typedef, make sure to emit the whole chain.
405   llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
406
407   // We don't set size information, but do specify where the typedef was
408   // declared.
409   SourceManager &SM = CGM.getContext().getSourceManager();
410   PresumedLoc PLoc = SM.getPresumedLoc(Ty->getDecl()->getLocation());
411   unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
412
413   llvm::DIDescriptor TyContext 
414     = getContextDescriptor(dyn_cast<Decl>(Ty->getDecl()->getDeclContext()),
415                            Unit);
416   llvm::DIType DbgTy = 
417     DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_typedef, 
418                                    TyContext,
419                                    Ty->getDecl()->getName(), Unit,
420                                    Line, 0, 0, 0, 0, Src);
421   return DbgTy;
422 }
423
424 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
425                                      llvm::DIFile Unit) {
426   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
427
428   // Add the result type at least.
429   EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
430
431   // Set up remainder of arguments if there is a prototype.
432   // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
433   if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
434     for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
435       EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
436   } else {
437     // FIXME: Handle () case in C.  llvm-gcc doesn't do it either.
438   }
439
440   llvm::DIArray EltTypeArray =
441     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
442
443   llvm::DIType DbgTy =
444     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
445                                      Unit, "", Unit,
446                                      0, 0, 0, 0, 0,
447                                      llvm::DIType(), EltTypeArray);
448   return DbgTy;
449 }
450
451 /// CollectRecordFields - A helper function to collect debug info for
452 /// record fields. This is used while creating debug info entry for a Record.
453 void CGDebugInfo::
454 CollectRecordFields(const RecordDecl *RD, llvm::DIFile Unit,
455                     llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
456   unsigned FieldNo = 0;
457   SourceManager &SM = CGM.getContext().getSourceManager();
458   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
459   for (RecordDecl::field_iterator I = RD->field_begin(),
460                                   E = RD->field_end();
461        I != E; ++I, ++FieldNo) {
462     FieldDecl *Field = *I;
463     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
464
465     llvm::StringRef FieldName = Field->getName();
466
467     // Ignore unnamed fields. Do not ignore unnamed records.
468     if (FieldName.empty() && !isa<RecordType>(Field->getType()))
469       continue;
470
471     // Get the location for the field.
472     SourceLocation FieldDefLoc = Field->getLocation();
473     PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
474     llvm::DIFile FieldDefUnit;
475     unsigned FieldLine = 0;
476
477     if (!PLoc.isInvalid()) {
478       FieldDefUnit = getOrCreateFile(FieldDefLoc);
479       FieldLine = PLoc.getLine();
480     }
481
482     QualType FType = Field->getType();
483     uint64_t FieldSize = 0;
484     unsigned FieldAlign = 0;
485     if (!FType->isIncompleteArrayType()) {
486
487       // Bit size, align and offset of the type.
488       FieldSize = CGM.getContext().getTypeSize(FType);
489       Expr *BitWidth = Field->getBitWidth();
490       if (BitWidth)
491         FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
492
493       FieldAlign =  CGM.getContext().getTypeAlign(FType);
494     }
495
496     uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
497
498     // Create a DW_TAG_member node to remember the offset of this field in the
499     // struct.  FIXME: This is an absolutely insane way to capture this
500     // information.  When we gut debug info, this should be fixed.
501     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
502                                              FieldName, FieldDefUnit,
503                                              FieldLine, FieldSize, FieldAlign,
504                                              FieldOffset, 0, FieldTy);
505     EltTys.push_back(FieldTy);
506   }
507 }
508
509 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
510 /// function type is not updated to include implicit "this" pointer. Use this
511 /// routine to get a method type which includes "this" pointer.
512 llvm::DIType
513 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
514                                    llvm::DIFile Unit) {
515   llvm::DIType FnTy = getOrCreateType(Method->getType(), Unit);
516   
517   // Static methods do not need "this" pointer argument.
518   if (Method->isStatic())
519     return FnTy;
520
521   // Add "this" pointer.
522
523   llvm::DIArray Args = llvm::DICompositeType(FnTy.getNode()).getTypeArray();
524   assert (Args.getNumElements() && "Invalid number of arguments!");
525
526   llvm::SmallVector<llvm::DIDescriptor, 16> Elts;
527
528   // First element is always return type. For 'void' functions it is NULL.
529   Elts.push_back(Args.getElement(0));
530
531   // "this" pointer is always first argument.
532   ASTContext &Context = CGM.getContext();
533   QualType ThisPtr = 
534     Context.getPointerType(Context.getTagDeclType(Method->getParent()));
535   llvm::DIType ThisPtrType = 
536     DebugFactory.CreateArtificialType(getOrCreateType(ThisPtr, Unit));
537   TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType.getNode();  
538   Elts.push_back(ThisPtrType);
539
540   // Copy rest of the arguments.
541   for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
542     Elts.push_back(Args.getElement(i));
543
544   llvm::DIArray EltTypeArray =
545     DebugFactory.GetOrCreateArray(Elts.data(), Elts.size());
546
547   return
548     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
549                                      Unit, "", Unit,
550                                      0, 0, 0, 0, 0,
551                                      llvm::DIType(), EltTypeArray);
552 }
553
554 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
555 /// a single member function GlobalDecl.
556 llvm::DISubprogram
557 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
558                                      llvm::DIFile Unit,
559                                      llvm::DICompositeType &RecordTy) {
560   bool IsCtorOrDtor = 
561     isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
562   
563   llvm::StringRef MethodName = getFunctionName(Method);
564   llvm::StringRef MethodLinkageName;
565   llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
566   
567   // Since a single ctor/dtor corresponds to multiple functions, it doesn't
568   // make sense to give a single ctor/dtor a linkage name.
569   if (!IsCtorOrDtor)
570     MethodLinkageName = CGM.getMangledName(Method);
571
572   SourceManager &SM = CGM.getContext().getSourceManager();
573
574   // Get the location for the method.
575   SourceLocation MethodDefLoc = Method->getLocation();
576   PresumedLoc PLoc = SM.getPresumedLoc(MethodDefLoc);
577   llvm::DIFile MethodDefUnit;
578   unsigned MethodLine = 0;
579
580   if (!PLoc.isInvalid()) {
581     MethodDefUnit = getOrCreateFile(MethodDefLoc);
582     MethodLine = PLoc.getLine();
583   }
584
585   // Collect virtual method info.
586   llvm::DIType ContainingType;
587   unsigned Virtuality = 0; 
588   unsigned VIndex = 0;
589   
590   if (Method->isVirtual()) {
591     if (Method->isPure())
592       Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
593     else
594       Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
595     
596     // It doesn't make sense to give a virtual destructor a vtable index,
597     // since a single destructor has two entries in the vtable.
598     if (!isa<CXXDestructorDecl>(Method))
599       VIndex = CGM.getVtableInfo().getMethodVtableIndex(Method);
600     ContainingType = RecordTy;
601   }
602
603   llvm::DISubprogram SP =
604     DebugFactory.CreateSubprogram(RecordTy , MethodName, MethodName, 
605                                   MethodLinkageName,
606                                   MethodDefUnit, MethodLine,
607                                   MethodTy, /*isLocalToUnit=*/false, 
608                                   Method->isThisDeclarationADefinition(),
609                                   Virtuality, VIndex, ContainingType);
610   
611   // Don't cache ctors or dtors since we have to emit multiple functions for
612   // a single ctor or dtor.
613   if (!IsCtorOrDtor && Method->isThisDeclarationADefinition())
614     SPCache[Method] = llvm::WeakVH(SP.getNode());
615
616   return SP;
617 }
618
619 /// CollectCXXMemberFunctions - A helper function to collect debug info for
620 /// C++ member functions.This is used while creating debug info entry for 
621 /// a Record.
622 void CGDebugInfo::
623 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
624                           llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
625                           llvm::DICompositeType &RecordTy) {
626   for(CXXRecordDecl::method_iterator I = RD->method_begin(),
627         E = RD->method_end(); I != E; ++I) {
628     const CXXMethodDecl *Method = *I;
629     
630     if (Method->isImplicit() && !Method->isUsed())
631       continue;
632
633     EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
634   }
635 }                                 
636
637 /// CollectCXXBases - A helper function to collect debug info for
638 /// C++ base classes. This is used while creating debug info entry for 
639 /// a Record.
640 void CGDebugInfo::
641 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
642                 llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys,
643                 llvm::DICompositeType &RecordTy) {
644
645   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
646   for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
647          BE = RD->bases_end(); BI != BE; ++BI) {
648     unsigned BFlags = 0;
649     uint64_t BaseOffset;
650     
651     const CXXRecordDecl *Base =
652       cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
653     
654     if (BI->isVirtual()) {
655       // virtual base offset offset is -ve. The code generator emits dwarf
656       // expression where it expects +ve number.
657       BaseOffset = 0 - CGM.getVtableInfo().getVirtualBaseOffsetOffset(RD, Base);
658       BFlags = llvm::DIType::FlagVirtual;
659     } else
660       BaseOffset = RL.getBaseClassOffset(Base);
661     
662     AccessSpecifier Access = BI->getAccessSpecifier();
663     if (Access == clang::AS_private)
664       BFlags |= llvm::DIType::FlagPrivate;
665     else if (Access == clang::AS_protected)
666       BFlags |= llvm::DIType::FlagProtected;
667     
668     llvm::DIType DTy =
669       DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
670                                      RecordTy, llvm::StringRef(), 
671                                      Unit, 0, 0, 0,
672                                      BaseOffset, BFlags,
673                                      getOrCreateType(BI->getType(),
674                                                      Unit));
675     EltTys.push_back(DTy);
676   }
677 }
678
679 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
680 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
681   if (VTablePtrType.isValid())
682     return VTablePtrType;
683
684   ASTContext &Context = CGM.getContext();
685
686   /* Function type */
687   llvm::SmallVector<llvm::DIDescriptor, 16> STys;
688   STys.push_back(getOrCreateType(Context.IntTy, Unit));
689   llvm::DIArray SElements =
690     DebugFactory.GetOrCreateArray(STys.data(), STys.size());
691   llvm::DIType SubTy =
692     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_subroutine_type,
693                                      Unit, "", Unit,
694                                      0, 0, 0, 0, 0, llvm::DIType(), SElements);
695
696   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
697   llvm::DIType vtbl_ptr_type 
698     = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
699                                      Unit, "__vtbl_ptr_type", Unit,
700                                      0, Size, 0, 0, 0, SubTy);
701
702   VTablePtrType = 
703     DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_pointer_type,
704                                    Unit, "", Unit,
705                                    0, Size, 0, 0, 0, vtbl_ptr_type);
706   return VTablePtrType;
707 }
708
709 /// getVtableName - Get vtable name for the given Class.
710 llvm::StringRef CGDebugInfo::getVtableName(const CXXRecordDecl *RD) {
711   // Otherwise construct gdb compatible name name.
712   std::string Name = "_vptr$" + RD->getNameAsString();
713
714   // Copy this name on the side and use its reference.
715   char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
716   memcpy(StrPtr, Name.data(), Name.length());
717   return llvm::StringRef(StrPtr, Name.length());
718 }
719
720
721 /// CollectVtableInfo - If the C++ class has vtable info then insert appropriate
722 /// debug info entry in EltTys vector.
723 void CGDebugInfo::
724 CollectVtableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
725                   llvm::SmallVectorImpl<llvm::DIDescriptor> &EltTys) {
726   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
727
728   // If there is a primary base then it will hold vtable info.
729   if (RL.getPrimaryBase())
730     return;
731
732   // If this class is not dynamic then there is not any vtable info to collect.
733   if (!RD->isDynamicClass())
734     return;
735
736   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
737   llvm::DIType VPTR
738     = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
739                                      getVtableName(RD), Unit,
740                                      0, Size, 0, 0, 0, 
741                                      getOrCreateVTablePtrType(Unit));
742   EltTys.push_back(VPTR);
743 }
744
745 /// CreateType - get structure or union type.
746 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty,
747                                      llvm::DIFile Unit) {
748   RecordDecl *RD = Ty->getDecl();
749
750   unsigned Tag;
751   if (RD->isStruct())
752     Tag = llvm::dwarf::DW_TAG_structure_type;
753   else if (RD->isUnion())
754     Tag = llvm::dwarf::DW_TAG_union_type;
755   else {
756     assert(RD->isClass() && "Unknown RecordType!");
757     Tag = llvm::dwarf::DW_TAG_class_type;
758   }
759
760   SourceManager &SM = CGM.getContext().getSourceManager();
761
762   // Get overall information about the record type for the debug info.
763   PresumedLoc PLoc = SM.getPresumedLoc(RD->getLocation());
764   llvm::DIFile DefUnit;
765   unsigned Line = 0;
766   if (!PLoc.isInvalid()) {
767     DefUnit = getOrCreateFile(RD->getLocation());
768     Line = PLoc.getLine();
769   }
770
771   // Records and classes and unions can all be recursive.  To handle them, we
772   // first generate a debug descriptor for the struct as a forward declaration.
773   // Then (if it is a definition) we go through and get debug info for all of
774   // its members.  Finally, we create a descriptor for the complete type (which
775   // may refer to the forward decl if the struct is recursive) and replace all
776   // uses of the forward declaration with the final definition.
777
778   // A RD->getName() is not unique. However, the debug info descriptors 
779   // are uniqued so use type name to ensure uniquness.
780   llvm::SmallString<128> FwdDeclName;
781   llvm::raw_svector_ostream(FwdDeclName) << "fwd.type." << FwdDeclCount++;
782   llvm::DIDescriptor FDContext = 
783     getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
784   llvm::DICompositeType FwdDecl =
785     DebugFactory.CreateCompositeType(Tag, FDContext, FwdDeclName,
786                                      DefUnit, Line, 0, 0, 0, 0,
787                                      llvm::DIType(), llvm::DIArray());
788
789   // If this is just a forward declaration, return it.
790   if (!RD->getDefinition())
791     return FwdDecl;
792
793   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = FwdDecl.getNode();
794   // Otherwise, insert it into the TypeCache so that recursive uses will find
795   // it.
796   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
797   // Push the struct on region stack.
798   RegionStack.push_back(FwdDecl.getNode());
799   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl.getNode());
800
801   // Convert all the elements.
802   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
803
804   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
805   if (CXXDecl) {
806     CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
807     CollectVtableInfo(CXXDecl, Unit, EltTys);
808   }
809   CollectRecordFields(RD, Unit, EltTys);
810   llvm::MDNode *ContainingType = NULL;
811   if (CXXDecl) {
812     CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
813
814     // A class's primary base or the class itself contains the vtable.
815     const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
816     if (const CXXRecordDecl *PBase = RL.getPrimaryBase())
817       ContainingType = 
818         getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit).getNode();
819     else if (CXXDecl->isDynamicClass()) 
820       ContainingType = FwdDecl.getNode();
821   }
822
823   llvm::DIArray Elements =
824     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
825
826   // Bit size, align and offset of the type.
827   uint64_t Size = CGM.getContext().getTypeSize(Ty);
828   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
829
830   RegionStack.pop_back();
831   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI = 
832     RegionMap.find(Ty->getDecl());
833   if (RI != RegionMap.end())
834     RegionMap.erase(RI);
835
836   llvm::DIDescriptor RDContext =  
837     getContextDescriptor(dyn_cast<Decl>(RD->getDeclContext()), Unit);
838   llvm::DICompositeType RealDecl =
839     DebugFactory.CreateCompositeType(Tag, RDContext,
840                                      RD->getName(),
841                                      DefUnit, Line, Size, Align, 0, 0, 
842                                      llvm::DIType(), Elements, 
843                                      0, ContainingType);
844
845   // Now that we have a real decl for the struct, replace anything using the
846   // old decl with the new one.  This will recursively update the debug info.
847   llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
848   RegionMap[RD] = llvm::WeakVH(RealDecl.getNode());
849   return RealDecl;
850 }
851
852 /// CreateType - get objective-c interface type.
853 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
854                                      llvm::DIFile Unit) {
855   ObjCInterfaceDecl *ID = Ty->getDecl();
856
857   unsigned Tag = llvm::dwarf::DW_TAG_structure_type;
858   SourceManager &SM = CGM.getContext().getSourceManager();
859
860   // Get overall information about the record type for the debug info.
861   llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
862   PresumedLoc PLoc = SM.getPresumedLoc(ID->getLocation());
863   unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
864
865
866   unsigned RuntimeLang = TheCU.getLanguage();
867
868   // To handle recursive interface, we
869   // first generate a debug descriptor for the struct as a forward declaration.
870   // Then (if it is a definition) we go through and get debug info for all of
871   // its members.  Finally, we create a descriptor for the complete type (which
872   // may refer to the forward decl if the struct is recursive) and replace all
873   // uses of the forward declaration with the final definition.
874   llvm::DICompositeType FwdDecl =
875     DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(),
876                                      DefUnit, Line, 0, 0, 0, 0,
877                                      llvm::DIType(), llvm::DIArray(),
878                                      RuntimeLang);
879
880   // If this is just a forward declaration, return it.
881   if (ID->isForwardDecl())
882     return FwdDecl;
883
884   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = FwdDecl.getNode();
885   // Otherwise, insert it into the TypeCache so that recursive uses will find
886   // it.
887   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl.getNode();
888   // Push the struct on region stack.
889   RegionStack.push_back(FwdDecl.getNode());
890   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl.getNode());
891
892   // Convert all the elements.
893   llvm::SmallVector<llvm::DIDescriptor, 16> EltTys;
894
895   ObjCInterfaceDecl *SClass = ID->getSuperClass();
896   if (SClass) {
897     llvm::DIType SClassTy =
898       getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
899     llvm::DIType InhTag =
900       DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_inheritance,
901                                      Unit, "", Unit, 0, 0, 0,
902                                      0 /* offset */, 0, SClassTy);
903     EltTys.push_back(InhTag);
904   }
905
906   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
907
908   unsigned FieldNo = 0;
909   for (ObjCInterfaceDecl::ivar_iterator I = ID->ivar_begin(),
910          E = ID->ivar_end();  I != E; ++I, ++FieldNo) {
911     ObjCIvarDecl *Field = *I;
912     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
913
914     llvm::StringRef FieldName = Field->getName();
915
916     // Ignore unnamed fields.
917     if (FieldName.empty())
918       continue;
919
920     // Get the location for the field.
921     SourceLocation FieldDefLoc = Field->getLocation();
922     llvm::DIFile FieldDefUnit = getOrCreateFile(FieldDefLoc);
923     PresumedLoc PLoc = SM.getPresumedLoc(FieldDefLoc);
924     unsigned FieldLine = PLoc.isInvalid() ? 0 : PLoc.getLine();
925
926
927     QualType FType = Field->getType();
928     uint64_t FieldSize = 0;
929     unsigned FieldAlign = 0;
930
931     if (!FType->isIncompleteArrayType()) {
932
933       // Bit size, align and offset of the type.
934       FieldSize = CGM.getContext().getTypeSize(FType);
935       Expr *BitWidth = Field->getBitWidth();
936       if (BitWidth)
937         FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
938
939       FieldAlign =  CGM.getContext().getTypeAlign(FType);
940     }
941
942     uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
943
944     unsigned Flags = 0;
945     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
946       Flags = llvm::DIType::FlagProtected;
947     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
948       Flags = llvm::DIType::FlagPrivate;
949
950     // Create a DW_TAG_member node to remember the offset of this field in the
951     // struct.  FIXME: This is an absolutely insane way to capture this
952     // information.  When we gut debug info, this should be fixed.
953     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
954                                              FieldName, FieldDefUnit,
955                                              FieldLine, FieldSize, FieldAlign,
956                                              FieldOffset, Flags, FieldTy);
957     EltTys.push_back(FieldTy);
958   }
959
960   llvm::DIArray Elements =
961     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
962
963   RegionStack.pop_back();
964   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI = 
965     RegionMap.find(Ty->getDecl());
966   if (RI != RegionMap.end())
967     RegionMap.erase(RI);
968
969   // Bit size, align and offset of the type.
970   uint64_t Size = CGM.getContext().getTypeSize(Ty);
971   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
972
973   llvm::DICompositeType RealDecl =
974     DebugFactory.CreateCompositeType(Tag, Unit, ID->getName(), DefUnit,
975                                      Line, Size, Align, 0, 0, llvm::DIType(), 
976                                      Elements, RuntimeLang);
977
978   // Now that we have a real decl for the struct, replace anything using the
979   // old decl with the new one.  This will recursively update the debug info.
980   llvm::DIDerivedType(FwdDeclNode).replaceAllUsesWith(RealDecl);
981   RegionMap[ID] = llvm::WeakVH(RealDecl.getNode());
982
983   return RealDecl;
984 }
985
986 llvm::DIType CGDebugInfo::CreateType(const EnumType *Ty,
987                                      llvm::DIFile Unit) {
988   EnumDecl *ED = Ty->getDecl();
989
990   llvm::SmallVector<llvm::DIDescriptor, 32> Enumerators;
991
992   // Create DIEnumerator elements for each enumerator.
993   for (EnumDecl::enumerator_iterator
994          Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
995        Enum != EnumEnd; ++Enum) {
996     Enumerators.push_back(DebugFactory.CreateEnumerator(Enum->getName(),
997                                             Enum->getInitVal().getZExtValue()));
998   }
999
1000   // Return a CompositeType for the enum itself.
1001   llvm::DIArray EltArray =
1002     DebugFactory.GetOrCreateArray(Enumerators.data(), Enumerators.size());
1003
1004   SourceLocation DefLoc = ED->getLocation();
1005   llvm::DIFile DefUnit = getOrCreateFile(DefLoc);
1006   SourceManager &SM = CGM.getContext().getSourceManager();
1007   PresumedLoc PLoc = SM.getPresumedLoc(DefLoc);
1008   unsigned Line = PLoc.isInvalid() ? 0 : PLoc.getLine();
1009
1010
1011   // Size and align of the type.
1012   uint64_t Size = 0;
1013   unsigned Align = 0;
1014   if (!Ty->isIncompleteType()) {
1015     Size = CGM.getContext().getTypeSize(Ty);
1016     Align = CGM.getContext().getTypeAlign(Ty);
1017   }
1018
1019   llvm::DIType DbgTy = 
1020     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_enumeration_type,
1021                                      Unit, ED->getName(), DefUnit, Line,
1022                                      Size, Align, 0, 0,
1023                                      llvm::DIType(), EltArray);
1024   return DbgTy;
1025 }
1026
1027 llvm::DIType CGDebugInfo::CreateType(const TagType *Ty,
1028                                      llvm::DIFile Unit) {
1029   if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1030     return CreateType(RT, Unit);
1031   else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1032     return CreateType(ET, Unit);
1033
1034   return llvm::DIType();
1035 }
1036
1037 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1038                                      llvm::DIFile Unit) {
1039   llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1040   uint64_t NumElems = Ty->getNumElements();
1041   if (NumElems > 0)
1042     --NumElems;
1043   llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
1044   Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, NumElems));
1045
1046   llvm::DIArray SubscriptArray =
1047     DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
1048
1049   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1050   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1051
1052   return
1053     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_vector_type,
1054                                      Unit, "", Unit,
1055                                      0, Size, Align, 0, 0,
1056                                      ElementTy,  SubscriptArray);
1057 }
1058
1059 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1060                                      llvm::DIFile Unit) {
1061   uint64_t Size;
1062   uint64_t Align;
1063
1064
1065   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1066   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1067     Size = 0;
1068     Align =
1069       CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1070   } else if (Ty->isIncompleteArrayType()) {
1071     Size = 0;
1072     Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1073   } else {
1074     // Size and align of the whole array, not the element type.
1075     Size = CGM.getContext().getTypeSize(Ty);
1076     Align = CGM.getContext().getTypeAlign(Ty);
1077   }
1078
1079   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1080   // interior arrays, do we care?  Why aren't nested arrays represented the
1081   // obvious/recursive way?
1082   llvm::SmallVector<llvm::DIDescriptor, 8> Subscripts;
1083   QualType EltTy(Ty, 0);
1084   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1085     uint64_t Upper = 0;
1086     if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1087       if (CAT->getSize().getZExtValue())
1088         Upper = CAT->getSize().getZExtValue() - 1;
1089     // FIXME: Verify this is right for VLAs.
1090     Subscripts.push_back(DebugFactory.GetOrCreateSubrange(0, Upper));
1091     EltTy = Ty->getElementType();
1092   }
1093
1094   llvm::DIArray SubscriptArray =
1095     DebugFactory.GetOrCreateArray(Subscripts.data(), Subscripts.size());
1096
1097   llvm::DIType DbgTy = 
1098     DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_array_type,
1099                                      Unit, "", Unit,
1100                                      0, Size, Align, 0, 0,
1101                                      getOrCreateType(EltTy, Unit),
1102                                      SubscriptArray);
1103   return DbgTy;
1104 }
1105
1106 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty, 
1107                                      llvm::DIFile Unit) {
1108   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, 
1109                                Ty, Ty->getPointeeType(), Unit);
1110 }
1111
1112 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty, 
1113                                      llvm::DIFile U) {
1114   QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1115   llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1116   
1117   if (!Ty->getPointeeType()->isFunctionType()) {
1118     // We have a data member pointer type.
1119     return PointerDiffDITy;
1120   }
1121   
1122   // We have a member function pointer type. Treat it as a struct with two
1123   // ptrdiff_t members.
1124   std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1125
1126   uint64_t FieldOffset = 0;
1127   llvm::DIDescriptor ElementTypes[2];
1128   
1129   // FIXME: This should probably be a function type instead.
1130   ElementTypes[0] =
1131     DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1132                                    "ptr", U, 0,
1133                                    Info.first, Info.second, FieldOffset, 0,
1134                                    PointerDiffDITy);
1135   FieldOffset += Info.first;
1136   
1137   ElementTypes[1] =
1138     DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, U,
1139                                    "ptr", U, 0,
1140                                    Info.first, Info.second, FieldOffset, 0,
1141                                    PointerDiffDITy);
1142   
1143   llvm::DIArray Elements = 
1144     DebugFactory.GetOrCreateArray(&ElementTypes[0],
1145                                   llvm::array_lengthof(ElementTypes));
1146
1147   return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type, 
1148                                           U, llvm::StringRef("test"), 
1149                                           U, 0, FieldOffset, 
1150                                           0, 0, 0, llvm::DIType(), Elements);
1151 }
1152
1153 static QualType UnwrapTypeForDebugInfo(QualType T) {
1154   do {
1155     QualType LastT = T;
1156     switch (T->getTypeClass()) {
1157     default:
1158       return T;
1159     case Type::TemplateSpecialization:
1160       T = cast<TemplateSpecializationType>(T)->desugar();
1161       break;
1162     case Type::TypeOfExpr: {
1163       TypeOfExprType *Ty = cast<TypeOfExprType>(T);
1164       T = Ty->getUnderlyingExpr()->getType();
1165       break;
1166     }
1167     case Type::TypeOf:
1168       T = cast<TypeOfType>(T)->getUnderlyingType();
1169       break;
1170     case Type::Decltype:
1171       T = cast<DecltypeType>(T)->getUnderlyingType();
1172       break;
1173     case Type::QualifiedName:
1174       T = cast<QualifiedNameType>(T)->getNamedType();
1175       break;
1176     case Type::SubstTemplateTypeParm:
1177       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1178       break;
1179     case Type::Elaborated:
1180       T = cast<ElaboratedType>(T)->getUnderlyingType();
1181       break;
1182     }
1183     
1184     assert(T != LastT && "Type unwrapping failed to unwrap!");
1185     if (T == LastT)
1186       return T;
1187   } while (true);
1188   
1189   return T;
1190 }
1191
1192 /// getOrCreateType - Get the type from the cache or create a new
1193 /// one if necessary.
1194 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1195                                           llvm::DIFile Unit) {
1196   if (Ty.isNull())
1197     return llvm::DIType();
1198
1199   // Unwrap the type as needed for debug information.
1200   Ty = UnwrapTypeForDebugInfo(Ty);
1201   
1202   // Check for existing entry.
1203   std::map<void *, llvm::WeakVH>::iterator it =
1204     TypeCache.find(Ty.getAsOpaquePtr());
1205   if (it != TypeCache.end()) {
1206     // Verify that the debug info still exists.
1207     if (&*it->second)
1208       return llvm::DIType(cast<llvm::MDNode>(it->second));
1209   }
1210
1211   // Otherwise create the type.
1212   llvm::DIType Res = CreateTypeNode(Ty, Unit);
1213
1214   // And update the type cache.
1215   TypeCache[Ty.getAsOpaquePtr()] = Res.getNode();  
1216   return Res;
1217 }
1218
1219 /// CreateTypeNode - Create a new debug type node.
1220 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1221                                          llvm::DIFile Unit) {
1222   // Handle qualifiers, which recursively handles what they refer to.
1223   if (Ty.hasLocalQualifiers())
1224     return CreateQualifiedType(Ty, Unit);
1225
1226   const char *Diag = 0;
1227   
1228   // Work out details of type.
1229   switch (Ty->getTypeClass()) {
1230 #define TYPE(Class, Base)
1231 #define ABSTRACT_TYPE(Class, Base)
1232 #define NON_CANONICAL_TYPE(Class, Base)
1233 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1234 #include "clang/AST/TypeNodes.def"
1235     assert(false && "Dependent types cannot show up in debug information");
1236
1237   // FIXME: Handle these.
1238   case Type::ExtVector:
1239     return llvm::DIType();
1240
1241   case Type::Vector:
1242     return CreateType(cast<VectorType>(Ty), Unit);
1243   case Type::ObjCObjectPointer:
1244     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1245   case Type::ObjCInterface:
1246     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1247   case Type::Builtin: return CreateType(cast<BuiltinType>(Ty), Unit);
1248   case Type::Complex: return CreateType(cast<ComplexType>(Ty), Unit);
1249   case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1250   case Type::BlockPointer:
1251     return CreateType(cast<BlockPointerType>(Ty), Unit);
1252   case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1253   case Type::Record:
1254   case Type::Enum:
1255     return CreateType(cast<TagType>(Ty), Unit);
1256   case Type::FunctionProto:
1257   case Type::FunctionNoProto:
1258     return CreateType(cast<FunctionType>(Ty), Unit);
1259   case Type::ConstantArray:
1260   case Type::VariableArray:
1261   case Type::IncompleteArray:
1262     return CreateType(cast<ArrayType>(Ty), Unit);
1263
1264   case Type::LValueReference:
1265     return CreateType(cast<LValueReferenceType>(Ty), Unit);
1266
1267   case Type::MemberPointer:
1268     return CreateType(cast<MemberPointerType>(Ty), Unit);
1269
1270   case Type::InjectedClassName:
1271   case Type::TemplateSpecialization:
1272   case Type::Elaborated:
1273   case Type::QualifiedName:
1274   case Type::SubstTemplateTypeParm:
1275   case Type::TypeOfExpr:
1276   case Type::TypeOf:
1277   case Type::Decltype:
1278     llvm_unreachable("type should have been unwrapped!");
1279     return llvm::DIType();
1280       
1281   case Type::RValueReference:
1282     // FIXME: Implement!
1283     Diag = "rvalue references";
1284     break;
1285   }
1286   
1287   assert(Diag && "Fall through without a diagnostic?");
1288   unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error,
1289                                "debug information for %0 is not yet supported");
1290   CGM.getDiags().Report(FullSourceLoc(), DiagID)
1291     << Diag;
1292   return llvm::DIType();
1293 }
1294
1295 /// EmitFunctionStart - Constructs the debug code for entering a function -
1296 /// "llvm.dbg.func.start.".
1297 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1298                                     llvm::Function *Fn,
1299                                     CGBuilderTy &Builder) {
1300
1301   llvm::StringRef Name;
1302   llvm::StringRef LinkageName;
1303
1304   const Decl *D = GD.getDecl();
1305   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1306     // If there is a DISubprogram for  this function available then use it.
1307     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1308       FI = SPCache.find(FD);
1309     if (FI != SPCache.end()) {
1310       llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(FI->second));
1311       if (SP.isSubprogram() && llvm::DISubprogram(SP.getNode()).isDefinition()) {
1312         RegionStack.push_back(SP.getNode());
1313         RegionMap[D] = llvm::WeakVH(SP.getNode());
1314         return;
1315       }
1316     }
1317     Name = getFunctionName(FD);
1318     if (!Name.empty() && Name[0] == '\01')
1319       Name = Name.substr(1);
1320     // Use mangled name as linkage name for c/c++ functions.
1321     LinkageName = CGM.getMangledName(GD);
1322   } else {
1323     // Use llvm function name as linkage name.
1324     Name = Fn->getName();
1325     LinkageName = Name;
1326     if (!Name.empty() && Name[0] == '\01')
1327       Name = Name.substr(1);
1328   }
1329
1330   // It is expected that CurLoc is set before using EmitFunctionStart.
1331   // Usually, CurLoc points to the left bracket location of compound
1332   // statement representing function body.
1333   llvm::DIFile Unit = getOrCreateFile(CurLoc);
1334   SourceManager &SM = CGM.getContext().getSourceManager();
1335   unsigned LineNo = SM.getPresumedLoc(CurLoc).getLine();
1336
1337   llvm::DISubprogram SP =
1338     DebugFactory.CreateSubprogram(Unit, Name, Name, LinkageName, Unit, LineNo,
1339                                   getOrCreateType(FnType, Unit),
1340                                   Fn->hasInternalLinkage(), true/*definition*/);
1341
1342   // Push function on region stack.
1343   RegionStack.push_back(SP.getNode());
1344   RegionMap[D] = llvm::WeakVH(SP.getNode());
1345 }
1346
1347
1348 void CGDebugInfo::EmitStopPoint(llvm::Function *Fn, CGBuilderTy &Builder) {
1349   if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1350
1351   // Don't bother if things are the same as last time.
1352   SourceManager &SM = CGM.getContext().getSourceManager();
1353   if (CurLoc == PrevLoc
1354        || (SM.getInstantiationLineNumber(CurLoc) ==
1355            SM.getInstantiationLineNumber(PrevLoc)
1356            && SM.isFromSameFile(CurLoc, PrevLoc)))
1357     return;
1358
1359   // Update last state.
1360   PrevLoc = CurLoc;
1361
1362   // Get the appropriate compile unit.
1363   llvm::DIFile Unit = getOrCreateFile(CurLoc);
1364   PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
1365
1366   llvm::DIDescriptor DR(RegionStack.back());
1367   llvm::DIScope DS = llvm::DIScope(DR.getNode());
1368   llvm::DILocation DO(NULL);
1369   llvm::DILocation DL = 
1370     DebugFactory.CreateLocation(PLoc.getLine(), PLoc.getColumn(),
1371                                 DS, DO);
1372   Builder.SetCurrentDebugLocation(DL.getNode());
1373 }
1374
1375 /// EmitRegionStart- Constructs the debug code for entering a declarative
1376 /// region - "llvm.dbg.region.start.".
1377 void CGDebugInfo::EmitRegionStart(llvm::Function *Fn, CGBuilderTy &Builder) {
1378   SourceManager &SM = CGM.getContext().getSourceManager();
1379   PresumedLoc PLoc = SM.getPresumedLoc(CurLoc);
1380   llvm::DIDescriptor D =
1381     DebugFactory.CreateLexicalBlock(RegionStack.empty() ? 
1382                                     llvm::DIDescriptor() : 
1383                                     llvm::DIDescriptor(RegionStack.back()),
1384                                     PLoc.getLine(), PLoc.getColumn());
1385   RegionStack.push_back(D.getNode());
1386 }
1387
1388 /// EmitRegionEnd - Constructs the debug code for exiting a declarative
1389 /// region - "llvm.dbg.region.end."
1390 void CGDebugInfo::EmitRegionEnd(llvm::Function *Fn, CGBuilderTy &Builder) {
1391   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1392
1393   // Provide an region stop point.
1394   EmitStopPoint(Fn, Builder);
1395
1396   RegionStack.pop_back();
1397 }
1398
1399 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.  
1400 // See BuildByRefType.
1401 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1402                                                        uint64_t *XOffset) {
1403
1404   llvm::SmallVector<llvm::DIDescriptor, 5> EltTys;
1405
1406   QualType FType;
1407   uint64_t FieldSize, FieldOffset;
1408   unsigned FieldAlign;
1409   
1410   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1411   QualType Type = VD->getType();  
1412
1413   FieldOffset = 0;
1414   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1415   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1416   FieldSize = CGM.getContext().getTypeSize(FType);
1417   FieldAlign = CGM.getContext().getTypeAlign(FType);
1418   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1419                                            "__isa", Unit,
1420                                            0, FieldSize, FieldAlign,
1421                                            FieldOffset, 0, FieldTy);
1422   EltTys.push_back(FieldTy);
1423   FieldOffset += FieldSize;
1424   
1425   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1426   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1427   FieldSize = CGM.getContext().getTypeSize(FType);
1428   FieldAlign = CGM.getContext().getTypeAlign(FType);
1429   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1430                                            "__forwarding", Unit,
1431                                            0, FieldSize, FieldAlign,
1432                                            FieldOffset, 0, FieldTy);
1433   EltTys.push_back(FieldTy);
1434   FieldOffset += FieldSize;
1435   
1436   FType = CGM.getContext().IntTy;
1437   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1438   FieldSize = CGM.getContext().getTypeSize(FType);
1439   FieldAlign = CGM.getContext().getTypeAlign(FType);
1440   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1441                                            "__flags", Unit,
1442                                            0, FieldSize, FieldAlign,
1443                                            FieldOffset, 0, FieldTy);
1444   EltTys.push_back(FieldTy);
1445   FieldOffset += FieldSize;
1446   
1447   FType = CGM.getContext().IntTy;
1448   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1449   FieldSize = CGM.getContext().getTypeSize(FType);
1450   FieldAlign = CGM.getContext().getTypeAlign(FType);
1451   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1452                                            "__size", Unit,
1453                                            0, FieldSize, FieldAlign,
1454                                            FieldOffset, 0, FieldTy);
1455   EltTys.push_back(FieldTy);
1456   FieldOffset += FieldSize;
1457   
1458   bool HasCopyAndDispose = CGM.BlockRequiresCopying(Type);
1459   if (HasCopyAndDispose) {
1460     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1461     FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1462     FieldSize = CGM.getContext().getTypeSize(FType);
1463     FieldAlign = CGM.getContext().getTypeAlign(FType);
1464     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1465                                              "__copy_helper", Unit,                                             
1466                                              0, FieldSize, FieldAlign,
1467                                              FieldOffset, 0, FieldTy);
1468     EltTys.push_back(FieldTy);
1469     FieldOffset += FieldSize;
1470     
1471     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1472     FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1473     FieldSize = CGM.getContext().getTypeSize(FType);
1474     FieldAlign = CGM.getContext().getTypeAlign(FType);
1475     FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1476                                              "__destroy_helper", Unit,
1477                                              0, FieldSize, FieldAlign,
1478                                              FieldOffset, 0, FieldTy);
1479     EltTys.push_back(FieldTy);
1480     FieldOffset += FieldSize;
1481   }
1482   
1483   CharUnits Align = CGM.getContext().getDeclAlign(VD);
1484   if (Align > CharUnits::fromQuantity(
1485         CGM.getContext().Target.getPointerAlign(0) / 8)) {
1486     unsigned AlignedOffsetInBytes
1487       = llvm::RoundUpToAlignment(FieldOffset/8, Align.getQuantity());
1488     unsigned NumPaddingBytes
1489       = AlignedOffsetInBytes - FieldOffset/8;
1490     
1491     if (NumPaddingBytes > 0) {
1492       llvm::APInt pad(32, NumPaddingBytes);
1493       FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1494                                                     pad, ArrayType::Normal, 0);
1495       FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1496       FieldSize = CGM.getContext().getTypeSize(FType);
1497       FieldAlign = CGM.getContext().getTypeAlign(FType);
1498       FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member,
1499                                                Unit, "", Unit,
1500                                                0, FieldSize, FieldAlign,
1501                                                FieldOffset, 0, FieldTy);
1502       EltTys.push_back(FieldTy);
1503       FieldOffset += FieldSize;
1504     }
1505   }
1506   
1507   FType = Type;
1508   FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1509   FieldSize = CGM.getContext().getTypeSize(FType);
1510   FieldAlign = Align.getQuantity()*8;
1511
1512   *XOffset = FieldOffset;  
1513   FieldTy = DebugFactory.CreateDerivedType(llvm::dwarf::DW_TAG_member, Unit,
1514                                            VD->getName(), Unit,
1515                                            0, FieldSize, FieldAlign,
1516                                            FieldOffset, 0, FieldTy);
1517   EltTys.push_back(FieldTy);
1518   FieldOffset += FieldSize;
1519   
1520   llvm::DIArray Elements = 
1521     DebugFactory.GetOrCreateArray(EltTys.data(), EltTys.size());
1522   
1523   unsigned Flags = llvm::DIType::FlagBlockByrefStruct;
1524   
1525   return DebugFactory.CreateCompositeType(llvm::dwarf::DW_TAG_structure_type, 
1526                                           Unit, "", Unit,
1527                                           0, FieldOffset, 0, 0, Flags,
1528                                           llvm::DIType(), Elements);
1529   
1530 }
1531 /// EmitDeclare - Emit local variable declaration debug info.
1532 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1533                               llvm::Value *Storage, CGBuilderTy &Builder) {
1534   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1535
1536   // Do not emit variable debug information while generating optimized code.
1537   // The llvm optimizer and code generator are not yet ready to support
1538   // optimized code debugging.
1539   const CodeGenOptions &CGO = CGM.getCodeGenOpts();
1540   if (CGO.OptimizationLevel)
1541     return;
1542
1543   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1544   llvm::DIType Ty;
1545   uint64_t XOffset = 0;
1546   if (VD->hasAttr<BlocksAttr>())
1547     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1548   else 
1549     Ty = getOrCreateType(VD->getType(), Unit);
1550
1551   // Get location information.
1552   SourceManager &SM = CGM.getContext().getSourceManager();
1553   PresumedLoc PLoc = SM.getPresumedLoc(VD->getLocation());
1554   unsigned Line = 0;
1555   unsigned Column = 0;
1556   if (PLoc.isInvalid())
1557     PLoc = SM.getPresumedLoc(CurLoc);
1558   if (PLoc.isValid()) {
1559     Line = PLoc.getLine();
1560     Column = PLoc.getColumn();
1561     Unit = getOrCreateFile(CurLoc);
1562   } else {
1563     Unit = llvm::DIFile();
1564   }
1565
1566   // Create the descriptor for the variable.
1567   llvm::DIVariable D =
1568     DebugFactory.CreateVariable(Tag, llvm::DIDescriptor(RegionStack.back()),
1569                                 VD->getName(),
1570                                 Unit, Line, Ty);
1571   // Insert an llvm.dbg.declare into the current block.
1572   llvm::Instruction *Call =
1573     DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1574
1575   llvm::DIScope DS(RegionStack.back());
1576   llvm::DILocation DO(NULL);
1577   llvm::DILocation DL = DebugFactory.CreateLocation(Line, Column, DS, DO);
1578   
1579   Call->setMetadata("dbg", DL.getNode());
1580 }
1581
1582 /// EmitDeclare - Emit local variable declaration debug info.
1583 void CGDebugInfo::EmitDeclare(const BlockDeclRefExpr *BDRE, unsigned Tag,
1584                               llvm::Value *Storage, CGBuilderTy &Builder,
1585                               CodeGenFunction *CGF) {
1586   const ValueDecl *VD = BDRE->getDecl();
1587   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1588
1589   // Do not emit variable debug information while generating optimized code.
1590   // The llvm optimizer and code generator are not yet ready to support
1591   // optimized code debugging.
1592   const CodeGenOptions &CGO = CGM.getCodeGenOpts();
1593   if (CGO.OptimizationLevel || Builder.GetInsertBlock() == 0)
1594     return;
1595
1596   uint64_t XOffset = 0;
1597   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1598   llvm::DIType Ty;
1599   if (VD->hasAttr<BlocksAttr>())
1600     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1601   else 
1602     Ty = getOrCreateType(VD->getType(), Unit);
1603
1604   // Get location information.
1605   SourceManager &SM = CGM.getContext().getSourceManager();
1606   PresumedLoc PLoc = SM.getPresumedLoc(VD->getLocation());
1607   unsigned Line = 0;
1608   if (!PLoc.isInvalid())
1609     Line = PLoc.getLine();
1610   else
1611     Unit = llvm::DIFile();
1612
1613   CharUnits offset = CGF->BlockDecls[VD];
1614   llvm::SmallVector<llvm::Value *, 9> addr;
1615   const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1616   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1617   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1618   addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1619   if (BDRE->isByRef()) {
1620     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1621     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1622     // offset of __forwarding field
1623     offset = CharUnits::fromQuantity(CGF->LLVMPointerWidth/8);
1624     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1625     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpDeref));
1626     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIFactory::OpPlus));
1627     // offset of x field
1628     offset = CharUnits::fromQuantity(XOffset/8);
1629     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1630   }
1631
1632   // Create the descriptor for the variable.
1633   llvm::DIVariable D =
1634     DebugFactory.CreateComplexVariable(Tag,
1635                                        llvm::DIDescriptor(RegionStack.back()),
1636                                        VD->getName(), Unit, Line, Ty,
1637                                        addr);
1638   // Insert an llvm.dbg.declare into the current block.
1639   llvm::Instruction *Call = 
1640     DebugFactory.InsertDeclare(Storage, D, Builder.GetInsertBlock());
1641
1642   llvm::DIScope DS(RegionStack.back());
1643   llvm::DILocation DO(NULL);
1644   llvm::DILocation DL = 
1645     DebugFactory.CreateLocation(Line, PLoc.getColumn(), DS, DO);
1646   
1647   Call->setMetadata("dbg", DL.getNode());
1648 }
1649
1650 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
1651                                             llvm::Value *Storage,
1652                                             CGBuilderTy &Builder) {
1653   EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder);
1654 }
1655
1656 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
1657   const BlockDeclRefExpr *BDRE, llvm::Value *Storage, CGBuilderTy &Builder,
1658   CodeGenFunction *CGF) {
1659   EmitDeclare(BDRE, llvm::dwarf::DW_TAG_auto_variable, Storage, Builder, CGF);
1660 }
1661
1662 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
1663 /// variable declaration.
1664 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
1665                                            CGBuilderTy &Builder) {
1666   EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, Builder);
1667 }
1668
1669
1670
1671 /// EmitGlobalVariable - Emit information about a global variable.
1672 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1673                                      const VarDecl *D) {
1674   
1675   // Create global variable debug descriptor.
1676   llvm::DIFile Unit = getOrCreateFile(D->getLocation());
1677   SourceManager &SM = CGM.getContext().getSourceManager();
1678   PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation());
1679   unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1680
1681   QualType T = D->getType();
1682   if (T->isIncompleteArrayType()) {
1683
1684     // CodeGen turns int[] into int[1] so we'll do the same here.
1685     llvm::APSInt ConstVal(32);
1686
1687     ConstVal = 1;
1688     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1689
1690     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1691                                            ArrayType::Normal, 0);
1692   }
1693   llvm::StringRef DeclName = Var->getName();
1694   llvm::DIDescriptor DContext = 
1695     getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()), Unit);
1696   DebugFactory.CreateGlobalVariable(DContext, DeclName,
1697                                     DeclName, llvm::StringRef(), Unit, LineNo,
1698                                     getOrCreateType(T, Unit),
1699                                     Var->hasInternalLinkage(),
1700                                     true/*definition*/, Var);
1701 }
1702
1703 /// EmitGlobalVariable - Emit information about an objective-c interface.
1704 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
1705                                      ObjCInterfaceDecl *ID) {
1706   // Create global variable debug descriptor.
1707   llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
1708   SourceManager &SM = CGM.getContext().getSourceManager();
1709   PresumedLoc PLoc = SM.getPresumedLoc(ID->getLocation());
1710   unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1711
1712   llvm::StringRef Name = ID->getName();
1713
1714   QualType T = CGM.getContext().getObjCInterfaceType(ID);
1715   if (T->isIncompleteArrayType()) {
1716
1717     // CodeGen turns int[] into int[1] so we'll do the same here.
1718     llvm::APSInt ConstVal(32);
1719
1720     ConstVal = 1;
1721     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
1722
1723     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
1724                                            ArrayType::Normal, 0);
1725   }
1726
1727   DebugFactory.CreateGlobalVariable(Unit, Name, Name, Name, Unit, LineNo,
1728                                     getOrCreateType(T, Unit),
1729                                     Var->hasInternalLinkage(),
1730                                     true/*definition*/, Var);
1731 }
1732
1733 /// getOrCreateNamesSpace - Return namespace descriptor for the given
1734 /// namespace decl.
1735 llvm::DINameSpace 
1736 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl, 
1737                                   llvm::DIDescriptor Unit) {
1738   llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I = 
1739     NameSpaceCache.find(NSDecl);
1740   if (I != NameSpaceCache.end())
1741     return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
1742   
1743   SourceManager &SM = CGM.getContext().getSourceManager();
1744   PresumedLoc PLoc = SM.getPresumedLoc(NSDecl->getLocation());
1745   unsigned LineNo = PLoc.isInvalid() ? 0 : PLoc.getLine();
1746
1747   llvm::DIDescriptor Context = 
1748     getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()), Unit);
1749   llvm::DINameSpace NS =
1750     DebugFactory.CreateNameSpace(Context, NSDecl->getName(), 
1751         llvm::DIFile(Unit.getNode()), LineNo);
1752   NameSpaceCache[NSDecl] = llvm::WeakVH(NS.getNode());
1753   return NS;
1754 }