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