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