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.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
340                                       "objc_class", getOrCreateMainFile(),
341                                       0);
342   case BuiltinType::ObjCId: {
343     // typedef struct objc_class *Class;
344     // typedef struct objc_object {
345     //  Class isa;
346     // } *id;
347 
348     llvm::DIType OCTy =
349       DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
350                                  "objc_class", getOrCreateMainFile(),
351                                  0);
352     unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
353 
354     llvm::DIType ISATy = DBuilder.createPointerType(OCTy, Size);
355 
356     SmallVector<llvm::Value *, 16> EltTys;
357     llvm::DIType FieldTy =
358       DBuilder.createMemberType(getOrCreateMainFile(), "isa",
359                                 getOrCreateMainFile(), 0, Size,
360                                 0, 0, 0, ISATy);
361     EltTys.push_back(FieldTy);
362     llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
363 
364     return DBuilder.createStructType(TheCU, "objc_object",
365                                      getOrCreateMainFile(),
366                                      0, 0, 0, 0, Elements);
367   }
368   case BuiltinType::ObjCSel: {
369     return
370       DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
371                                  "objc_selector", getOrCreateMainFile(),
372                                  0);
373   }
374   case BuiltinType::UChar:
375   case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
376   case BuiltinType::Char_S:
377   case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
378   case BuiltinType::Char16:
379   case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
380   case BuiltinType::UShort:
381   case BuiltinType::UInt:
382   case BuiltinType::UInt128:
383   case BuiltinType::ULong:
384   case BuiltinType::WChar_U:
385   case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
386   case BuiltinType::Short:
387   case BuiltinType::Int:
388   case BuiltinType::Int128:
389   case BuiltinType::Long:
390   case BuiltinType::WChar_S:
391   case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
392   case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
393   case BuiltinType::Half:
394   case BuiltinType::Float:
395   case BuiltinType::LongDouble:
396   case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
397   }
398 
399   switch (BT->getKind()) {
400   case BuiltinType::Long:      BTName = "long int"; break;
401   case BuiltinType::LongLong:  BTName = "long long int"; break;
402   case BuiltinType::ULong:     BTName = "long unsigned int"; break;
403   case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
404   default:
405     BTName = BT->getName(CGM.getContext().getLangOptions());
406     break;
407   }
408   // Bit size, align and offset of the type.
409   uint64_t Size = CGM.getContext().getTypeSize(BT);
410   uint64_t Align = CGM.getContext().getTypeAlign(BT);
411   llvm::DIType DbgTy =
412     DBuilder.createBasicType(BTName, Size, Align, Encoding);
413   return DbgTy;
414 }
415 
416 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
417   // Bit size, align and offset of the type.
418   unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
419   if (Ty->isComplexIntegerType())
420     Encoding = llvm::dwarf::DW_ATE_lo_user;
421 
422   uint64_t Size = CGM.getContext().getTypeSize(Ty);
423   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
424   llvm::DIType DbgTy =
425     DBuilder.createBasicType("complex", Size, Align, Encoding);
426 
427   return DbgTy;
428 }
429 
430 /// CreateCVRType - Get the qualified type from the cache or create
431 /// a new one if necessary.
432 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
433   QualifierCollector Qc;
434   const Type *T = Qc.strip(Ty);
435 
436   // Ignore these qualifiers for now.
437   Qc.removeObjCGCAttr();
438   Qc.removeAddressSpace();
439   Qc.removeObjCLifetime();
440 
441   // We will create one Derived type for one qualifier and recurse to handle any
442   // additional ones.
443   unsigned Tag;
444   if (Qc.hasConst()) {
445     Tag = llvm::dwarf::DW_TAG_const_type;
446     Qc.removeConst();
447   } else if (Qc.hasVolatile()) {
448     Tag = llvm::dwarf::DW_TAG_volatile_type;
449     Qc.removeVolatile();
450   } else if (Qc.hasRestrict()) {
451     Tag = llvm::dwarf::DW_TAG_restrict_type;
452     Qc.removeRestrict();
453   } else {
454     assert(Qc.empty() && "Unknown type qualifier for debug info");
455     return getOrCreateType(QualType(T, 0), Unit);
456   }
457 
458   llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
459 
460   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
461   // CVR derived types.
462   llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
463 
464   return DbgTy;
465 }
466 
467 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
468                                      llvm::DIFile Unit) {
469   llvm::DIType DbgTy =
470     CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
471                           Ty->getPointeeType(), Unit);
472   return DbgTy;
473 }
474 
475 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
476                                      llvm::DIFile Unit) {
477   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
478                                Ty->getPointeeType(), Unit);
479 }
480 
481 // Creates a forward declaration for a RecordDecl in the given context.
482 llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
483                                               llvm::DIDescriptor Ctx) {
484   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
485   unsigned Line = getLineNumber(RD->getLocation());
486   StringRef RDName = RD->getName();
487 
488   // Get the tag.
489   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
490   unsigned Tag = 0;
491   if (CXXDecl) {
492     RDName = getClassName(RD);
493     Tag = llvm::dwarf::DW_TAG_class_type;
494   }
495   else if (RD->isStruct())
496     Tag = llvm::dwarf::DW_TAG_structure_type;
497   else if (RD->isUnion())
498     Tag = llvm::dwarf::DW_TAG_union_type;
499   else
500     llvm_unreachable("Unknown RecordDecl type!");
501 
502   // Create the type.
503   return DBuilder.createForwardDecl(Tag, RDName, DefUnit, Line);
504 }
505 
506 // Walk up the context chain and create forward decls for record decls,
507 // and normal descriptors for namespaces.
508 llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
509   if (!Context)
510     return TheCU;
511 
512   // See if we already have the parent.
513   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
514     I = RegionMap.find(Context);
515   if (I != RegionMap.end())
516     return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second));
517 
518   // Check namespace.
519   if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
520     return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
521 
522   if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
523     if (!RD->isDependentType()) {
524       llvm::DIType Ty = getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
525 					       getOrCreateMainFile());
526       return llvm::DIDescriptor(Ty);
527     }
528   }
529   return TheCU;
530 }
531 
532 /// CreatePointeeType - Create Pointee type. If Pointee is a record
533 /// then emit record's fwd if debug info size reduction is enabled.
534 llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
535                                             llvm::DIFile Unit) {
536   if (!CGM.getCodeGenOpts().LimitDebugInfo)
537     return getOrCreateType(PointeeTy, Unit);
538 
539   // Limit debug info for the pointee type.
540 
541   // If we have an existing type, use that, it's still smaller than creating
542   // a new type.
543   llvm::DIType Ty = getTypeOrNull(PointeeTy);
544   if (Ty.Verify()) return Ty;
545 
546   // Handle qualifiers.
547   if (PointeeTy.hasLocalQualifiers())
548     return CreateQualifiedType(PointeeTy, Unit);
549 
550   if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
551     RecordDecl *RD = RTy->getDecl();
552     llvm::DIDescriptor FDContext =
553       getContextDescriptor(cast<Decl>(RD->getDeclContext()));
554     llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
555     TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy;
556     return RetTy;
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   return T;
1124 }
1125 
1126 /// CreateType - get structure or union type.
1127 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1128   RecordDecl *RD = Ty->getDecl();
1129 
1130   // Get overall information about the record type for the debug info.
1131   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1132 
1133   // Records and classes and unions can all be recursive.  To handle them, we
1134   // first generate a debug descriptor for the struct as a forward declaration.
1135   // Then (if it is a definition) we go through and get debug info for all of
1136   // its members.  Finally, we create a descriptor for the complete type (which
1137   // may refer to the forward decl if the struct is recursive) and replace all
1138   // uses of the forward declaration with the final definition.
1139 
1140   llvm::DIType FwdDecl = getOrCreateLimitedType(QualType(Ty, 0), DefUnit);
1141 
1142   if (FwdDecl.isForwardDecl())
1143     return FwdDecl;
1144 
1145   llvm::MDNode *MN = FwdDecl;
1146   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1147 
1148   // Push the struct on region stack.
1149   LexicalBlockStack.push_back(FwdDeclNode);
1150   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1151 
1152   // Add this to the completed types cache since we're completing it.
1153   CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1154 
1155   // Convert all the elements.
1156   SmallVector<llvm::Value *, 16> EltTys;
1157 
1158   // Note: The split of CXXDecl information here is intentional, the
1159   // gdb tests will depend on a certain ordering at printout. The debug
1160   // information offsets are still correct if we merge them all together
1161   // though.
1162   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1163   if (CXXDecl) {
1164     CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1165     CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1166   }
1167 
1168   // Collect static variables with initializers and other fields.
1169   CollectRecordStaticVars(RD, FwdDecl);
1170   CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1171   llvm::DIArray TParamsArray;
1172   if (CXXDecl) {
1173     CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1174     CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1175     if (const ClassTemplateSpecializationDecl *TSpecial
1176         = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1177       TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1178   }
1179 
1180   LexicalBlockStack.pop_back();
1181   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
1182     RegionMap.find(Ty->getDecl());
1183   if (RI != RegionMap.end())
1184     RegionMap.erase(RI);
1185 
1186   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1187   // FIXME: Magic numbers ahoy! These should be changed when we
1188   // get some enums in llvm/Analysis/DebugInfo.h to refer to
1189   // them.
1190   if (RD->isUnion())
1191     MN->replaceOperandWith(10, Elements);
1192   else if (CXXDecl) {
1193     MN->replaceOperandWith(10, Elements);
1194     MN->replaceOperandWith(13, TParamsArray);
1195   } else
1196     MN->replaceOperandWith(10, Elements);
1197 
1198   RegionMap[Ty->getDecl()] = llvm::WeakVH(MN);
1199   return llvm::DIType(MN);
1200 }
1201 
1202 /// CreateType - get objective-c object type.
1203 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1204                                      llvm::DIFile Unit) {
1205   // Ignore protocols.
1206   return getOrCreateType(Ty->getBaseType(), Unit);
1207 }
1208 
1209 /// CreateType - get objective-c interface type.
1210 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1211                                      llvm::DIFile Unit) {
1212   ObjCInterfaceDecl *ID = Ty->getDecl();
1213   if (!ID)
1214     return llvm::DIType();
1215 
1216   // Get overall information about the record type for the debug info.
1217   llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1218   unsigned Line = getLineNumber(ID->getLocation());
1219   unsigned RuntimeLang = TheCU.getLanguage();
1220 
1221   // If this is just a forward declaration return a special forward-declaration
1222   // debug type since we won't be able to lay out the entire type.
1223   ObjCInterfaceDecl *Def = ID->getDefinition();
1224   if (!Def) {
1225     llvm::DIType FwdDecl =
1226       DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1227 				 ID->getName(), DefUnit, Line,
1228 				 RuntimeLang);
1229     return FwdDecl;
1230   }
1231   ID = Def;
1232 
1233   // Bit size, align and offset of the type.
1234   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1235   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1236 
1237   unsigned Flags = 0;
1238   if (ID->getImplementation())
1239     Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1240 
1241   llvm::DIType RealDecl =
1242     DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1243                               Line, Size, Align, Flags,
1244                               llvm::DIArray(), RuntimeLang);
1245 
1246   // Otherwise, insert it into the TypeCache so that recursive uses will find
1247   // it.
1248   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
1249   // Push the struct on region stack.
1250   llvm::MDNode *MN = RealDecl;
1251   llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1252 
1253   LexicalBlockStack.push_back(FwdDeclNode);
1254   RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1255 
1256   // Convert all the elements.
1257   SmallVector<llvm::Value *, 16> EltTys;
1258 
1259   ObjCInterfaceDecl *SClass = ID->getSuperClass();
1260   if (SClass) {
1261     llvm::DIType SClassTy =
1262       getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1263     if (!SClassTy.isValid())
1264       return llvm::DIType();
1265 
1266     llvm::DIType InhTag =
1267       DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1268     EltTys.push_back(InhTag);
1269   }
1270 
1271   for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1272          E = ID->prop_end(); I != E; ++I) {
1273     const ObjCPropertyDecl *PD = *I;
1274     llvm::MDNode *PropertyNode =
1275       DBuilder.createObjCProperty(PD->getName(),
1276                                   getSelectorName(PD->getGetterName()),
1277                                   getSelectorName(PD->getSetterName()),
1278                                   PD->getPropertyAttributes());
1279     EltTys.push_back(PropertyNode);
1280   }
1281 
1282   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1283   unsigned FieldNo = 0;
1284   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1285        Field = Field->getNextIvar(), ++FieldNo) {
1286     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1287     if (!FieldTy.isValid())
1288       return llvm::DIType();
1289 
1290     StringRef FieldName = Field->getName();
1291 
1292     // Ignore unnamed fields.
1293     if (FieldName.empty())
1294       continue;
1295 
1296     // Get the location for the field.
1297     llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1298     unsigned FieldLine = getLineNumber(Field->getLocation());
1299     QualType FType = Field->getType();
1300     uint64_t FieldSize = 0;
1301     unsigned FieldAlign = 0;
1302 
1303     if (!FType->isIncompleteArrayType()) {
1304 
1305       // Bit size, align and offset of the type.
1306       FieldSize = Field->isBitField()
1307         ? Field->getBitWidthValue(CGM.getContext())
1308         : CGM.getContext().getTypeSize(FType);
1309       FieldAlign = CGM.getContext().getTypeAlign(FType);
1310     }
1311 
1312     // We can't know the offset of our ivar in the structure if we're using
1313     // the non-fragile abi and the debugger should ignore the value anyways.
1314     // Call it the FieldNo+1 due to how debuggers use the information,
1315     // e.g. negating the value when it needs a lookup in the dynamic table.
1316     uint64_t FieldOffset = CGM.getLangOptions().ObjCNonFragileABI ? FieldNo+1
1317       : RL.getFieldOffset(FieldNo);
1318 
1319     unsigned Flags = 0;
1320     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1321       Flags = llvm::DIDescriptor::FlagProtected;
1322     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1323       Flags = llvm::DIDescriptor::FlagPrivate;
1324 
1325     llvm::MDNode *PropertyNode = NULL;
1326     if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1327       if (ObjCPropertyImplDecl *PImpD =
1328           ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1329         if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1330           PropertyNode =
1331             DBuilder.createObjCProperty(PD->getName(),
1332                                         getSelectorName(PD->getGetterName()),
1333                                         getSelectorName(PD->getSetterName()),
1334                                         PD->getPropertyAttributes());
1335         }
1336       }
1337     }
1338     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1339                                       FieldLine, FieldSize, FieldAlign,
1340                                       FieldOffset, Flags, FieldTy,
1341                                       PropertyNode);
1342     EltTys.push_back(FieldTy);
1343   }
1344 
1345   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1346   RealDecl->replaceOperandWith(10, Elements);
1347 
1348   LexicalBlockStack.pop_back();
1349   return RealDecl;
1350 }
1351 
1352 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1353   llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1354   int64_t NumElems = Ty->getNumElements();
1355   int64_t LowerBound = 0;
1356   if (NumElems == 0)
1357     // If number of elements are not known then this is an unbounded array.
1358     // Use Low = 1, Hi = 0 to express such arrays.
1359     LowerBound = 1;
1360   else
1361     --NumElems;
1362 
1363   llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems);
1364   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1365 
1366   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1367   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1368 
1369   return
1370     DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1371 }
1372 
1373 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1374                                      llvm::DIFile Unit) {
1375   uint64_t Size;
1376   uint64_t Align;
1377 
1378 
1379   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1380   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1381     Size = 0;
1382     Align =
1383       CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1384   } else if (Ty->isIncompleteArrayType()) {
1385     Size = 0;
1386     Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1387   } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1388     Size = 0;
1389     Align = 0;
1390   } else {
1391     // Size and align of the whole array, not the element type.
1392     Size = CGM.getContext().getTypeSize(Ty);
1393     Align = CGM.getContext().getTypeAlign(Ty);
1394   }
1395 
1396   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1397   // interior arrays, do we care?  Why aren't nested arrays represented the
1398   // obvious/recursive way?
1399   SmallVector<llvm::Value *, 8> Subscripts;
1400   QualType EltTy(Ty, 0);
1401   if (Ty->isIncompleteArrayType())
1402     EltTy = Ty->getElementType();
1403   else {
1404     while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1405       int64_t UpperBound = 0;
1406       int64_t LowerBound = 0;
1407       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
1408         if (CAT->getSize().getZExtValue())
1409           UpperBound = CAT->getSize().getZExtValue() - 1;
1410       } else
1411         // This is an unbounded array. Use Low = 1, Hi = 0 to express such
1412         // arrays.
1413         LowerBound = 1;
1414 
1415       // FIXME: Verify this is right for VLAs.
1416       Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound,
1417                                                         UpperBound));
1418       EltTy = Ty->getElementType();
1419     }
1420   }
1421 
1422   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1423 
1424   llvm::DIType DbgTy =
1425     DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1426                              SubscriptArray);
1427   return DbgTy;
1428 }
1429 
1430 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1431                                      llvm::DIFile Unit) {
1432   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1433                                Ty, Ty->getPointeeType(), Unit);
1434 }
1435 
1436 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1437                                      llvm::DIFile Unit) {
1438   return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1439                                Ty, Ty->getPointeeType(), Unit);
1440 }
1441 
1442 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1443                                      llvm::DIFile U) {
1444   QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1445   llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1446 
1447   if (!Ty->getPointeeType()->isFunctionType()) {
1448     // We have a data member pointer type.
1449     return PointerDiffDITy;
1450   }
1451 
1452   // We have a member function pointer type. Treat it as a struct with two
1453   // ptrdiff_t members.
1454   std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1455 
1456   uint64_t FieldOffset = 0;
1457   llvm::Value *ElementTypes[2];
1458 
1459   // FIXME: This should probably be a function type instead.
1460   ElementTypes[0] =
1461     DBuilder.createMemberType(U, "ptr", U, 0,
1462                               Info.first, Info.second, FieldOffset, 0,
1463                               PointerDiffDITy);
1464   FieldOffset += Info.first;
1465 
1466   ElementTypes[1] =
1467     DBuilder.createMemberType(U, "ptr", U, 0,
1468                               Info.first, Info.second, FieldOffset, 0,
1469                               PointerDiffDITy);
1470 
1471   llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes);
1472 
1473   return DBuilder.createStructType(U, StringRef("test"),
1474                                    U, 0, FieldOffset,
1475                                    0, 0, Elements);
1476 }
1477 
1478 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1479                                      llvm::DIFile U) {
1480   // Ignore the atomic wrapping
1481   // FIXME: What is the correct representation?
1482   return getOrCreateType(Ty->getValueType(), U);
1483 }
1484 
1485 /// CreateEnumType - get enumeration type.
1486 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1487   llvm::DIFile Unit = getOrCreateFile(ED->getLocation());
1488   SmallVector<llvm::Value *, 16> Enumerators;
1489 
1490   // Create DIEnumerator elements for each enumerator.
1491   for (EnumDecl::enumerator_iterator
1492          Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1493        Enum != EnumEnd; ++Enum) {
1494     Enumerators.push_back(
1495       DBuilder.createEnumerator(Enum->getName(),
1496                                 Enum->getInitVal().getZExtValue()));
1497   }
1498 
1499   // Return a CompositeType for the enum itself.
1500   llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1501 
1502   llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1503   unsigned Line = getLineNumber(ED->getLocation());
1504   uint64_t Size = 0;
1505   uint64_t Align = 0;
1506   if (!ED->getTypeForDecl()->isIncompleteType()) {
1507     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1508     Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1509   }
1510   llvm::DIDescriptor EnumContext =
1511     getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1512   llvm::DIType DbgTy =
1513     DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1514                                    Size, Align, EltArray);
1515   return DbgTy;
1516 }
1517 
1518 static QualType UnwrapTypeForDebugInfo(QualType T) {
1519   do {
1520     QualType LastT = T;
1521     switch (T->getTypeClass()) {
1522     default:
1523       return T;
1524     case Type::TemplateSpecialization:
1525       T = cast<TemplateSpecializationType>(T)->desugar();
1526       break;
1527     case Type::TypeOfExpr:
1528       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1529       break;
1530     case Type::TypeOf:
1531       T = cast<TypeOfType>(T)->getUnderlyingType();
1532       break;
1533     case Type::Decltype:
1534       T = cast<DecltypeType>(T)->getUnderlyingType();
1535       break;
1536     case Type::UnaryTransform:
1537       T = cast<UnaryTransformType>(T)->getUnderlyingType();
1538       break;
1539     case Type::Attributed:
1540       T = cast<AttributedType>(T)->getEquivalentType();
1541       break;
1542     case Type::Elaborated:
1543       T = cast<ElaboratedType>(T)->getNamedType();
1544       break;
1545     case Type::Paren:
1546       T = cast<ParenType>(T)->getInnerType();
1547       break;
1548     case Type::SubstTemplateTypeParm:
1549       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1550       break;
1551     case Type::Auto:
1552       T = cast<AutoType>(T)->getDeducedType();
1553       break;
1554     }
1555 
1556     assert(T != LastT && "Type unwrapping failed to unwrap!");
1557     if (T == LastT)
1558       return T;
1559   } while (true);
1560 }
1561 
1562 /// getType - Get the type from the cache or return null type if it doesn't exist.
1563 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1564 
1565   // Unwrap the type as needed for debug information.
1566   Ty = UnwrapTypeForDebugInfo(Ty);
1567 
1568   // Check for existing entry.
1569   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1570     TypeCache.find(Ty.getAsOpaquePtr());
1571   if (it != TypeCache.end()) {
1572     // Verify that the debug info still exists.
1573     if (&*it->second)
1574       return llvm::DIType(cast<llvm::MDNode>(it->second));
1575   }
1576 
1577   return llvm::DIType();
1578 }
1579 
1580 /// getCompletedTypeOrNull - Get the type from the cache or return null if it
1581 /// doesn't exist.
1582 llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1583 
1584   // Unwrap the type as needed for debug information.
1585   Ty = UnwrapTypeForDebugInfo(Ty);
1586 
1587   // Check for existing entry.
1588   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1589     CompletedTypeCache.find(Ty.getAsOpaquePtr());
1590   if (it != CompletedTypeCache.end()) {
1591     // Verify that the debug info still exists.
1592     if (&*it->second)
1593       return llvm::DIType(cast<llvm::MDNode>(it->second));
1594   }
1595 
1596   return llvm::DIType();
1597 }
1598 
1599 
1600 /// getOrCreateType - Get the type from the cache or create a new
1601 /// one if necessary.
1602 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1603   if (Ty.isNull())
1604     return llvm::DIType();
1605 
1606   // Unwrap the type as needed for debug information.
1607   Ty = UnwrapTypeForDebugInfo(Ty);
1608 
1609   llvm::DIType T = getCompletedTypeOrNull(Ty);
1610 
1611   if (T.Verify()) return T;
1612 
1613   // Otherwise create the type.
1614   llvm::DIType Res = CreateTypeNode(Ty, Unit);
1615 
1616   llvm::DIType TC = getTypeOrNull(Ty);
1617   if (TC.Verify() && TC.isForwardDecl())
1618     ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(), TC));
1619 
1620   // And update the type cache.
1621   TypeCache[Ty.getAsOpaquePtr()] = Res;
1622 
1623   if (!Res.isForwardDecl())
1624     CompletedTypeCache[Ty.getAsOpaquePtr()] = Res;
1625   return Res;
1626 }
1627 
1628 /// CreateTypeNode - Create a new debug type node.
1629 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1630   // Handle qualifiers, which recursively handles what they refer to.
1631   if (Ty.hasLocalQualifiers())
1632     return CreateQualifiedType(Ty, Unit);
1633 
1634   const char *Diag = 0;
1635 
1636   // Work out details of type.
1637   switch (Ty->getTypeClass()) {
1638 #define TYPE(Class, Base)
1639 #define ABSTRACT_TYPE(Class, Base)
1640 #define NON_CANONICAL_TYPE(Class, Base)
1641 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1642 #include "clang/AST/TypeNodes.def"
1643     llvm_unreachable("Dependent types cannot show up in debug information");
1644 
1645   case Type::ExtVector:
1646   case Type::Vector:
1647     return CreateType(cast<VectorType>(Ty), Unit);
1648   case Type::ObjCObjectPointer:
1649     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1650   case Type::ObjCObject:
1651     return CreateType(cast<ObjCObjectType>(Ty), Unit);
1652   case Type::ObjCInterface:
1653     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1654   case Type::Builtin:
1655     return CreateType(cast<BuiltinType>(Ty));
1656   case Type::Complex:
1657     return CreateType(cast<ComplexType>(Ty));
1658   case Type::Pointer:
1659     return CreateType(cast<PointerType>(Ty), Unit);
1660   case Type::BlockPointer:
1661     return CreateType(cast<BlockPointerType>(Ty), Unit);
1662   case Type::Typedef:
1663     return CreateType(cast<TypedefType>(Ty), Unit);
1664   case Type::Record:
1665     return CreateType(cast<RecordType>(Ty));
1666   case Type::Enum:
1667     return CreateEnumType(cast<EnumType>(Ty)->getDecl());
1668   case Type::FunctionProto:
1669   case Type::FunctionNoProto:
1670     return CreateType(cast<FunctionType>(Ty), Unit);
1671   case Type::ConstantArray:
1672   case Type::VariableArray:
1673   case Type::IncompleteArray:
1674     return CreateType(cast<ArrayType>(Ty), Unit);
1675 
1676   case Type::LValueReference:
1677     return CreateType(cast<LValueReferenceType>(Ty), Unit);
1678   case Type::RValueReference:
1679     return CreateType(cast<RValueReferenceType>(Ty), Unit);
1680 
1681   case Type::MemberPointer:
1682     return CreateType(cast<MemberPointerType>(Ty), Unit);
1683 
1684   case Type::Atomic:
1685     return CreateType(cast<AtomicType>(Ty), Unit);
1686 
1687   case Type::Attributed:
1688   case Type::TemplateSpecialization:
1689   case Type::Elaborated:
1690   case Type::Paren:
1691   case Type::SubstTemplateTypeParm:
1692   case Type::TypeOfExpr:
1693   case Type::TypeOf:
1694   case Type::Decltype:
1695   case Type::UnaryTransform:
1696   case Type::Auto:
1697     llvm_unreachable("type should have been unwrapped!");
1698   }
1699 
1700   assert(Diag && "Fall through without a diagnostic?");
1701   unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1702                                "debug information for %0 is not yet supported");
1703   CGM.getDiags().Report(DiagID)
1704     << Diag;
1705   return llvm::DIType();
1706 }
1707 
1708 /// getOrCreateLimitedType - Get the type from the cache or create a new
1709 /// limited type if necessary.
1710 llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
1711 						 llvm::DIFile Unit) {
1712   if (Ty.isNull())
1713     return llvm::DIType();
1714 
1715   // Unwrap the type as needed for debug information.
1716   Ty = UnwrapTypeForDebugInfo(Ty);
1717 
1718   llvm::DIType T = getTypeOrNull(Ty);
1719 
1720   // We may have cached a forward decl when we could have created
1721   // a non-forward decl. Go ahead and create a non-forward decl
1722   // now.
1723   if (T.Verify() && !T.isForwardDecl()) return T;
1724 
1725   // Otherwise create the type.
1726   llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
1727 
1728   if (T.Verify() && T.isForwardDecl())
1729     ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(), T));
1730 
1731   // And update the type cache.
1732   TypeCache[Ty.getAsOpaquePtr()] = Res;
1733   return Res;
1734 }
1735 
1736 // TODO: Currently used for context chains when limiting debug info.
1737 llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
1738   RecordDecl *RD = Ty->getDecl();
1739 
1740   // Get overall information about the record type for the debug info.
1741   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1742   unsigned Line = getLineNumber(RD->getLocation());
1743   StringRef RDName = RD->getName();
1744 
1745   llvm::DIDescriptor RDContext;
1746   if (CGM.getCodeGenOpts().LimitDebugInfo)
1747     RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
1748   else
1749     RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1750 
1751   // If this is just a forward declaration, construct an appropriately
1752   // marked node and just return it.
1753   if (!RD->getDefinition())
1754     return createRecordFwdDecl(RD, RDContext);
1755 
1756   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1757   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1758   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1759   llvm::MDNode *RealDecl = NULL;
1760 
1761   if (RD->isUnion())
1762     RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
1763 					Size, Align, 0, llvm::DIArray());
1764   else if (CXXDecl) {
1765     RDName = getClassName(RD);
1766 
1767     // FIXME: This could be a struct type giving a default visibility different
1768     // than C++ class type, but needs llvm metadata changes first.
1769     RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
1770 					Size, Align, 0, 0, llvm::DIType(),
1771 					llvm::DIArray(), llvm::DIType(),
1772 					llvm::DIArray());
1773   } else
1774     RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
1775 					 Size, Align, 0, llvm::DIArray());
1776 
1777   RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1778   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = llvm::DIType(RealDecl);
1779 
1780   if (CXXDecl) {
1781     // A class's primary base or the class itself contains the vtable.
1782     llvm::MDNode *ContainingType = NULL;
1783     const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1784     if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
1785       // Seek non virtual primary base root.
1786       while (1) {
1787 	const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
1788 	const CXXRecordDecl *PBT = BRL.getPrimaryBase();
1789 	if (PBT && !BRL.isPrimaryBaseVirtual())
1790 	  PBase = PBT;
1791 	else
1792 	  break;
1793       }
1794       ContainingType =
1795 	getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit);
1796     }
1797     else if (CXXDecl->isDynamicClass())
1798       ContainingType = RealDecl;
1799 
1800     RealDecl->replaceOperandWith(12, ContainingType);
1801   }
1802   return llvm::DIType(RealDecl);
1803 }
1804 
1805 /// CreateLimitedTypeNode - Create a new debug type node, but only forward
1806 /// declare composite types that haven't been processed yet.
1807 llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
1808 
1809   // Work out details of type.
1810   switch (Ty->getTypeClass()) {
1811 #define TYPE(Class, Base)
1812 #define ABSTRACT_TYPE(Class, Base)
1813 #define NON_CANONICAL_TYPE(Class, Base)
1814 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1815         #include "clang/AST/TypeNodes.def"
1816     llvm_unreachable("Dependent types cannot show up in debug information");
1817 
1818   case Type::Record:
1819     return CreateLimitedType(cast<RecordType>(Ty));
1820   default:
1821     return CreateTypeNode(Ty, Unit);
1822   }
1823 }
1824 
1825 /// CreateMemberType - Create new member and increase Offset by FType's size.
1826 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1827                                            StringRef Name,
1828                                            uint64_t *Offset) {
1829   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1830   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1831   unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1832   llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
1833                                               FieldSize, FieldAlign,
1834                                               *Offset, 0, FieldTy);
1835   *Offset += FieldSize;
1836   return Ty;
1837 }
1838 
1839 /// getFunctionDeclaration - Return debug info descriptor to describe method
1840 /// declaration for the given method definition.
1841 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
1842   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1843   if (!FD) return llvm::DISubprogram();
1844 
1845   // Setup context.
1846   getContextDescriptor(cast<Decl>(D->getDeclContext()));
1847 
1848   llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1849     MI = SPCache.find(FD->getCanonicalDecl());
1850   if (MI != SPCache.end()) {
1851     llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1852     if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1853       return SP;
1854   }
1855 
1856   for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
1857          E = FD->redecls_end(); I != E; ++I) {
1858     const FunctionDecl *NextFD = *I;
1859     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1860       MI = SPCache.find(NextFD->getCanonicalDecl());
1861     if (MI != SPCache.end()) {
1862       llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1863       if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1864         return SP;
1865     }
1866   }
1867   return llvm::DISubprogram();
1868 }
1869 
1870 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
1871 // implicit parameter "this".
1872 llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl * D,
1873                                                   QualType FnType,
1874                                                   llvm::DIFile F) {
1875   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1876     return getOrCreateMethodType(Method, F);
1877   if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
1878     // Add "self" and "_cmd"
1879     SmallVector<llvm::Value *, 16> Elts;
1880 
1881     // First element is always return type. For 'void' functions it is NULL.
1882     Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
1883     // "self" pointer is always first argument.
1884     Elts.push_back(getOrCreateType(OMethod->getSelfDecl()->getType(), F));
1885     // "cmd" pointer is always second argument.
1886     Elts.push_back(getOrCreateType(OMethod->getCmdDecl()->getType(), F));
1887     // Get rest of the arguments.
1888     for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
1889            PE = OMethod->param_end(); PI != PE; ++PI)
1890       Elts.push_back(getOrCreateType((*PI)->getType(), F));
1891 
1892     llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1893     return DBuilder.createSubroutineType(F, EltTypeArray);
1894   }
1895   return getOrCreateType(FnType, F);
1896 }
1897 
1898 /// EmitFunctionStart - Constructs the debug code for entering a function -
1899 /// "llvm.dbg.func.start.".
1900 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1901                                     llvm::Function *Fn,
1902                                     CGBuilderTy &Builder) {
1903 
1904   StringRef Name;
1905   StringRef LinkageName;
1906 
1907   FnBeginRegionCount.push_back(LexicalBlockStack.size());
1908 
1909   const Decl *D = GD.getDecl();
1910 
1911   unsigned Flags = 0;
1912   llvm::DIFile Unit = getOrCreateFile(CurLoc);
1913   llvm::DIDescriptor FDContext(Unit);
1914   llvm::DIArray TParamsArray;
1915   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1916     // If there is a DISubprogram for this function available then use it.
1917     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1918       FI = SPCache.find(FD->getCanonicalDecl());
1919     if (FI != SPCache.end()) {
1920       llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second));
1921       if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1922         llvm::MDNode *SPN = SP;
1923         LexicalBlockStack.push_back(SPN);
1924         RegionMap[D] = llvm::WeakVH(SP);
1925         return;
1926       }
1927     }
1928     Name = getFunctionName(FD);
1929     // Use mangled name as linkage name for c/c++ functions.
1930     if (!Fn->hasInternalLinkage())
1931       LinkageName = CGM.getMangledName(GD);
1932     if (LinkageName == Name)
1933       LinkageName = StringRef();
1934     if (FD->hasPrototype())
1935       Flags |= llvm::DIDescriptor::FlagPrototyped;
1936     if (const NamespaceDecl *NSDecl =
1937         dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
1938       FDContext = getOrCreateNameSpace(NSDecl);
1939     else if (const RecordDecl *RDecl =
1940              dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
1941       FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
1942 
1943     // Collect template parameters.
1944     TParamsArray = CollectFunctionTemplateParams(FD, Unit);
1945   } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
1946     Name = getObjCMethodName(OMD);
1947     Flags |= llvm::DIDescriptor::FlagPrototyped;
1948   } else {
1949     // Use llvm function name.
1950     Name = Fn->getName();
1951     Flags |= llvm::DIDescriptor::FlagPrototyped;
1952   }
1953   if (!Name.empty() && Name[0] == '\01')
1954     Name = Name.substr(1);
1955 
1956   // It is expected that CurLoc is set before using EmitFunctionStart.
1957   // Usually, CurLoc points to the left bracket location of compound
1958   // statement representing function body.
1959   unsigned LineNo = getLineNumber(CurLoc);
1960   if (D->isImplicit())
1961     Flags |= llvm::DIDescriptor::FlagArtificial;
1962   llvm::DISubprogram SPDecl = getFunctionDeclaration(D);
1963   llvm::DISubprogram SP =
1964     DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
1965                             LineNo, getOrCreateFunctionType(D, FnType, Unit),
1966                             Fn->hasInternalLinkage(), true/*definition*/,
1967                             Flags, CGM.getLangOptions().Optimize, Fn,
1968                             TParamsArray, SPDecl);
1969 
1970   // Push function on region stack.
1971   llvm::MDNode *SPN = SP;
1972   LexicalBlockStack.push_back(SPN);
1973   RegionMap[D] = llvm::WeakVH(SP);
1974 }
1975 
1976 /// EmitLocation - Emit metadata to indicate a change in line/column
1977 /// information in the source file.
1978 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
1979 
1980   // Update our current location
1981   setLocation(Loc);
1982 
1983   if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1984 
1985   // Don't bother if things are the same as last time.
1986   SourceManager &SM = CGM.getContext().getSourceManager();
1987   if (CurLoc == PrevLoc ||
1988       SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
1989     // New Builder may not be in sync with CGDebugInfo.
1990     if (!Builder.getCurrentDebugLocation().isUnknown())
1991       return;
1992 
1993   // Update last state.
1994   PrevLoc = CurLoc;
1995 
1996   llvm::MDNode *Scope = LexicalBlockStack.back();
1997   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
1998                                                       getColumnNumber(CurLoc),
1999                                                       Scope));
2000 }
2001 
2002 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2003 /// the stack.
2004 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2005   llvm::DIDescriptor D =
2006     DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2007                                 llvm::DIDescriptor() :
2008                                 llvm::DIDescriptor(LexicalBlockStack.back()),
2009                                 getOrCreateFile(CurLoc),
2010                                 getLineNumber(CurLoc),
2011                                 getColumnNumber(CurLoc));
2012   llvm::MDNode *DN = D;
2013   LexicalBlockStack.push_back(DN);
2014 }
2015 
2016 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2017 /// region - beginning of a DW_TAG_lexical_block.
2018 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2019   // Set our current location.
2020   setLocation(Loc);
2021 
2022   // Create a new lexical block and push it on the stack.
2023   CreateLexicalBlock(Loc);
2024 
2025   // Emit a line table change for the current location inside the new scope.
2026   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2027                                   getColumnNumber(Loc),
2028                                   LexicalBlockStack.back()));
2029 }
2030 
2031 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2032 /// region - end of a DW_TAG_lexical_block.
2033 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2034   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2035 
2036   // Provide an entry in the line table for the end of the block.
2037   EmitLocation(Builder, Loc);
2038 
2039   LexicalBlockStack.pop_back();
2040 }
2041 
2042 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
2043 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2044   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2045   unsigned RCount = FnBeginRegionCount.back();
2046   assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2047 
2048   // Pop all regions for this function.
2049   while (LexicalBlockStack.size() != RCount)
2050     EmitLexicalBlockEnd(Builder, CurLoc);
2051   FnBeginRegionCount.pop_back();
2052 }
2053 
2054 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2055 // See BuildByRefType.
2056 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
2057                                                        uint64_t *XOffset) {
2058 
2059   SmallVector<llvm::Value *, 5> EltTys;
2060   QualType FType;
2061   uint64_t FieldSize, FieldOffset;
2062   unsigned FieldAlign;
2063 
2064   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2065   QualType Type = VD->getType();
2066 
2067   FieldOffset = 0;
2068   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2069   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2070   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2071   FType = CGM.getContext().IntTy;
2072   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2073   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2074 
2075   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type);
2076   if (HasCopyAndDispose) {
2077     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2078     EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2079                                       &FieldOffset));
2080     EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2081                                       &FieldOffset));
2082   }
2083 
2084   CharUnits Align = CGM.getContext().getDeclAlign(VD);
2085   if (Align > CGM.getContext().toCharUnitsFromBits(
2086         CGM.getContext().getTargetInfo().getPointerAlign(0))) {
2087     CharUnits FieldOffsetInBytes
2088       = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2089     CharUnits AlignedOffsetInBytes
2090       = FieldOffsetInBytes.RoundUpToAlignment(Align);
2091     CharUnits NumPaddingBytes
2092       = AlignedOffsetInBytes - FieldOffsetInBytes;
2093 
2094     if (NumPaddingBytes.isPositive()) {
2095       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2096       FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2097                                                     pad, ArrayType::Normal, 0);
2098       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2099     }
2100   }
2101 
2102   FType = Type;
2103   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2104   FieldSize = CGM.getContext().getTypeSize(FType);
2105   FieldAlign = CGM.getContext().toBits(Align);
2106 
2107   *XOffset = FieldOffset;
2108   FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2109                                       0, FieldSize, FieldAlign,
2110                                       FieldOffset, 0, FieldTy);
2111   EltTys.push_back(FieldTy);
2112   FieldOffset += FieldSize;
2113 
2114   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2115 
2116   unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2117 
2118   return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2119                                    Elements);
2120 }
2121 
2122 /// EmitDeclare - Emit local variable declaration debug info.
2123 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2124                               llvm::Value *Storage,
2125                               unsigned ArgNo, CGBuilderTy &Builder) {
2126   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2127 
2128   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2129   llvm::DIType Ty;
2130   uint64_t XOffset = 0;
2131   if (VD->hasAttr<BlocksAttr>())
2132     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2133   else
2134     Ty = getOrCreateType(VD->getType(), Unit);
2135 
2136   // If there is not any debug info for type then do not emit debug info
2137   // for this variable.
2138   if (!Ty)
2139     return;
2140 
2141   if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2142     // If Storage is an aggregate returned as 'sret' then let debugger know
2143     // about this.
2144     if (Arg->hasStructRetAttr())
2145       Ty = DBuilder.createReferenceType(Ty);
2146     else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2147       // If an aggregate variable has non trivial destructor or non trivial copy
2148       // constructor than it is pass indirectly. Let debug info know about this
2149       // by using reference of the aggregate type as a argument type.
2150       if (!Record->hasTrivialCopyConstructor() ||
2151           !Record->hasTrivialDestructor())
2152         Ty = DBuilder.createReferenceType(Ty);
2153     }
2154   }
2155 
2156   // Get location information.
2157   unsigned Line = getLineNumber(VD->getLocation());
2158   unsigned Column = getColumnNumber(VD->getLocation());
2159   unsigned Flags = 0;
2160   if (VD->isImplicit())
2161     Flags |= llvm::DIDescriptor::FlagArtificial;
2162   llvm::MDNode *Scope = LexicalBlockStack.back();
2163 
2164   StringRef Name = VD->getName();
2165   if (!Name.empty()) {
2166     if (VD->hasAttr<BlocksAttr>()) {
2167       CharUnits offset = CharUnits::fromQuantity(32);
2168       SmallVector<llvm::Value *, 9> addr;
2169       llvm::Type *Int64Ty = CGM.Int64Ty;
2170       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2171       // offset of __forwarding field
2172       offset = CGM.getContext().toCharUnitsFromBits(
2173         CGM.getContext().getTargetInfo().getPointerWidth(0));
2174       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2175       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2176       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2177       // offset of x field
2178       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2179       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2180 
2181       // Create the descriptor for the variable.
2182       llvm::DIVariable D =
2183         DBuilder.createComplexVariable(Tag,
2184                                        llvm::DIDescriptor(Scope),
2185                                        VD->getName(), Unit, Line, Ty,
2186                                        addr, ArgNo);
2187 
2188       // Insert an llvm.dbg.declare into the current block.
2189       llvm::Instruction *Call =
2190         DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2191       Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2192       return;
2193     }
2194       // Create the descriptor for the variable.
2195     llvm::DIVariable D =
2196       DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2197                                    Name, Unit, Line, Ty,
2198                                    CGM.getLangOptions().Optimize, Flags, ArgNo);
2199 
2200     // Insert an llvm.dbg.declare into the current block.
2201     llvm::Instruction *Call =
2202       DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2203     Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2204     return;
2205   }
2206 
2207   // If VD is an anonymous union then Storage represents value for
2208   // all union fields.
2209   if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2210     const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2211     if (RD->isUnion()) {
2212       for (RecordDecl::field_iterator I = RD->field_begin(),
2213              E = RD->field_end();
2214            I != E; ++I) {
2215         FieldDecl *Field = *I;
2216         llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2217         StringRef FieldName = Field->getName();
2218 
2219         // Ignore unnamed fields. Do not ignore unnamed records.
2220         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2221           continue;
2222 
2223         // Use VarDecl's Tag, Scope and Line number.
2224         llvm::DIVariable D =
2225           DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2226                                        FieldName, Unit, Line, FieldTy,
2227                                        CGM.getLangOptions().Optimize, Flags,
2228                                        ArgNo);
2229 
2230         // Insert an llvm.dbg.declare into the current block.
2231         llvm::Instruction *Call =
2232           DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2233         Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2234       }
2235     }
2236   }
2237 }
2238 
2239 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2240                                             llvm::Value *Storage,
2241                                             CGBuilderTy &Builder) {
2242   EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2243 }
2244 
2245 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2246   const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2247   const CGBlockInfo &blockInfo) {
2248   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2249 
2250   if (Builder.GetInsertBlock() == 0)
2251     return;
2252 
2253   bool isByRef = VD->hasAttr<BlocksAttr>();
2254 
2255   uint64_t XOffset = 0;
2256   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2257   llvm::DIType Ty;
2258   if (isByRef)
2259     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2260   else
2261     Ty = getOrCreateType(VD->getType(), Unit);
2262 
2263   // Get location information.
2264   unsigned Line = getLineNumber(VD->getLocation());
2265   unsigned Column = getColumnNumber(VD->getLocation());
2266 
2267   const llvm::TargetData &target = CGM.getTargetData();
2268 
2269   CharUnits offset = CharUnits::fromQuantity(
2270     target.getStructLayout(blockInfo.StructureType)
2271           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2272 
2273   SmallVector<llvm::Value *, 9> addr;
2274   llvm::Type *Int64Ty = CGM.Int64Ty;
2275   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2276   addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2277   if (isByRef) {
2278     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2279     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2280     // offset of __forwarding field
2281     offset = CGM.getContext()
2282                 .toCharUnitsFromBits(target.getPointerSizeInBits());
2283     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2284     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2285     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2286     // offset of x field
2287     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2288     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2289   }
2290 
2291   // Create the descriptor for the variable.
2292   llvm::DIVariable D =
2293     DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2294                                    llvm::DIDescriptor(LexicalBlockStack.back()),
2295                                    VD->getName(), Unit, Line, Ty, addr);
2296   // Insert an llvm.dbg.declare into the current block.
2297   llvm::Instruction *Call =
2298     DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2299   Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2300                                         LexicalBlockStack.back()));
2301 }
2302 
2303 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2304 /// variable declaration.
2305 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2306                                            unsigned ArgNo,
2307                                            CGBuilderTy &Builder) {
2308   EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2309 }
2310 
2311 namespace {
2312   struct BlockLayoutChunk {
2313     uint64_t OffsetInBits;
2314     const BlockDecl::Capture *Capture;
2315   };
2316   bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2317     return l.OffsetInBits < r.OffsetInBits;
2318   }
2319 }
2320 
2321 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2322                                                        llvm::Value *addr,
2323                                                        CGBuilderTy &Builder) {
2324   ASTContext &C = CGM.getContext();
2325   const BlockDecl *blockDecl = block.getBlockDecl();
2326 
2327   // Collect some general information about the block's location.
2328   SourceLocation loc = blockDecl->getCaretLocation();
2329   llvm::DIFile tunit = getOrCreateFile(loc);
2330   unsigned line = getLineNumber(loc);
2331   unsigned column = getColumnNumber(loc);
2332 
2333   // Build the debug-info type for the block literal.
2334   getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2335 
2336   const llvm::StructLayout *blockLayout =
2337     CGM.getTargetData().getStructLayout(block.StructureType);
2338 
2339   SmallVector<llvm::Value*, 16> fields;
2340   fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2341                                    blockLayout->getElementOffsetInBits(0),
2342                                    tunit, tunit));
2343   fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2344                                    blockLayout->getElementOffsetInBits(1),
2345                                    tunit, tunit));
2346   fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2347                                    blockLayout->getElementOffsetInBits(2),
2348                                    tunit, tunit));
2349   fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2350                                    blockLayout->getElementOffsetInBits(3),
2351                                    tunit, tunit));
2352   fields.push_back(createFieldType("__descriptor",
2353                                    C.getPointerType(block.NeedsCopyDispose ?
2354                                         C.getBlockDescriptorExtendedType() :
2355                                         C.getBlockDescriptorType()),
2356                                    0, loc, AS_public,
2357                                    blockLayout->getElementOffsetInBits(4),
2358                                    tunit, tunit));
2359 
2360   // We want to sort the captures by offset, not because DWARF
2361   // requires this, but because we're paranoid about debuggers.
2362   SmallVector<BlockLayoutChunk, 8> chunks;
2363 
2364   // 'this' capture.
2365   if (blockDecl->capturesCXXThis()) {
2366     BlockLayoutChunk chunk;
2367     chunk.OffsetInBits =
2368       blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2369     chunk.Capture = 0;
2370     chunks.push_back(chunk);
2371   }
2372 
2373   // Variable captures.
2374   for (BlockDecl::capture_const_iterator
2375          i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2376        i != e; ++i) {
2377     const BlockDecl::Capture &capture = *i;
2378     const VarDecl *variable = capture.getVariable();
2379     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2380 
2381     // Ignore constant captures.
2382     if (captureInfo.isConstant())
2383       continue;
2384 
2385     BlockLayoutChunk chunk;
2386     chunk.OffsetInBits =
2387       blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2388     chunk.Capture = &capture;
2389     chunks.push_back(chunk);
2390   }
2391 
2392   // Sort by offset.
2393   llvm::array_pod_sort(chunks.begin(), chunks.end());
2394 
2395   for (SmallVectorImpl<BlockLayoutChunk>::iterator
2396          i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2397     uint64_t offsetInBits = i->OffsetInBits;
2398     const BlockDecl::Capture *capture = i->Capture;
2399 
2400     // If we have a null capture, this must be the C++ 'this' capture.
2401     if (!capture) {
2402       const CXXMethodDecl *method =
2403         cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2404       QualType type = method->getThisType(C);
2405 
2406       fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2407                                        offsetInBits, tunit, tunit));
2408       continue;
2409     }
2410 
2411     const VarDecl *variable = capture->getVariable();
2412     StringRef name = variable->getName();
2413 
2414     llvm::DIType fieldType;
2415     if (capture->isByRef()) {
2416       std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2417 
2418       // FIXME: this creates a second copy of this type!
2419       uint64_t xoffset;
2420       fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2421       fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2422       fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2423                                             ptrInfo.first, ptrInfo.second,
2424                                             offsetInBits, 0, fieldType);
2425     } else {
2426       fieldType = createFieldType(name, variable->getType(), 0,
2427                                   loc, AS_public, offsetInBits, tunit, tunit);
2428     }
2429     fields.push_back(fieldType);
2430   }
2431 
2432   SmallString<36> typeName;
2433   llvm::raw_svector_ostream(typeName)
2434     << "__block_literal_" << CGM.getUniqueBlockCount();
2435 
2436   llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2437 
2438   llvm::DIType type =
2439     DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2440                               CGM.getContext().toBits(block.BlockSize),
2441                               CGM.getContext().toBits(block.BlockAlign),
2442                               0, fieldsArray);
2443   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2444 
2445   // Get overall information about the block.
2446   unsigned flags = llvm::DIDescriptor::FlagArtificial;
2447   llvm::MDNode *scope = LexicalBlockStack.back();
2448   StringRef name = ".block_descriptor";
2449 
2450   // Create the descriptor for the parameter.
2451   llvm::DIVariable debugVar =
2452     DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2453                                  llvm::DIDescriptor(scope),
2454                                  name, tunit, line, type,
2455                                  CGM.getLangOptions().Optimize, flags,
2456                                  cast<llvm::Argument>(addr)->getArgNo() + 1);
2457 
2458   // Insert an llvm.dbg.value into the current block.
2459   llvm::Instruction *declare =
2460     DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2461                                      Builder.GetInsertBlock());
2462   declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2463 }
2464 
2465 /// EmitGlobalVariable - Emit information about a global variable.
2466 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2467                                      const VarDecl *D) {
2468   // Create global variable debug descriptor.
2469   llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2470   unsigned LineNo = getLineNumber(D->getLocation());
2471 
2472   setLocation(D->getLocation());
2473 
2474   QualType T = D->getType();
2475   if (T->isIncompleteArrayType()) {
2476 
2477     // CodeGen turns int[] into int[1] so we'll do the same here.
2478     llvm::APSInt ConstVal(32);
2479 
2480     ConstVal = 1;
2481     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2482 
2483     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2484                                               ArrayType::Normal, 0);
2485   }
2486   StringRef DeclName = D->getName();
2487   StringRef LinkageName;
2488   if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2489       && !isa<ObjCMethodDecl>(D->getDeclContext()))
2490     LinkageName = Var->getName();
2491   if (LinkageName == DeclName)
2492     LinkageName = StringRef();
2493   llvm::DIDescriptor DContext =
2494     getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2495   DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2496                                 Unit, LineNo, getOrCreateType(T, Unit),
2497                                 Var->hasInternalLinkage(), Var);
2498 }
2499 
2500 /// EmitGlobalVariable - Emit information about an objective-c interface.
2501 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2502                                      ObjCInterfaceDecl *ID) {
2503   // Create global variable debug descriptor.
2504   llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2505   unsigned LineNo = getLineNumber(ID->getLocation());
2506 
2507   StringRef Name = ID->getName();
2508 
2509   QualType T = CGM.getContext().getObjCInterfaceType(ID);
2510   if (T->isIncompleteArrayType()) {
2511 
2512     // CodeGen turns int[] into int[1] so we'll do the same here.
2513     llvm::APSInt ConstVal(32);
2514 
2515     ConstVal = 1;
2516     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2517 
2518     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2519                                            ArrayType::Normal, 0);
2520   }
2521 
2522   DBuilder.createGlobalVariable(Name, Unit, LineNo,
2523                                 getOrCreateType(T, Unit),
2524                                 Var->hasInternalLinkage(), Var);
2525 }
2526 
2527 /// EmitGlobalVariable - Emit global variable's debug info.
2528 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2529                                      llvm::Constant *Init) {
2530   // Create the descriptor for the variable.
2531   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2532   StringRef Name = VD->getName();
2533   llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2534   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2535     if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext()))
2536       Ty = CreateEnumType(ED);
2537   }
2538   // Do not use DIGlobalVariable for enums.
2539   if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2540     return;
2541   DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2542                                 getLineNumber(VD->getLocation()),
2543                                 Ty, true, Init);
2544 }
2545 
2546 /// getOrCreateNamesSpace - Return namespace descriptor for the given
2547 /// namespace decl.
2548 llvm::DINameSpace
2549 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2550   llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2551     NameSpaceCache.find(NSDecl);
2552   if (I != NameSpaceCache.end())
2553     return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2554 
2555   unsigned LineNo = getLineNumber(NSDecl->getLocation());
2556   llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2557   llvm::DIDescriptor Context =
2558     getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2559   llvm::DINameSpace NS =
2560     DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2561   NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2562   return NS;
2563 }
2564 
2565 void CGDebugInfo::finalize(void) {
2566   for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
2567          = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
2568     llvm::DIType Ty, RepTy;
2569     // Verify that the debug info still exists.
2570     if (&*VI->second)
2571       Ty = llvm::DIType(cast<llvm::MDNode>(VI->second));
2572 
2573     llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2574       TypeCache.find(VI->first);
2575     if (it != TypeCache.end()) {
2576       // Verify that the debug info still exists.
2577       if (&*it->second)
2578         RepTy = llvm::DIType(cast<llvm::MDNode>(it->second));
2579     }
2580 
2581     if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify()) {
2582       Ty.replaceAllUsesWith(RepTy);
2583     }
2584   }
2585   DBuilder.finalize();
2586 }
2587