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