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