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