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