]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGDebugInfo.cpp
Copy head to stable/9 as part of 9.0-RELEASE release cycle.
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / 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 "CGBlocks.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclFriend.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/FileManager.h"
26 #include "clang/Basic/Version.h"
27 #include "clang/Frontend/CodeGenOptions.h"
28 #include "llvm/Constants.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/Instructions.h"
31 #include "llvm/Intrinsics.h"
32 #include "llvm/Module.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetMachine.h"
39 using namespace clang;
40 using namespace clang::CodeGen;
41
42 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
43   : CGM(CGM), DBuilder(CGM.getModule()),
44     BlockLiteralGenericSet(false) {
45   CreateCompileUnit();
46 }
47
48 CGDebugInfo::~CGDebugInfo() {
49   assert(RegionStack.empty() && "Region stack mismatch, stack not empty!");
50 }
51
52 void CGDebugInfo::setLocation(SourceLocation Loc) {
53   if (Loc.isValid())
54     CurLoc = CGM.getContext().getSourceManager().getInstantiationLoc(Loc);
55 }
56
57 /// getContextDescriptor - Get context info for the decl.
58 llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
59   if (!Context)
60     return TheCU;
61
62   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
63     I = RegionMap.find(Context);
64   if (I != RegionMap.end())
65     return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second));
66
67   // Check namespace.
68   if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
69     return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
70
71   if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
72     if (!RDecl->isDependentType()) {
73       llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
74                                         getOrCreateMainFile());
75       return llvm::DIDescriptor(Ty);
76     }
77   }
78   return TheCU;
79 }
80
81 /// getFunctionName - Get function name for the given FunctionDecl. If the
82 /// name is constructred on demand (e.g. C++ destructor) then the name
83 /// is stored on the side.
84 llvm::StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
85   assert (FD && "Invalid FunctionDecl!");
86   IdentifierInfo *FII = FD->getIdentifier();
87   if (FII)
88     return FII->getName();
89
90   // Otherwise construct human readable name for debug info.
91   std::string NS = FD->getNameAsString();
92
93   // Copy this name on the side and use its reference.
94   char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
95   memcpy(StrPtr, NS.data(), NS.length());
96   return llvm::StringRef(StrPtr, NS.length());
97 }
98
99 llvm::StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
100   llvm::SmallString<256> MethodName;
101   llvm::raw_svector_ostream OS(MethodName);
102   OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
103   const DeclContext *DC = OMD->getDeclContext();
104   if (const ObjCImplementationDecl *OID = 
105       dyn_cast<const ObjCImplementationDecl>(DC)) {
106      OS << OID->getName();
107   } else if (const ObjCInterfaceDecl *OID = 
108              dyn_cast<const ObjCInterfaceDecl>(DC)) {
109       OS << OID->getName();
110   } else if (const ObjCCategoryImplDecl *OCD = 
111              dyn_cast<const ObjCCategoryImplDecl>(DC)){
112       OS << ((NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
113           OCD->getIdentifier()->getNameStart() << ')';
114   }
115   OS << ' ' << OMD->getSelector().getAsString() << ']';
116
117   char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
118   memcpy(StrPtr, MethodName.begin(), OS.tell());
119   return llvm::StringRef(StrPtr, OS.tell());
120 }
121
122 /// getSelectorName - Return selector name. This is used for debugging
123 /// info.
124 llvm::StringRef CGDebugInfo::getSelectorName(Selector S) {
125   llvm::SmallString<256> SName;
126   llvm::raw_svector_ostream OS(SName);
127   OS << S.getAsString();
128   char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
129   memcpy(StrPtr, SName.begin(), OS.tell());
130   return llvm::StringRef(StrPtr, OS.tell());
131 }
132
133 /// getClassName - Get class name including template argument list.
134 llvm::StringRef 
135 CGDebugInfo::getClassName(RecordDecl *RD) {
136   ClassTemplateSpecializationDecl *Spec
137     = dyn_cast<ClassTemplateSpecializationDecl>(RD);
138   if (!Spec)
139     return RD->getName();
140
141   const TemplateArgument *Args;
142   unsigned NumArgs;
143   std::string Buffer;
144   if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
145     const TemplateSpecializationType *TST =
146       cast<TemplateSpecializationType>(TAW->getType());
147     Args = TST->getArgs();
148     NumArgs = TST->getNumArgs();
149   } else {
150     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
151     Args = TemplateArgs.data();
152     NumArgs = TemplateArgs.size();
153   }
154   Buffer = RD->getIdentifier()->getNameStart();
155   PrintingPolicy Policy(CGM.getLangOptions());
156   Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
157                                                                   NumArgs,
158                                                                   Policy);
159
160   // Copy this name on the side and use its reference.
161   char *StrPtr = DebugInfoNames.Allocate<char>(Buffer.length());
162   memcpy(StrPtr, Buffer.data(), Buffer.length());
163   return llvm::StringRef(StrPtr, Buffer.length());
164 }
165
166 /// getOrCreateFile - Get the file debug info descriptor for the input location.
167 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
168   if (!Loc.isValid())
169     // If Location is not valid then use main input file.
170     return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
171
172   SourceManager &SM = CGM.getContext().getSourceManager();
173   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
174
175   if (PLoc.isInvalid() || llvm::StringRef(PLoc.getFilename()).empty())
176     // If the location is not valid then use main input file.
177     return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
178
179   // Cache the results.
180   const char *fname = PLoc.getFilename();
181   llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
182     DIFileCache.find(fname);
183
184   if (it != DIFileCache.end()) {
185     // Verify that the information still exists.
186     if (&*it->second)
187       return llvm::DIFile(cast<llvm::MDNode>(it->second));
188   }
189
190   llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
191
192   DIFileCache[fname] = F;
193   return F;
194
195 }
196
197 /// getOrCreateMainFile - Get the file info for main compile unit.
198 llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
199   return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
200 }
201
202 /// getLineNumber - Get line number for the location. If location is invalid
203 /// then use current location.
204 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
205   assert (CurLoc.isValid() && "Invalid current location!");
206   SourceManager &SM = CGM.getContext().getSourceManager();
207   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
208   return PLoc.isValid()? PLoc.getLine() : 0;
209 }
210
211 /// getColumnNumber - Get column number for the location. If location is 
212 /// invalid then use current location.
213 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
214   assert (CurLoc.isValid() && "Invalid current location!");
215   SourceManager &SM = CGM.getContext().getSourceManager();
216   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
217   return PLoc.isValid()? PLoc.getColumn() : 0;
218 }
219
220 llvm::StringRef CGDebugInfo::getCurrentDirname() {
221   if (!CWDName.empty())
222     return CWDName;
223   char *CompDirnamePtr = NULL;
224   llvm::sys::Path CWD = llvm::sys::Path::GetCurrentDirectory();
225   CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
226   memcpy(CompDirnamePtr, CWD.c_str(), CWD.size());
227   return CWDName = llvm::StringRef(CompDirnamePtr, CWD.size());
228 }
229
230 /// CreateCompileUnit - Create new compile unit.
231 void CGDebugInfo::CreateCompileUnit() {
232
233   // Get absolute path name.
234   SourceManager &SM = CGM.getContext().getSourceManager();
235   std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
236   if (MainFileName.empty())
237     MainFileName = "<unknown>";
238
239   // The main file name provided via the "-main-file-name" option contains just
240   // the file name itself with no path information. This file name may have had
241   // a relative path, so we look into the actual file entry for the main
242   // file to determine the real absolute path for the file.
243   std::string MainFileDir;
244   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
245     MainFileDir = MainFile->getDir()->getName();
246     if (MainFileDir != ".")
247       MainFileName = MainFileDir + "/" + MainFileName;
248   }
249
250   // Save filename string.
251   char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
252   memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
253   llvm::StringRef Filename(FilenamePtr, MainFileName.length());
254   
255   unsigned LangTag;
256   const LangOptions &LO = CGM.getLangOptions();
257   if (LO.CPlusPlus) {
258     if (LO.ObjC1)
259       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
260     else
261       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
262   } else if (LO.ObjC1) {
263     LangTag = llvm::dwarf::DW_LANG_ObjC;
264   } else if (LO.C99) {
265     LangTag = llvm::dwarf::DW_LANG_C99;
266   } else {
267     LangTag = llvm::dwarf::DW_LANG_C89;
268   }
269
270   std::string Producer = getClangFullVersion();
271
272   // Figure out which version of the ObjC runtime we have.
273   unsigned RuntimeVers = 0;
274   if (LO.ObjC1)
275     RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
276
277   // Create new compile unit.
278   DBuilder.createCompileUnit(
279     LangTag, Filename, getCurrentDirname(),
280     Producer,
281     LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
282   // FIXME - Eliminate TheCU.
283   TheCU = llvm::DICompileUnit(DBuilder.getCU());
284 }
285
286 /// CreateType - Get the Basic type from the cache or create a new
287 /// one if necessary.
288 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
289   unsigned Encoding = 0;
290   const char *BTName = NULL;
291   switch (BT->getKind()) {
292   default:
293   case BuiltinType::Void:
294     return llvm::DIType();
295   case BuiltinType::ObjCClass:
296     return DBuilder.createStructType(TheCU, "objc_class", 
297                                      getOrCreateMainFile(), 0, 0, 0,
298                                      llvm::DIDescriptor::FlagFwdDecl, 
299                                      llvm::DIArray());
300   case BuiltinType::ObjCId: {
301     // typedef struct objc_class *Class;
302     // typedef struct objc_object {
303     //  Class isa;
304     // } *id;
305
306     llvm::DIType OCTy = 
307       DBuilder.createStructType(TheCU, "objc_class", 
308                                 getOrCreateMainFile(), 0, 0, 0,
309                                 llvm::DIDescriptor::FlagFwdDecl, 
310                                 llvm::DIArray());
311     unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
312     
313     llvm::DIType ISATy = DBuilder.createPointerType(OCTy, Size);
314
315     llvm::SmallVector<llvm::Value *, 16> EltTys;
316     llvm::DIType FieldTy = 
317       DBuilder.createMemberType(getOrCreateMainFile(), "isa",
318                                 getOrCreateMainFile(), 0, Size,
319                                 0, 0, 0, ISATy);
320     EltTys.push_back(FieldTy);
321     llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
322     
323     return DBuilder.createStructType(TheCU, "objc_object", 
324                                      getOrCreateMainFile(),
325                                      0, 0, 0, 0, Elements);
326   }
327   case BuiltinType::ObjCSel: {
328     return  DBuilder.createStructType(TheCU, "objc_selector", 
329                                       getOrCreateMainFile(), 0, 0, 0,
330                                       llvm::DIDescriptor::FlagFwdDecl, 
331                                       llvm::DIArray());
332   }
333   case BuiltinType::UChar:
334   case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
335   case BuiltinType::Char_S:
336   case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
337   case BuiltinType::UShort:
338   case BuiltinType::UInt:
339   case BuiltinType::UInt128:
340   case BuiltinType::ULong:
341   case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
342   case BuiltinType::Short:
343   case BuiltinType::Int:
344   case BuiltinType::Int128:
345   case BuiltinType::Long:
346   case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
347   case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
348   case BuiltinType::Float:
349   case BuiltinType::LongDouble:
350   case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
351   }
352
353   switch (BT->getKind()) {
354   case BuiltinType::Long:      BTName = "long int"; break;
355   case BuiltinType::LongLong:  BTName = "long long int"; break;
356   case BuiltinType::ULong:     BTName = "long unsigned int"; break;
357   case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
358   default:
359     BTName = BT->getName(CGM.getContext().getLangOptions());
360     break;
361   }
362   // Bit size, align and offset of the type.
363   uint64_t Size = CGM.getContext().getTypeSize(BT);
364   uint64_t Align = CGM.getContext().getTypeAlign(BT);
365   llvm::DIType DbgTy = 
366     DBuilder.createBasicType(BTName, Size, Align, Encoding);
367   return DbgTy;
368 }
369
370 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
371   // Bit size, align and offset of the type.
372   unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
373   if (Ty->isComplexIntegerType())
374     Encoding = llvm::dwarf::DW_ATE_lo_user;
375
376   uint64_t Size = CGM.getContext().getTypeSize(Ty);
377   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
378   llvm::DIType DbgTy = 
379     DBuilder.createBasicType("complex", Size, Align, Encoding);
380
381   return DbgTy;
382 }
383
384 /// CreateCVRType - Get the qualified type from the cache or create
385 /// a new one if necessary.
386 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
387   QualifierCollector Qc;
388   const Type *T = Qc.strip(Ty);
389
390   // Ignore these qualifiers for now.
391   Qc.removeObjCGCAttr();
392   Qc.removeAddressSpace();
393   Qc.removeObjCLifetime();
394
395   // We will create one Derived type for one qualifier and recurse to handle any
396   // additional ones.
397   unsigned Tag;
398   if (Qc.hasConst()) {
399     Tag = llvm::dwarf::DW_TAG_const_type;
400     Qc.removeConst();
401   } else if (Qc.hasVolatile()) {
402     Tag = llvm::dwarf::DW_TAG_volatile_type;
403     Qc.removeVolatile();
404   } else if (Qc.hasRestrict()) {
405     Tag = llvm::dwarf::DW_TAG_restrict_type;
406     Qc.removeRestrict();
407   } else {
408     assert(Qc.empty() && "Unknown type qualifier for debug info");
409     return getOrCreateType(QualType(T, 0), Unit);
410   }
411
412   llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
413
414   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
415   // CVR derived types.
416   llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
417   
418   return DbgTy;
419 }
420
421 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
422                                      llvm::DIFile Unit) {
423   llvm::DIType DbgTy =
424     CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 
425                           Ty->getPointeeType(), Unit);
426   return DbgTy;
427 }
428
429 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
430                                      llvm::DIFile Unit) {
431   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, 
432                                Ty->getPointeeType(), Unit);
433 }
434
435 /// CreatePointeeType - Create PointTee type. If Pointee is a record
436 /// then emit record's fwd if debug info size reduction is enabled.
437 llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
438                                             llvm::DIFile Unit) {
439   if (!CGM.getCodeGenOpts().LimitDebugInfo)
440     return getOrCreateType(PointeeTy, Unit);
441   
442   if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
443     RecordDecl *RD = RTy->getDecl();
444     llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
445     unsigned Line = getLineNumber(RD->getLocation());
446     llvm::DIDescriptor FDContext =
447       getContextDescriptor(cast<Decl>(RD->getDeclContext()));
448
449     if (RD->isStruct())
450       return DBuilder.createStructType(FDContext, RD->getName(), DefUnit,
451                                        Line, 0, 0, llvm::DIType::FlagFwdDecl,
452                                        llvm::DIArray());
453     else if (RD->isUnion())
454       return DBuilder.createUnionType(FDContext, RD->getName(), DefUnit,
455                                       Line, 0, 0, llvm::DIType::FlagFwdDecl,
456                                       llvm::DIArray());
457     else {
458       assert(RD->isClass() && "Unknown RecordType!");
459       return DBuilder.createClassType(FDContext, RD->getName(), DefUnit,
460                                       Line, 0, 0, 0, llvm::DIType::FlagFwdDecl,
461                                       llvm::DIType(), llvm::DIArray());
462     }
463   }
464   return getOrCreateType(PointeeTy, Unit);
465
466 }
467
468 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
469                                                 const Type *Ty, 
470                                                 QualType PointeeTy,
471                                                 llvm::DIFile Unit) {
472
473   if (Tag == llvm::dwarf::DW_TAG_reference_type)
474     return DBuilder.createReferenceType(CreatePointeeType(PointeeTy, Unit));
475                                     
476   // Bit size, align and offset of the type.
477   // Size is always the size of a pointer. We can't use getTypeSize here
478   // because that does not return the correct value for references.
479   unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
480   uint64_t Size = CGM.getContext().Target.getPointerWidth(AS);
481   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
482
483   return 
484     DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit), Size, Align);
485 }
486
487 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
488                                      llvm::DIFile Unit) {
489   if (BlockLiteralGenericSet)
490     return BlockLiteralGeneric;
491
492   llvm::SmallVector<llvm::Value *, 8> EltTys;
493   llvm::DIType FieldTy;
494   QualType FType;
495   uint64_t FieldSize, FieldOffset;
496   unsigned FieldAlign;
497   llvm::DIArray Elements;
498   llvm::DIType EltTy, DescTy;
499
500   FieldOffset = 0;
501   FType = CGM.getContext().UnsignedLongTy;
502   EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
503   EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
504
505   Elements = DBuilder.getOrCreateArray(EltTys);
506   EltTys.clear();
507
508   unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
509   unsigned LineNo = getLineNumber(CurLoc);
510
511   EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
512                                     Unit, LineNo, FieldOffset, 0,
513                                     Flags, Elements);
514
515   // Bit size, align and offset of the type.
516   uint64_t Size = CGM.getContext().getTypeSize(Ty);
517
518   DescTy = DBuilder.createPointerType(EltTy, Size);
519
520   FieldOffset = 0;
521   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
522   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
523   FType = CGM.getContext().IntTy;
524   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
525   EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
526   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
527   EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
528
529   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
530   FieldTy = DescTy;
531   FieldSize = CGM.getContext().getTypeSize(Ty);
532   FieldAlign = CGM.getContext().getTypeAlign(Ty);
533   FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
534                                       LineNo, FieldSize, FieldAlign,
535                                       FieldOffset, 0, FieldTy);
536   EltTys.push_back(FieldTy);
537
538   FieldOffset += FieldSize;
539   Elements = DBuilder.getOrCreateArray(EltTys);
540
541   EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
542                                     Unit, LineNo, FieldOffset, 0,
543                                     Flags, Elements);
544
545   BlockLiteralGenericSet = true;
546   BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
547   return BlockLiteralGeneric;
548 }
549
550 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
551                                      llvm::DIFile Unit) {
552   // Typedefs are derived from some other type.  If we have a typedef of a
553   // typedef, make sure to emit the whole chain.
554   llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
555   if (!Src.Verify())
556     return llvm::DIType();
557   // We don't set size information, but do specify where the typedef was
558   // declared.
559   unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
560   const TypedefNameDecl *TyDecl = Ty->getDecl();
561   llvm::DIDescriptor TydefContext =
562     getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
563
564   return  
565     DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TydefContext);
566 }
567
568 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
569                                      llvm::DIFile Unit) {
570   llvm::SmallVector<llvm::Value *, 16> EltTys;
571
572   // Add the result type at least.
573   EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
574
575   // Set up remainder of arguments if there is a prototype.
576   // FIXME: IF NOT, HOW IS THIS REPRESENTED?  llvm-gcc doesn't represent '...'!
577   if (isa<FunctionNoProtoType>(Ty))
578     EltTys.push_back(DBuilder.createUnspecifiedParameter());
579   else if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
580     for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
581       EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
582   }
583
584   llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
585
586   llvm::DIType DbgTy = DBuilder.createSubroutineType(Unit, EltTypeArray);
587   return DbgTy;
588 }
589
590 llvm::DIType CGDebugInfo::createFieldType(llvm::StringRef name,
591                                           QualType type,
592                                           Expr *bitWidth,
593                                           SourceLocation loc,
594                                           AccessSpecifier AS,
595                                           uint64_t offsetInBits,
596                                           llvm::DIFile tunit,
597                                           llvm::DIDescriptor scope) {
598   llvm::DIType debugType = getOrCreateType(type, tunit);
599
600   // Get the location for the field.
601   llvm::DIFile file = getOrCreateFile(loc);
602   unsigned line = getLineNumber(loc);
603
604   uint64_t sizeInBits = 0;
605   unsigned alignInBits = 0;
606   if (!type->isIncompleteArrayType()) {
607     llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
608
609     if (bitWidth)
610       sizeInBits = bitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
611   }
612
613   unsigned flags = 0;
614   if (AS == clang::AS_private)
615     flags |= llvm::DIDescriptor::FlagPrivate;
616   else if (AS == clang::AS_protected)
617     flags |= llvm::DIDescriptor::FlagProtected;
618
619   return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
620                                    alignInBits, offsetInBits, flags, debugType);
621 }
622
623 /// CollectRecordFields - A helper function to collect debug info for
624 /// record fields. This is used while creating debug info entry for a Record.
625 void CGDebugInfo::
626 CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
627                     llvm::SmallVectorImpl<llvm::Value *> &elements,
628                     llvm::DIType RecordTy) {
629   unsigned fieldNo = 0;
630   const FieldDecl *LastFD = 0;
631   bool IsMsStruct = record->hasAttr<MsStructAttr>();
632   
633   const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
634   for (RecordDecl::field_iterator I = record->field_begin(),
635                                   E = record->field_end();
636        I != E; ++I, ++fieldNo) {
637     FieldDecl *field = *I;
638     if (IsMsStruct) {
639       // Zero-length bitfields following non-bitfield members are ignored
640       if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) {
641         --fieldNo;
642         continue;
643       }
644       LastFD = field;
645     }
646
647     llvm::StringRef name = field->getName();
648     QualType type = field->getType();
649
650     // Ignore unnamed fields unless they're anonymous structs/unions.
651     if (name.empty() && !type->isRecordType()) {
652       LastFD = field;
653       continue;
654     }
655
656     llvm::DIType fieldType
657       = createFieldType(name, type, field->getBitWidth(),
658                         field->getLocation(), field->getAccess(),
659                         layout.getFieldOffset(fieldNo), tunit, RecordTy);
660
661     elements.push_back(fieldType);
662   }
663 }
664
665 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
666 /// function type is not updated to include implicit "this" pointer. Use this
667 /// routine to get a method type which includes "this" pointer.
668 llvm::DIType
669 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
670                                    llvm::DIFile Unit) {
671   llvm::DIType FnTy
672     = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
673                                0),
674                       Unit);
675   
676   // Add "this" pointer.
677
678   llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
679   assert (Args.getNumElements() && "Invalid number of arguments!");
680
681   llvm::SmallVector<llvm::Value *, 16> Elts;
682
683   // First element is always return type. For 'void' functions it is NULL.
684   Elts.push_back(Args.getElement(0));
685
686   if (!Method->isStatic())
687   {
688         // "this" pointer is always first argument.
689         QualType ThisPtr = Method->getThisType(CGM.getContext());
690         llvm::DIType ThisPtrType =
691           DBuilder.createArtificialType(getOrCreateType(ThisPtr, Unit));
692
693         TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
694         Elts.push_back(ThisPtrType);
695     }
696
697   // Copy rest of the arguments.
698   for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
699     Elts.push_back(Args.getElement(i));
700
701   llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
702
703   return DBuilder.createSubroutineType(Unit, EltTypeArray);
704 }
705
706 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined 
707 /// inside a function.
708 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
709   if (const CXXRecordDecl *NRD = 
710       dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
711     return isFunctionLocalClass(NRD);
712   else if (isa<FunctionDecl>(RD->getDeclContext()))
713     return true;
714   return false;
715   
716 }
717 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
718 /// a single member function GlobalDecl.
719 llvm::DISubprogram
720 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
721                                      llvm::DIFile Unit,
722                                      llvm::DIType RecordTy) {
723   bool IsCtorOrDtor = 
724     isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
725   
726   llvm::StringRef MethodName = getFunctionName(Method);
727   llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
728   
729   // Since a single ctor/dtor corresponds to multiple functions, it doesn't
730   // make sense to give a single ctor/dtor a linkage name.
731   llvm::StringRef MethodLinkageName;
732   if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
733     MethodLinkageName = CGM.getMangledName(Method);
734
735   // Get the location for the method.
736   llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
737   unsigned MethodLine = getLineNumber(Method->getLocation());
738
739   // Collect virtual method info.
740   llvm::DIType ContainingType;
741   unsigned Virtuality = 0; 
742   unsigned VIndex = 0;
743   
744   if (Method->isVirtual()) {
745     if (Method->isPure())
746       Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
747     else
748       Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
749     
750     // It doesn't make sense to give a virtual destructor a vtable index,
751     // since a single destructor has two entries in the vtable.
752     if (!isa<CXXDestructorDecl>(Method))
753       VIndex = CGM.getVTables().getMethodVTableIndex(Method);
754     ContainingType = RecordTy;
755   }
756
757   unsigned Flags = 0;
758   if (Method->isImplicit())
759     Flags |= llvm::DIDescriptor::FlagArtificial;
760   AccessSpecifier Access = Method->getAccess();
761   if (Access == clang::AS_private)
762     Flags |= llvm::DIDescriptor::FlagPrivate;
763   else if (Access == clang::AS_protected)
764     Flags |= llvm::DIDescriptor::FlagProtected;
765   if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
766     if (CXXC->isExplicit())
767       Flags |= llvm::DIDescriptor::FlagExplicit;
768   } else if (const CXXConversionDecl *CXXC = 
769              dyn_cast<CXXConversionDecl>(Method)) {
770     if (CXXC->isExplicit())
771       Flags |= llvm::DIDescriptor::FlagExplicit;
772   }
773   if (Method->hasPrototype())
774     Flags |= llvm::DIDescriptor::FlagPrototyped;
775     
776   llvm::DISubprogram SP =
777     DBuilder.createMethod(RecordTy , MethodName, MethodLinkageName, 
778                           MethodDefUnit, MethodLine,
779                           MethodTy, /*isLocalToUnit=*/false, 
780                           /* isDefinition=*/ false,
781                           Virtuality, VIndex, ContainingType,
782                           Flags, CGM.getLangOptions().Optimize);
783   
784   SPCache[Method] = llvm::WeakVH(SP);
785
786   return SP;
787 }
788
789 /// CollectCXXMemberFunctions - A helper function to collect debug info for
790 /// C++ member functions.This is used while creating debug info entry for 
791 /// a Record.
792 void CGDebugInfo::
793 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
794                           llvm::SmallVectorImpl<llvm::Value *> &EltTys,
795                           llvm::DIType RecordTy) {
796   for(CXXRecordDecl::method_iterator I = RD->method_begin(),
797         E = RD->method_end(); I != E; ++I) {
798     const CXXMethodDecl *Method = *I;
799     
800     if (Method->isImplicit() && !Method->isUsed())
801       continue;
802
803     EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
804   }
805 }                                 
806
807 /// CollectCXXFriends - A helper function to collect debug info for
808 /// C++ base classes. This is used while creating debug info entry for
809 /// a Record.
810 void CGDebugInfo::
811 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
812                 llvm::SmallVectorImpl<llvm::Value *> &EltTys,
813                 llvm::DIType RecordTy) {
814
815   for (CXXRecordDecl::friend_iterator BI =  RD->friend_begin(),
816          BE = RD->friend_end(); BI != BE; ++BI) {
817     if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
818       EltTys.push_back(DBuilder.createFriend(RecordTy, 
819                                              getOrCreateType(TInfo->getType(), 
820                                                              Unit)));
821   }
822 }
823
824 /// CollectCXXBases - A helper function to collect debug info for
825 /// C++ base classes. This is used while creating debug info entry for 
826 /// a Record.
827 void CGDebugInfo::
828 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
829                 llvm::SmallVectorImpl<llvm::Value *> &EltTys,
830                 llvm::DIType RecordTy) {
831
832   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
833   for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
834          BE = RD->bases_end(); BI != BE; ++BI) {
835     unsigned BFlags = 0;
836     uint64_t BaseOffset;
837     
838     const CXXRecordDecl *Base =
839       cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
840     
841     if (BI->isVirtual()) {
842       // virtual base offset offset is -ve. The code generator emits dwarf
843       // expression where it expects +ve number.
844       BaseOffset = 
845         0 - CGM.getVTables().getVirtualBaseOffsetOffset(RD, Base).getQuantity();
846       BFlags = llvm::DIDescriptor::FlagVirtual;
847     } else
848       BaseOffset = RL.getBaseClassOffsetInBits(Base);
849     // FIXME: Inconsistent units for BaseOffset. It is in bytes when
850     // BI->isVirtual() and bits when not.
851     
852     AccessSpecifier Access = BI->getAccessSpecifier();
853     if (Access == clang::AS_private)
854       BFlags |= llvm::DIDescriptor::FlagPrivate;
855     else if (Access == clang::AS_protected)
856       BFlags |= llvm::DIDescriptor::FlagProtected;
857     
858     llvm::DIType DTy = 
859       DBuilder.createInheritance(RecordTy,                                     
860                                  getOrCreateType(BI->getType(), Unit),
861                                  BaseOffset, BFlags);
862     EltTys.push_back(DTy);
863   }
864 }
865
866 /// CollectTemplateParams - A helper function to collect template parameters.
867 llvm::DIArray CGDebugInfo::
868 CollectTemplateParams(const TemplateParameterList *TPList,
869                       const TemplateArgumentList &TAList,
870                       llvm::DIFile Unit) {
871   llvm::SmallVector<llvm::Value *, 16> TemplateParams;  
872   for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
873     const TemplateArgument &TA = TAList[i];
874     const NamedDecl *ND = TPList->getParam(i);
875     if (TA.getKind() == TemplateArgument::Type) {
876       llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
877       llvm::DITemplateTypeParameter TTP =
878         DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
879       TemplateParams.push_back(TTP);
880     } else if (TA.getKind() == TemplateArgument::Integral) {
881       llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
882       llvm::DITemplateValueParameter TVP =
883         DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
884                                           TA.getAsIntegral()->getZExtValue());
885       TemplateParams.push_back(TVP);          
886     }
887   }
888   return DBuilder.getOrCreateArray(TemplateParams);
889 }
890
891 /// CollectFunctionTemplateParams - A helper function to collect debug
892 /// info for function template parameters.
893 llvm::DIArray CGDebugInfo::
894 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
895   if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization){
896     const TemplateParameterList *TList =
897       FD->getTemplateSpecializationInfo()->getTemplate()->getTemplateParameters();
898     return 
899       CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
900   }
901   return llvm::DIArray();
902 }
903
904 /// CollectCXXTemplateParams - A helper function to collect debug info for
905 /// template parameters.
906 llvm::DIArray CGDebugInfo::
907 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
908                          llvm::DIFile Unit) {
909   llvm::PointerUnion<ClassTemplateDecl *,
910                      ClassTemplatePartialSpecializationDecl *>
911     PU = TSpecial->getSpecializedTemplateOrPartial();
912   
913   TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
914     PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
915     PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
916   const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
917   return CollectTemplateParams(TPList, TAList, Unit);
918 }
919
920 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
921 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
922   if (VTablePtrType.isValid())
923     return VTablePtrType;
924
925   ASTContext &Context = CGM.getContext();
926
927   /* Function type */
928   llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
929   llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
930   llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
931   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
932   llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
933                                                           "__vtbl_ptr_type");
934   VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
935   return VTablePtrType;
936 }
937
938 /// getVTableName - Get vtable name for the given Class.
939 llvm::StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
940   // Otherwise construct gdb compatible name name.
941   std::string Name = "_vptr$" + RD->getNameAsString();
942
943   // Copy this name on the side and use its reference.
944   char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
945   memcpy(StrPtr, Name.data(), Name.length());
946   return llvm::StringRef(StrPtr, Name.length());
947 }
948
949
950 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
951 /// debug info entry in EltTys vector.
952 void CGDebugInfo::
953 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
954                   llvm::SmallVectorImpl<llvm::Value *> &EltTys) {
955   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
956
957   // If there is a primary base then it will hold vtable info.
958   if (RL.getPrimaryBase())
959     return;
960
961   // If this class is not dynamic then there is not any vtable info to collect.
962   if (!RD->isDynamicClass())
963     return;
964
965   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
966   llvm::DIType VPTR
967     = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
968                                 0, Size, 0, 0, 0, 
969                                 getOrCreateVTablePtrType(Unit));
970   EltTys.push_back(VPTR);
971 }
972
973 /// getOrCreateRecordType - Emit record type's standalone debug info. 
974 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy, 
975                                                 SourceLocation Loc) {
976   llvm::DIType T =  getOrCreateType(RTy, getOrCreateFile(Loc));
977   DBuilder.retainType(T);
978   return T;
979 }
980
981 /// CreateType - get structure or union type.
982 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
983   RecordDecl *RD = Ty->getDecl();
984   llvm::DIFile Unit = getOrCreateFile(RD->getLocation());
985
986   // Get overall information about the record type for the debug info.
987   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
988   unsigned Line = getLineNumber(RD->getLocation());
989
990   // Records and classes and unions can all be recursive.  To handle them, we
991   // first generate a debug descriptor for the struct as a forward declaration.
992   // Then (if it is a definition) we go through and get debug info for all of
993   // its members.  Finally, we create a descriptor for the complete type (which
994   // may refer to the forward decl if the struct is recursive) and replace all
995   // uses of the forward declaration with the final definition.
996   llvm::DIDescriptor FDContext =
997     getContextDescriptor(cast<Decl>(RD->getDeclContext()));
998
999   // If this is just a forward declaration, construct an appropriately
1000   // marked node and just return it.
1001   if (!RD->getDefinition()) {
1002     llvm::DIType FwdDecl =
1003       DBuilder.createStructType(FDContext, RD->getName(),
1004                                 DefUnit, Line, 0, 0,
1005                                 llvm::DIDescriptor::FlagFwdDecl,
1006                                 llvm::DIArray());
1007
1008       return FwdDecl;
1009   }
1010
1011   llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit);
1012
1013   llvm::MDNode *MN = FwdDecl;
1014   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1015   // Otherwise, insert it into the TypeCache so that recursive uses will find
1016   // it.
1017   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1018   // Push the struct on region stack.
1019   RegionStack.push_back(FwdDeclNode);
1020   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1021
1022   // Convert all the elements.
1023   llvm::SmallVector<llvm::Value *, 16> EltTys;
1024
1025   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1026   if (CXXDecl) {
1027     CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
1028     CollectVTableInfo(CXXDecl, Unit, EltTys);
1029   }
1030   
1031   // Collect static variables with initializers.
1032   for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
1033        I != E; ++I)
1034     if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
1035       if (const Expr *Init = V->getInit()) {
1036         Expr::EvalResult Result;
1037         if (Init->Evaluate(Result, CGM.getContext()) && Result.Val.isInt()) {
1038           llvm::ConstantInt *CI 
1039             = llvm::ConstantInt::get(CGM.getLLVMContext(), Result.Val.getInt());
1040           
1041           // Create the descriptor for static variable.
1042           llvm::DIFile VUnit = getOrCreateFile(V->getLocation());
1043           llvm::StringRef VName = V->getName();
1044           llvm::DIType VTy = getOrCreateType(V->getType(), VUnit);
1045           // Do not use DIGlobalVariable for enums.
1046           if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) {
1047             DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit,
1048                                           getLineNumber(V->getLocation()),
1049                                           VTy, true, CI);
1050           }
1051         }
1052       }
1053     }
1054
1055   CollectRecordFields(RD, Unit, EltTys, FwdDecl);
1056   llvm::DIArray TParamsArray;
1057   if (CXXDecl) {
1058     CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
1059     CollectCXXFriends(CXXDecl, Unit, EltTys, FwdDecl);
1060     if (const ClassTemplateSpecializationDecl *TSpecial
1061         = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1062       TParamsArray = CollectCXXTemplateParams(TSpecial, Unit);
1063   }
1064
1065   RegionStack.pop_back();
1066   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI = 
1067     RegionMap.find(Ty->getDecl());
1068   if (RI != RegionMap.end())
1069     RegionMap.erase(RI);
1070
1071   llvm::DIDescriptor RDContext =  
1072     getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1073   llvm::StringRef RDName = RD->getName();
1074   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1075   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1076   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1077   llvm::MDNode *RealDecl = NULL;
1078
1079   if (RD->isUnion())
1080     RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
1081                                         Size, Align, 0, Elements);
1082   else if (CXXDecl) {
1083     RDName = getClassName(RD);
1084      // A class's primary base or the class itself contains the vtable.
1085     llvm::MDNode *ContainingType = NULL;
1086     const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1087     if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
1088       // Seek non virtual primary base root.
1089       while (1) {
1090         const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
1091         const CXXRecordDecl *PBT = BRL.getPrimaryBase();
1092         if (PBT && !BRL.isPrimaryBaseVirtual())
1093           PBase = PBT;
1094         else 
1095           break;
1096       }
1097       ContainingType = 
1098         getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit);
1099     }
1100     else if (CXXDecl->isDynamicClass()) 
1101       ContainingType = FwdDecl;
1102
1103    RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
1104                                        Size, Align, 0, 0, llvm::DIType(),
1105                                        Elements, ContainingType,
1106                                        TParamsArray);
1107   } else 
1108     RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
1109                                          Size, Align, 0, Elements);
1110
1111   // Now that we have a real decl for the struct, replace anything using the
1112   // old decl with the new one.  This will recursively update the debug info.
1113   llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1114   RegionMap[RD] = llvm::WeakVH(RealDecl);
1115   return llvm::DIType(RealDecl);
1116 }
1117
1118 /// CreateType - get objective-c object type.
1119 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1120                                      llvm::DIFile Unit) {
1121   // Ignore protocols.
1122   return getOrCreateType(Ty->getBaseType(), Unit);
1123 }
1124
1125 /// CreateType - get objective-c interface type.
1126 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1127                                      llvm::DIFile Unit) {
1128   ObjCInterfaceDecl *ID = Ty->getDecl();
1129   if (!ID)
1130     return llvm::DIType();
1131
1132   // Get overall information about the record type for the debug info.
1133   llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1134   unsigned Line = getLineNumber(ID->getLocation());
1135   unsigned RuntimeLang = TheCU.getLanguage();
1136
1137   // If this is just a forward declaration, return a special forward-declaration
1138   // debug type.
1139   if (ID->isForwardDecl()) {
1140     llvm::DIType FwdDecl =
1141       DBuilder.createStructType(Unit, ID->getName(),
1142                                 DefUnit, Line, 0, 0, 0,
1143                                 llvm::DIArray(), RuntimeLang);
1144     return FwdDecl;
1145   }
1146
1147   // To handle recursive interface, we
1148   // first generate a debug descriptor for the struct as a forward declaration.
1149   // Then (if it is a definition) we go through and get debug info for all of
1150   // its members.  Finally, we create a descriptor for the complete type (which
1151   // may refer to the forward decl if the struct is recursive) and replace all
1152   // uses of the forward declaration with the final definition.
1153   llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit);
1154
1155   llvm::MDNode *MN = FwdDecl;
1156   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1157   // Otherwise, insert it into the TypeCache so that recursive uses will find
1158   // it.
1159   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1160   // Push the struct on region stack.
1161   RegionStack.push_back(FwdDeclNode);
1162   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1163
1164   // Convert all the elements.
1165   llvm::SmallVector<llvm::Value *, 16> EltTys;
1166
1167   ObjCInterfaceDecl *SClass = ID->getSuperClass();
1168   if (SClass) {
1169     llvm::DIType SClassTy =
1170       getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1171     if (!SClassTy.isValid())
1172       return llvm::DIType();
1173     
1174     llvm::DIType InhTag =
1175       DBuilder.createInheritance(FwdDecl, SClassTy, 0, 0);
1176     EltTys.push_back(InhTag);
1177   }
1178
1179   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1180
1181   unsigned FieldNo = 0;
1182   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1183        Field = Field->getNextIvar(), ++FieldNo) {
1184     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1185     if (!FieldTy.isValid())
1186       return llvm::DIType();
1187     
1188     llvm::StringRef FieldName = Field->getName();
1189
1190     // Ignore unnamed fields.
1191     if (FieldName.empty())
1192       continue;
1193
1194     // Get the location for the field.
1195     llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1196     unsigned FieldLine = getLineNumber(Field->getLocation());
1197     QualType FType = Field->getType();
1198     uint64_t FieldSize = 0;
1199     unsigned FieldAlign = 0;
1200
1201     if (!FType->isIncompleteArrayType()) {
1202
1203       // Bit size, align and offset of the type.
1204       FieldSize = CGM.getContext().getTypeSize(FType);
1205       Expr *BitWidth = Field->getBitWidth();
1206       if (BitWidth)
1207         FieldSize = BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
1208
1209       FieldAlign =  CGM.getContext().getTypeAlign(FType);
1210     }
1211
1212     uint64_t FieldOffset = RL.getFieldOffset(FieldNo);
1213
1214     unsigned Flags = 0;
1215     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1216       Flags = llvm::DIDescriptor::FlagProtected;
1217     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1218       Flags = llvm::DIDescriptor::FlagPrivate;
1219
1220     llvm::StringRef PropertyName;
1221     llvm::StringRef PropertyGetter;
1222     llvm::StringRef PropertySetter;
1223     unsigned PropertyAttributes = 0;
1224     if (ObjCPropertyDecl *PD =
1225         ID->FindPropertyVisibleInPrimaryClass(Field->getIdentifier())) {
1226       PropertyName = PD->getName();
1227       PropertyGetter = getSelectorName(PD->getGetterName());
1228       PropertySetter = getSelectorName(PD->getSetterName());
1229       PropertyAttributes = PD->getPropertyAttributes();
1230     }
1231     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1232                                       FieldLine, FieldSize, FieldAlign,
1233                                       FieldOffset, Flags, FieldTy,
1234                                       PropertyName, PropertyGetter,
1235                                       PropertySetter, PropertyAttributes);
1236     EltTys.push_back(FieldTy);
1237   }
1238
1239   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1240
1241   RegionStack.pop_back();
1242   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI = 
1243     RegionMap.find(Ty->getDecl());
1244   if (RI != RegionMap.end())
1245     RegionMap.erase(RI);
1246
1247   // Bit size, align and offset of the type.
1248   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1249   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1250
1251   unsigned Flags = 0;
1252   if (ID->getImplementation())
1253     Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1254
1255   llvm::DIType RealDecl =
1256     DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1257                                   Line, Size, Align, Flags,
1258                                   Elements, RuntimeLang);
1259
1260   // Now that we have a real decl for the struct, replace anything using the
1261   // old decl with the new one.  This will recursively update the debug info.
1262   llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1263   RegionMap[ID] = llvm::WeakVH(RealDecl);
1264
1265   return RealDecl;
1266 }
1267
1268 llvm::DIType CGDebugInfo::CreateType(const TagType *Ty) {
1269   if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1270     return CreateType(RT);
1271   else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1272     return CreateEnumType(ET->getDecl());
1273
1274   return llvm::DIType();
1275 }
1276
1277 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1278                                      llvm::DIFile Unit) {
1279   llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1280   int64_t NumElems = Ty->getNumElements();
1281   int64_t LowerBound = 0;
1282   if (NumElems == 0)
1283     // If number of elements are not known then this is an unbounded array.
1284     // Use Low = 1, Hi = 0 to express such arrays.
1285     LowerBound = 1;
1286   else
1287     --NumElems;
1288
1289   llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems);
1290   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1291
1292   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1293   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1294
1295   return
1296     DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1297 }
1298
1299 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1300                                      llvm::DIFile Unit) {
1301   uint64_t Size;
1302   uint64_t Align;
1303
1304
1305   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1306   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1307     Size = 0;
1308     Align =
1309       CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1310   } else if (Ty->isIncompleteArrayType()) {
1311     Size = 0;
1312     Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1313   } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1314     Size = 0;
1315     Align = 0;
1316   } else {
1317     // Size and align of the whole array, not the element type.
1318     Size = CGM.getContext().getTypeSize(Ty);
1319     Align = CGM.getContext().getTypeAlign(Ty);
1320   }
1321
1322   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1323   // interior arrays, do we care?  Why aren't nested arrays represented the
1324   // obvious/recursive way?
1325   llvm::SmallVector<llvm::Value *, 8> Subscripts;
1326   QualType EltTy(Ty, 0);
1327   if (Ty->isIncompleteArrayType())
1328     EltTy = Ty->getElementType();
1329   else {
1330     while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1331       int64_t UpperBound = 0;
1332       int64_t LowerBound = 0;
1333       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
1334         if (CAT->getSize().getZExtValue())
1335           UpperBound = CAT->getSize().getZExtValue() - 1;
1336       } else
1337         // This is an unbounded array. Use Low = 1, Hi = 0 to express such 
1338         // arrays.
1339         LowerBound = 1;
1340
1341       // FIXME: Verify this is right for VLAs.
1342       Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound, UpperBound));
1343       EltTy = Ty->getElementType();
1344     }
1345   }
1346
1347   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1348
1349   llvm::DIType DbgTy = 
1350     DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1351                              SubscriptArray);
1352   return DbgTy;
1353 }
1354
1355 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty, 
1356                                      llvm::DIFile Unit) {
1357   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, 
1358                                Ty, Ty->getPointeeType(), Unit);
1359 }
1360
1361 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty, 
1362                                      llvm::DIFile Unit) {
1363   return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, 
1364                                Ty, Ty->getPointeeType(), Unit);
1365 }
1366
1367 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty, 
1368                                      llvm::DIFile U) {
1369   QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1370   llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1371   
1372   if (!Ty->getPointeeType()->isFunctionType()) {
1373     // We have a data member pointer type.
1374     return PointerDiffDITy;
1375   }
1376   
1377   // We have a member function pointer type. Treat it as a struct with two
1378   // ptrdiff_t members.
1379   std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1380
1381   uint64_t FieldOffset = 0;
1382   llvm::Value *ElementTypes[2];
1383   
1384   // FIXME: This should probably be a function type instead.
1385   ElementTypes[0] =
1386     DBuilder.createMemberType(U, "ptr", U, 0,
1387                               Info.first, Info.second, FieldOffset, 0,
1388                               PointerDiffDITy);
1389   FieldOffset += Info.first;
1390   
1391   ElementTypes[1] =
1392     DBuilder.createMemberType(U, "ptr", U, 0,
1393                               Info.first, Info.second, FieldOffset, 0,
1394                               PointerDiffDITy);
1395   
1396   llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes);
1397
1398   return DBuilder.createStructType(U, llvm::StringRef("test"), 
1399                                    U, 0, FieldOffset, 
1400                                    0, 0, Elements);
1401 }
1402
1403 /// CreateEnumType - get enumeration type.
1404 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1405   llvm::DIFile Unit = getOrCreateFile(ED->getLocation());
1406   llvm::SmallVector<llvm::Value *, 16> Enumerators;
1407
1408   // Create DIEnumerator elements for each enumerator.
1409   for (EnumDecl::enumerator_iterator
1410          Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1411        Enum != EnumEnd; ++Enum) {
1412     Enumerators.push_back(
1413       DBuilder.createEnumerator(Enum->getName(),
1414                                 Enum->getInitVal().getZExtValue()));
1415   }
1416
1417   // Return a CompositeType for the enum itself.
1418   llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1419
1420   llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1421   unsigned Line = getLineNumber(ED->getLocation());
1422   uint64_t Size = 0;
1423   uint64_t Align = 0;
1424   if (!ED->getTypeForDecl()->isIncompleteType()) {
1425     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1426     Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1427   }
1428   llvm::DIDescriptor EnumContext = 
1429     getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1430   llvm::DIType DbgTy = 
1431     DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1432                                    Size, Align, EltArray);
1433   return DbgTy;
1434 }
1435
1436 static QualType UnwrapTypeForDebugInfo(QualType T) {
1437   do {
1438     QualType LastT = T;
1439     switch (T->getTypeClass()) {
1440     default:
1441       return T;
1442     case Type::TemplateSpecialization:
1443       T = cast<TemplateSpecializationType>(T)->desugar();
1444       break;
1445     case Type::TypeOfExpr:
1446       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1447       break;
1448     case Type::TypeOf:
1449       T = cast<TypeOfType>(T)->getUnderlyingType();
1450       break;
1451     case Type::Decltype:
1452       T = cast<DecltypeType>(T)->getUnderlyingType();
1453       break;
1454     case Type::UnaryTransform:
1455       T = cast<UnaryTransformType>(T)->getUnderlyingType();
1456       break;
1457     case Type::Attributed:
1458       T = cast<AttributedType>(T)->getEquivalentType();
1459       break;
1460     case Type::Elaborated:
1461       T = cast<ElaboratedType>(T)->getNamedType();
1462       break;
1463     case Type::Paren:
1464       T = cast<ParenType>(T)->getInnerType();
1465       break;
1466     case Type::SubstTemplateTypeParm:
1467       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1468       break;
1469     case Type::Auto:
1470       T = cast<AutoType>(T)->getDeducedType();
1471       break;
1472     }
1473     
1474     assert(T != LastT && "Type unwrapping failed to unwrap!");
1475     if (T == LastT)
1476       return T;
1477   } while (true);
1478   
1479   return T;
1480 }
1481
1482 /// getOrCreateType - Get the type from the cache or create a new
1483 /// one if necessary.
1484 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1485                                           llvm::DIFile Unit) {
1486   if (Ty.isNull())
1487     return llvm::DIType();
1488
1489   // Unwrap the type as needed for debug information.
1490   Ty = UnwrapTypeForDebugInfo(Ty);
1491
1492   // Check for existing entry.
1493   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1494     TypeCache.find(Ty.getAsOpaquePtr());
1495   if (it != TypeCache.end()) {
1496     // Verify that the debug info still exists.
1497     if (&*it->second)
1498       return llvm::DIType(cast<llvm::MDNode>(it->second));
1499   }
1500
1501   // Otherwise create the type.
1502   llvm::DIType Res = CreateTypeNode(Ty, Unit);
1503
1504   // And update the type cache.
1505   TypeCache[Ty.getAsOpaquePtr()] = Res;  
1506   return Res;
1507 }
1508
1509 /// CreateTypeNode - Create a new debug type node.
1510 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1511                                          llvm::DIFile Unit) {
1512   // Handle qualifiers, which recursively handles what they refer to.
1513   if (Ty.hasLocalQualifiers())
1514     return CreateQualifiedType(Ty, Unit);
1515
1516   const char *Diag = 0;
1517   
1518   // Work out details of type.
1519   switch (Ty->getTypeClass()) {
1520 #define TYPE(Class, Base)
1521 #define ABSTRACT_TYPE(Class, Base)
1522 #define NON_CANONICAL_TYPE(Class, Base)
1523 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1524 #include "clang/AST/TypeNodes.def"
1525     assert(false && "Dependent types cannot show up in debug information");
1526
1527   case Type::ExtVector:
1528   case Type::Vector:
1529     return CreateType(cast<VectorType>(Ty), Unit);
1530   case Type::ObjCObjectPointer:
1531     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1532   case Type::ObjCObject:
1533     return CreateType(cast<ObjCObjectType>(Ty), Unit);
1534   case Type::ObjCInterface:
1535     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1536   case Type::Builtin: return CreateType(cast<BuiltinType>(Ty));
1537   case Type::Complex: return CreateType(cast<ComplexType>(Ty));
1538   case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1539   case Type::BlockPointer:
1540     return CreateType(cast<BlockPointerType>(Ty), Unit);
1541   case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1542   case Type::Record:
1543   case Type::Enum:
1544     return CreateType(cast<TagType>(Ty));
1545   case Type::FunctionProto:
1546   case Type::FunctionNoProto:
1547     return CreateType(cast<FunctionType>(Ty), Unit);
1548   case Type::ConstantArray:
1549   case Type::VariableArray:
1550   case Type::IncompleteArray:
1551     return CreateType(cast<ArrayType>(Ty), Unit);
1552
1553   case Type::LValueReference:
1554     return CreateType(cast<LValueReferenceType>(Ty), Unit);
1555   case Type::RValueReference:
1556     return CreateType(cast<RValueReferenceType>(Ty), Unit);
1557
1558   case Type::MemberPointer:
1559     return CreateType(cast<MemberPointerType>(Ty), Unit);
1560
1561   case Type::Attributed:
1562   case Type::TemplateSpecialization:
1563   case Type::Elaborated:
1564   case Type::Paren:
1565   case Type::SubstTemplateTypeParm:
1566   case Type::TypeOfExpr:
1567   case Type::TypeOf:
1568   case Type::Decltype:
1569   case Type::UnaryTransform:
1570   case Type::Auto:
1571     llvm_unreachable("type should have been unwrapped!");
1572     return llvm::DIType();      
1573   }
1574   
1575   assert(Diag && "Fall through without a diagnostic?");
1576   unsigned DiagID = CGM.getDiags().getCustomDiagID(Diagnostic::Error,
1577                                "debug information for %0 is not yet supported");
1578   CGM.getDiags().Report(DiagID)
1579     << Diag;
1580   return llvm::DIType();
1581 }
1582
1583 /// CreateMemberType - Create new member and increase Offset by FType's size.
1584 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1585                                            llvm::StringRef Name,
1586                                            uint64_t *Offset) {
1587   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1588   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1589   unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1590   llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
1591                                               FieldSize, FieldAlign,
1592                                               *Offset, 0, FieldTy);
1593   *Offset += FieldSize;
1594   return Ty;
1595 }
1596
1597 /// getFunctionDeclaration - Return debug info descriptor to describe method
1598 /// declaration for the given method definition.
1599 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
1600   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1601   if (!FD) return llvm::DISubprogram();
1602
1603   // Setup context.
1604   getContextDescriptor(cast<Decl>(D->getDeclContext()));
1605
1606   llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1607     MI = SPCache.find(FD);
1608   if (MI != SPCache.end()) {
1609     llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1610     if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1611       return SP;
1612   }
1613
1614   for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
1615          E = FD->redecls_end(); I != E; ++I) {
1616     const FunctionDecl *NextFD = *I;
1617     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1618       MI = SPCache.find(NextFD);
1619     if (MI != SPCache.end()) {
1620       llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1621       if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1622         return SP;
1623     }
1624   }
1625   return llvm::DISubprogram();
1626 }
1627
1628 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
1629 // implicit parameter "this".
1630 llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl * D, QualType FnType,
1631                                                   llvm::DIFile F) {
1632   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1633     return getOrCreateMethodType(Method, F);
1634   else if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
1635     // Add "self" and "_cmd"
1636     llvm::SmallVector<llvm::Value *, 16> Elts;
1637
1638     // First element is always return type. For 'void' functions it is NULL.
1639     Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
1640     // "self" pointer is always first argument.
1641     Elts.push_back(getOrCreateType(OMethod->getSelfDecl()->getType(), F));
1642     // "cmd" pointer is always second argument.
1643     Elts.push_back(getOrCreateType(OMethod->getCmdDecl()->getType(), F));
1644     // Get rest of the arguments.
1645     for (ObjCMethodDecl::param_iterator PI = OMethod->param_begin(), 
1646            PE = OMethod->param_end(); PI != PE; ++PI)
1647       Elts.push_back(getOrCreateType((*PI)->getType(), F));
1648
1649     llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1650     return DBuilder.createSubroutineType(F, EltTypeArray);
1651   }
1652   return getOrCreateType(FnType, F);
1653 }
1654
1655 /// EmitFunctionStart - Constructs the debug code for entering a function -
1656 /// "llvm.dbg.func.start.".
1657 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1658                                     llvm::Function *Fn,
1659                                     CGBuilderTy &Builder) {
1660
1661   llvm::StringRef Name;
1662   llvm::StringRef LinkageName;
1663
1664   FnBeginRegionCount.push_back(RegionStack.size());
1665
1666   const Decl *D = GD.getDecl();
1667
1668   unsigned Flags = 0;
1669   llvm::DIFile Unit = getOrCreateFile(CurLoc);
1670   llvm::DIDescriptor FDContext(Unit);
1671   llvm::DIArray TParamsArray;
1672   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1673     // If there is a DISubprogram for  this function available then use it.
1674     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1675       FI = SPCache.find(FD);
1676     if (FI != SPCache.end()) {
1677       llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second));
1678       if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1679         llvm::MDNode *SPN = SP;
1680         RegionStack.push_back(SPN);
1681         RegionMap[D] = llvm::WeakVH(SP);
1682         return;
1683       }
1684     }
1685     Name = getFunctionName(FD);
1686     // Use mangled name as linkage name for c/c++ functions.
1687     if (!Fn->hasInternalLinkage())
1688       LinkageName = CGM.getMangledName(GD);
1689     if (LinkageName == Name)
1690       LinkageName = llvm::StringRef();
1691     if (FD->hasPrototype())
1692       Flags |= llvm::DIDescriptor::FlagPrototyped;
1693     if (const NamespaceDecl *NSDecl =
1694         dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
1695       FDContext = getOrCreateNameSpace(NSDecl);
1696     else if (const RecordDecl *RDecl =
1697              dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
1698       FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
1699
1700     // Collect template parameters.
1701     TParamsArray = CollectFunctionTemplateParams(FD, Unit);
1702   } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
1703     Name = getObjCMethodName(OMD);
1704     Flags |= llvm::DIDescriptor::FlagPrototyped;
1705   } else {
1706     // Use llvm function name.
1707     Name = Fn->getName();
1708     Flags |= llvm::DIDescriptor::FlagPrototyped;
1709   }
1710   if (!Name.empty() && Name[0] == '\01')
1711     Name = Name.substr(1);
1712
1713   // It is expected that CurLoc is set before using EmitFunctionStart.
1714   // Usually, CurLoc points to the left bracket location of compound
1715   // statement representing function body.
1716   unsigned LineNo = getLineNumber(CurLoc);
1717   if (D->isImplicit())
1718     Flags |= llvm::DIDescriptor::FlagArtificial;
1719   llvm::DISubprogram SPDecl = getFunctionDeclaration(D);
1720   llvm::DISubprogram SP =
1721     DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
1722                             LineNo, getOrCreateFunctionType(D, FnType, Unit),
1723                             Fn->hasInternalLinkage(), true/*definition*/,
1724                             Flags, CGM.getLangOptions().Optimize, Fn,
1725                             TParamsArray, SPDecl);
1726
1727   // Push function on region stack.
1728   llvm::MDNode *SPN = SP;
1729   RegionStack.push_back(SPN);
1730   RegionMap[D] = llvm::WeakVH(SP);
1731
1732   // Clear stack used to keep track of #line directives.
1733   LineDirectiveFiles.clear();
1734 }
1735
1736
1737 void CGDebugInfo::EmitStopPoint(CGBuilderTy &Builder) {
1738   if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1739
1740   // Don't bother if things are the same as last time.
1741   SourceManager &SM = CGM.getContext().getSourceManager();
1742   if (CurLoc == PrevLoc
1743        || (SM.getInstantiationLineNumber(CurLoc) ==
1744            SM.getInstantiationLineNumber(PrevLoc)
1745            && SM.isFromSameFile(CurLoc, PrevLoc)))
1746     // New Builder may not be in sync with CGDebugInfo.
1747     if (!Builder.getCurrentDebugLocation().isUnknown())
1748       return;
1749
1750   // Update last state.
1751   PrevLoc = CurLoc;
1752
1753   llvm::MDNode *Scope = RegionStack.back();
1754   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
1755                                                       getColumnNumber(CurLoc),
1756                                                       Scope));
1757 }
1758
1759 /// UpdateLineDirectiveRegion - Update region stack only if #line directive
1760 /// has introduced scope change.
1761 void CGDebugInfo::UpdateLineDirectiveRegion(CGBuilderTy &Builder) {
1762   if (CurLoc.isInvalid() || CurLoc.isMacroID() ||
1763       PrevLoc.isInvalid() || PrevLoc.isMacroID())
1764     return;
1765   SourceManager &SM = CGM.getContext().getSourceManager();
1766   PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
1767   PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
1768
1769   if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
1770       !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
1771     return;
1772
1773   // If #line directive stack is empty then we are entering a new scope.
1774   if (LineDirectiveFiles.empty()) {
1775     EmitRegionStart(Builder);
1776     LineDirectiveFiles.push_back(PCLoc.getFilename());
1777     return;
1778   }
1779
1780   assert (RegionStack.size() >= LineDirectiveFiles.size()
1781           && "error handling  #line regions!");
1782
1783   bool SeenThisFile = false;
1784   // Chek if current file is already seen earlier.
1785   for(std::vector<const char *>::iterator I = LineDirectiveFiles.begin(),
1786         E = LineDirectiveFiles.end(); I != E; ++I)
1787     if (!strcmp(PCLoc.getFilename(), *I)) {
1788       SeenThisFile = true;
1789       break;
1790     }
1791
1792   // If #line for this file is seen earlier then pop out #line regions.
1793   if (SeenThisFile) {
1794     while (!LineDirectiveFiles.empty()) {
1795       const char *LastFile = LineDirectiveFiles.back();
1796       RegionStack.pop_back();
1797       LineDirectiveFiles.pop_back();
1798       if (!strcmp(PPLoc.getFilename(), LastFile))
1799         break;
1800     }
1801     return;
1802   } 
1803
1804   // .. otherwise insert new #line region.
1805   EmitRegionStart(Builder);
1806   LineDirectiveFiles.push_back(PCLoc.getFilename());
1807
1808   return;
1809 }
1810 /// EmitRegionStart- Constructs the debug code for entering a declarative
1811 /// region - "llvm.dbg.region.start.".
1812 void CGDebugInfo::EmitRegionStart(CGBuilderTy &Builder) {
1813   llvm::DIDescriptor D =
1814     DBuilder.createLexicalBlock(RegionStack.empty() ? 
1815                                 llvm::DIDescriptor() : 
1816                                 llvm::DIDescriptor(RegionStack.back()),
1817                                 getOrCreateFile(CurLoc),
1818                                 getLineNumber(CurLoc), 
1819                                 getColumnNumber(CurLoc));
1820   llvm::MDNode *DN = D;
1821   RegionStack.push_back(DN);
1822 }
1823
1824 /// EmitRegionEnd - Constructs the debug code for exiting a declarative
1825 /// region - "llvm.dbg.region.end."
1826 void CGDebugInfo::EmitRegionEnd(CGBuilderTy &Builder) {
1827   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1828
1829   // Provide an region stop point.
1830   EmitStopPoint(Builder);
1831
1832   RegionStack.pop_back();
1833 }
1834
1835 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
1836 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
1837   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1838   unsigned RCount = FnBeginRegionCount.back();
1839   assert(RCount <= RegionStack.size() && "Region stack mismatch");
1840
1841   // Pop all regions for this function.
1842   while (RegionStack.size() != RCount)
1843     EmitRegionEnd(Builder);
1844   FnBeginRegionCount.pop_back();
1845 }
1846
1847 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.  
1848 // See BuildByRefType.
1849 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1850                                                        uint64_t *XOffset) {
1851
1852   llvm::SmallVector<llvm::Value *, 5> EltTys;
1853   QualType FType;
1854   uint64_t FieldSize, FieldOffset;
1855   unsigned FieldAlign;
1856   
1857   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1858   QualType Type = VD->getType();  
1859
1860   FieldOffset = 0;
1861   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1862   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1863   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
1864   FType = CGM.getContext().IntTy;
1865   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1866   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1867
1868   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type);
1869   if (HasCopyAndDispose) {
1870     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1871     EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
1872                                       &FieldOffset));
1873     EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
1874                                       &FieldOffset));
1875   }
1876   
1877   CharUnits Align = CGM.getContext().getDeclAlign(VD);
1878   if (Align > CGM.getContext().toCharUnitsFromBits(
1879         CGM.getContext().Target.getPointerAlign(0))) {
1880     CharUnits FieldOffsetInBytes 
1881       = CGM.getContext().toCharUnitsFromBits(FieldOffset);
1882     CharUnits AlignedOffsetInBytes
1883       = FieldOffsetInBytes.RoundUpToAlignment(Align);
1884     CharUnits NumPaddingBytes
1885       = AlignedOffsetInBytes - FieldOffsetInBytes;
1886     
1887     if (NumPaddingBytes.isPositive()) {
1888       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
1889       FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1890                                                     pad, ArrayType::Normal, 0);
1891       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
1892     }
1893   }
1894   
1895   FType = Type;
1896   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1897   FieldSize = CGM.getContext().getTypeSize(FType);
1898   FieldAlign = CGM.getContext().toBits(Align);
1899
1900   *XOffset = FieldOffset;  
1901   FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
1902                                       0, FieldSize, FieldAlign,
1903                                       FieldOffset, 0, FieldTy);
1904   EltTys.push_back(FieldTy);
1905   FieldOffset += FieldSize;
1906   
1907   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1908   
1909   unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
1910   
1911   return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
1912                                    Elements);
1913 }
1914
1915 /// EmitDeclare - Emit local variable declaration debug info.
1916 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1917                               llvm::Value *Storage, 
1918                               unsigned ArgNo, CGBuilderTy &Builder) {
1919   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
1920
1921   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1922   llvm::DIType Ty;
1923   uint64_t XOffset = 0;
1924   if (VD->hasAttr<BlocksAttr>())
1925     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1926   else 
1927     Ty = getOrCreateType(VD->getType(), Unit);
1928
1929   // If there is not any debug info for type then do not emit debug info
1930   // for this variable.
1931   if (!Ty)
1932     return;
1933
1934   if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
1935     // If Storage is an aggregate returned as 'sret' then let debugger know
1936     // about this.
1937     if (Arg->hasStructRetAttr())
1938       Ty = DBuilder.createReferenceType(Ty);
1939     else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
1940       // If an aggregate variable has non trivial destructor or non trivial copy
1941       // constructor than it is pass indirectly. Let debug info know about this
1942       // by using reference of the aggregate type as a argument type.
1943       if (!Record->hasTrivialCopyConstructor() || !Record->hasTrivialDestructor())
1944         Ty = DBuilder.createReferenceType(Ty);
1945     }
1946   }
1947       
1948   // Get location information.
1949   unsigned Line = getLineNumber(VD->getLocation());
1950   unsigned Column = getColumnNumber(VD->getLocation());
1951   unsigned Flags = 0;
1952   if (VD->isImplicit())
1953     Flags |= llvm::DIDescriptor::FlagArtificial;
1954   llvm::MDNode *Scope = RegionStack.back();
1955     
1956   llvm::StringRef Name = VD->getName();
1957   if (!Name.empty()) {
1958     if (VD->hasAttr<BlocksAttr>()) {
1959       CharUnits offset = CharUnits::fromQuantity(32);
1960       llvm::SmallVector<llvm::Value *, 9> addr;
1961       const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
1962       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
1963       // offset of __forwarding field
1964       offset = CGM.getContext().toCharUnitsFromBits(
1965         CGM.getContext().Target.getPointerWidth(0));
1966       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1967       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
1968       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
1969       // offset of x field
1970       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
1971       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
1972
1973       // Create the descriptor for the variable.
1974       llvm::DIVariable D =
1975         DBuilder.createComplexVariable(Tag, 
1976                                        llvm::DIDescriptor(RegionStack.back()),
1977                                        VD->getName(), Unit, Line, Ty,
1978                                        addr, ArgNo);
1979       
1980       // Insert an llvm.dbg.declare into the current block.
1981       llvm::Instruction *Call =
1982         DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
1983       
1984       Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1985       return;
1986     } 
1987       // Create the descriptor for the variable.
1988     llvm::DIVariable D =
1989       DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope), 
1990                                    Name, Unit, Line, Ty, 
1991                                    CGM.getLangOptions().Optimize, Flags, ArgNo);
1992     
1993     // Insert an llvm.dbg.declare into the current block.
1994     llvm::Instruction *Call =
1995       DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
1996     
1997     Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
1998     return;
1999   }
2000   
2001   // If VD is an anonymous union then Storage represents value for
2002   // all union fields.
2003   if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2004     const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2005     if (RD->isUnion()) {
2006       for (RecordDecl::field_iterator I = RD->field_begin(),
2007              E = RD->field_end();
2008            I != E; ++I) {
2009         FieldDecl *Field = *I;
2010         llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2011         llvm::StringRef FieldName = Field->getName();
2012           
2013         // Ignore unnamed fields. Do not ignore unnamed records.
2014         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2015           continue;
2016           
2017         // Use VarDecl's Tag, Scope and Line number.
2018         llvm::DIVariable D =
2019           DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2020                                        FieldName, Unit, Line, FieldTy, 
2021                                        CGM.getLangOptions().Optimize, Flags,
2022                                        ArgNo);
2023           
2024         // Insert an llvm.dbg.declare into the current block.
2025         llvm::Instruction *Call =
2026           DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2027           
2028         Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2029       }
2030     }
2031   }
2032 }
2033
2034 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2035                                             llvm::Value *Storage,
2036                                             CGBuilderTy &Builder) {
2037   EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2038 }
2039
2040 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2041   const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2042   const CGBlockInfo &blockInfo) {
2043   assert(!RegionStack.empty() && "Region stack mismatch, stack empty!");
2044   
2045   if (Builder.GetInsertBlock() == 0)
2046     return;
2047   
2048   bool isByRef = VD->hasAttr<BlocksAttr>();
2049   
2050   uint64_t XOffset = 0;
2051   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2052   llvm::DIType Ty;
2053   if (isByRef)
2054     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2055   else 
2056     Ty = getOrCreateType(VD->getType(), Unit);
2057
2058   // Get location information.
2059   unsigned Line = getLineNumber(VD->getLocation());
2060   unsigned Column = getColumnNumber(VD->getLocation());
2061
2062   const llvm::TargetData &target = CGM.getTargetData();
2063
2064   CharUnits offset = CharUnits::fromQuantity(
2065     target.getStructLayout(blockInfo.StructureType)
2066           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2067
2068   llvm::SmallVector<llvm::Value *, 9> addr;
2069   const llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
2070   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2071   addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2072   if (isByRef) {
2073     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2074     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2075     // offset of __forwarding field
2076     offset = CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits());
2077     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2078     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2079     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2080     // offset of x field
2081     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2082     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2083   }
2084
2085   // Create the descriptor for the variable.
2086   llvm::DIVariable D =
2087     DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable, 
2088                                    llvm::DIDescriptor(RegionStack.back()),
2089                                    VD->getName(), Unit, Line, Ty, addr);
2090   // Insert an llvm.dbg.declare into the current block.
2091   llvm::Instruction *Call = 
2092     DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2093   
2094   llvm::MDNode *Scope = RegionStack.back();
2095   Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2096 }
2097
2098 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2099 /// variable declaration.
2100 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2101                                            unsigned ArgNo,
2102                                            CGBuilderTy &Builder) {
2103   EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2104 }
2105
2106 namespace {
2107   struct BlockLayoutChunk {
2108     uint64_t OffsetInBits;
2109     const BlockDecl::Capture *Capture;
2110   };
2111   bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2112     return l.OffsetInBits < r.OffsetInBits;
2113   }
2114 }
2115
2116 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2117                                                        llvm::Value *addr,
2118                                                        CGBuilderTy &Builder) {
2119   ASTContext &C = CGM.getContext();
2120   const BlockDecl *blockDecl = block.getBlockDecl();
2121
2122   // Collect some general information about the block's location.
2123   SourceLocation loc = blockDecl->getCaretLocation();
2124   llvm::DIFile tunit = getOrCreateFile(loc);
2125   unsigned line = getLineNumber(loc);
2126   unsigned column = getColumnNumber(loc);
2127   
2128   // Build the debug-info type for the block literal.
2129   getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2130
2131   const llvm::StructLayout *blockLayout =
2132     CGM.getTargetData().getStructLayout(block.StructureType);
2133
2134   llvm::SmallVector<llvm::Value*, 16> fields;
2135   fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2136                                    blockLayout->getElementOffsetInBits(0),
2137                                    tunit, tunit));
2138   fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2139                                    blockLayout->getElementOffsetInBits(1),
2140                                    tunit, tunit));
2141   fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2142                                    blockLayout->getElementOffsetInBits(2),
2143                                    tunit, tunit));
2144   fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2145                                    blockLayout->getElementOffsetInBits(3),
2146                                    tunit, tunit));
2147   fields.push_back(createFieldType("__descriptor",
2148                                    C.getPointerType(block.NeedsCopyDispose ?
2149                                         C.getBlockDescriptorExtendedType() :
2150                                         C.getBlockDescriptorType()),
2151                                    0, loc, AS_public,
2152                                    blockLayout->getElementOffsetInBits(4),
2153                                    tunit, tunit));
2154
2155   // We want to sort the captures by offset, not because DWARF
2156   // requires this, but because we're paranoid about debuggers.
2157   llvm::SmallVector<BlockLayoutChunk, 8> chunks;
2158
2159   // 'this' capture.
2160   if (blockDecl->capturesCXXThis()) {
2161     BlockLayoutChunk chunk;
2162     chunk.OffsetInBits =
2163       blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2164     chunk.Capture = 0;
2165     chunks.push_back(chunk);
2166   }
2167
2168   // Variable captures.
2169   for (BlockDecl::capture_const_iterator
2170          i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2171        i != e; ++i) {
2172     const BlockDecl::Capture &capture = *i;
2173     const VarDecl *variable = capture.getVariable();
2174     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2175
2176     // Ignore constant captures.
2177     if (captureInfo.isConstant())
2178       continue;
2179
2180     BlockLayoutChunk chunk;
2181     chunk.OffsetInBits =
2182       blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2183     chunk.Capture = &capture;
2184     chunks.push_back(chunk);
2185   }
2186
2187   // Sort by offset.
2188   llvm::array_pod_sort(chunks.begin(), chunks.end());
2189
2190   for (llvm::SmallVectorImpl<BlockLayoutChunk>::iterator
2191          i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2192     uint64_t offsetInBits = i->OffsetInBits;
2193     const BlockDecl::Capture *capture = i->Capture;
2194
2195     // If we have a null capture, this must be the C++ 'this' capture.
2196     if (!capture) {
2197       const CXXMethodDecl *method =
2198         cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2199       QualType type = method->getThisType(C);
2200
2201       fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2202                                        offsetInBits, tunit, tunit));
2203       continue;
2204     }
2205
2206     const VarDecl *variable = capture->getVariable();
2207     llvm::StringRef name = variable->getName();
2208
2209     llvm::DIType fieldType;
2210     if (capture->isByRef()) {
2211       std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2212
2213       // FIXME: this creates a second copy of this type!
2214       uint64_t xoffset;
2215       fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2216       fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2217       fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2218                                             ptrInfo.first, ptrInfo.second,
2219                                             offsetInBits, 0, fieldType);
2220     } else {
2221       fieldType = createFieldType(name, variable->getType(), 0,
2222                                   loc, AS_public, offsetInBits, tunit, tunit);
2223     }
2224     fields.push_back(fieldType);
2225   }
2226
2227   llvm::SmallString<36> typeName;
2228   llvm::raw_svector_ostream(typeName)
2229     << "__block_literal_" << CGM.getUniqueBlockCount();
2230
2231   llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2232
2233   llvm::DIType type =
2234     DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2235                               CGM.getContext().toBits(block.BlockSize),
2236                               CGM.getContext().toBits(block.BlockAlign),
2237                               0, fieldsArray);
2238   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2239
2240   // Get overall information about the block.
2241   unsigned flags = llvm::DIDescriptor::FlagArtificial;
2242   llvm::MDNode *scope = RegionStack.back();
2243   llvm::StringRef name = ".block_descriptor";
2244
2245   // Create the descriptor for the parameter.
2246   llvm::DIVariable debugVar =
2247     DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2248                                  llvm::DIDescriptor(scope), 
2249                                  name, tunit, line, type, 
2250                                  CGM.getLangOptions().Optimize, flags,
2251                                  cast<llvm::Argument>(addr)->getArgNo() + 1);
2252     
2253   // Insert an llvm.dbg.value into the current block.
2254   llvm::Instruction *declare =
2255     DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2256                                      Builder.GetInsertBlock());
2257   declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2258 }
2259
2260 /// EmitGlobalVariable - Emit information about a global variable.
2261 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2262                                      const VarDecl *D) {
2263   
2264   // Create global variable debug descriptor.
2265   llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2266   unsigned LineNo = getLineNumber(D->getLocation());
2267
2268   QualType T = D->getType();
2269   if (T->isIncompleteArrayType()) {
2270
2271     // CodeGen turns int[] into int[1] so we'll do the same here.
2272     llvm::APSInt ConstVal(32);
2273
2274     ConstVal = 1;
2275     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2276
2277     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2278                                            ArrayType::Normal, 0);
2279   }
2280   llvm::StringRef DeclName = D->getName();
2281   llvm::StringRef LinkageName;
2282   if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2283       && !isa<ObjCMethodDecl>(D->getDeclContext()))
2284     LinkageName = Var->getName();
2285   if (LinkageName == DeclName)
2286     LinkageName = llvm::StringRef();
2287   llvm::DIDescriptor DContext = 
2288     getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2289   DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2290                                 Unit, LineNo, getOrCreateType(T, Unit),
2291                                 Var->hasInternalLinkage(), Var);
2292 }
2293
2294 /// EmitGlobalVariable - Emit information about an objective-c interface.
2295 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2296                                      ObjCInterfaceDecl *ID) {
2297   // Create global variable debug descriptor.
2298   llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2299   unsigned LineNo = getLineNumber(ID->getLocation());
2300
2301   llvm::StringRef Name = ID->getName();
2302
2303   QualType T = CGM.getContext().getObjCInterfaceType(ID);
2304   if (T->isIncompleteArrayType()) {
2305
2306     // CodeGen turns int[] into int[1] so we'll do the same here.
2307     llvm::APSInt ConstVal(32);
2308
2309     ConstVal = 1;
2310     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2311
2312     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2313                                            ArrayType::Normal, 0);
2314   }
2315
2316   DBuilder.createGlobalVariable(Name, Unit, LineNo,
2317                                 getOrCreateType(T, Unit),
2318                                 Var->hasInternalLinkage(), Var);
2319 }
2320
2321 /// EmitGlobalVariable - Emit global variable's debug info.
2322 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, 
2323                                      llvm::Constant *Init) {
2324   // Create the descriptor for the variable.
2325   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2326   llvm::StringRef Name = VD->getName();
2327   llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2328   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2329     if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext()))
2330       Ty = CreateEnumType(ED);
2331   }
2332   // Do not use DIGlobalVariable for enums.
2333   if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2334     return;
2335   DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2336                                 getLineNumber(VD->getLocation()),
2337                                 Ty, true, Init);
2338 }
2339
2340 /// getOrCreateNamesSpace - Return namespace descriptor for the given
2341 /// namespace decl.
2342 llvm::DINameSpace 
2343 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2344   llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I = 
2345     NameSpaceCache.find(NSDecl);
2346   if (I != NameSpaceCache.end())
2347     return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2348   
2349   unsigned LineNo = getLineNumber(NSDecl->getLocation());
2350   llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2351   llvm::DIDescriptor Context = 
2352     getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2353   llvm::DINameSpace NS =
2354     DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2355   NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2356   return NS;
2357 }
2358
2359 /// UpdateCompletedType - Update type cache because the type is now
2360 /// translated.
2361 void CGDebugInfo::UpdateCompletedType(const TagDecl *TD) {
2362   QualType Ty = CGM.getContext().getTagDeclType(TD);
2363
2364   // If the type exist in type cache then remove it from the cache.
2365   // There is no need to prepare debug info for the completed type
2366   // right now. It will be generated on demand lazily.
2367   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2368     TypeCache.find(Ty.getAsOpaquePtr());
2369   if (it != TypeCache.end()) 
2370     TypeCache.erase(it);
2371 }