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