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 "CGBlocks.h"
16 #include "CGCXXABI.h"
17 #include "CGObjCRuntime.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/RecordLayout.h"
26 #include "clang/Basic/FileManager.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/Version.h"
29 #include "clang/Frontend/CodeGenOptions.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Path.h"
41 using namespace clang;
42 using namespace clang::CodeGen;
43 
44 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
45     : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
46       DBuilder(CGM.getModule()) {
47   CreateCompileUnit();
48 }
49 
50 CGDebugInfo::~CGDebugInfo() {
51   assert(LexicalBlockStack.empty() &&
52          "Region stack mismatch, stack not empty!");
53 }
54 
55 SaveAndRestoreLocation::SaveAndRestoreLocation(CodeGenFunction &CGF,
56                                                CGBuilderTy &B)
57     : DI(CGF.getDebugInfo()), Builder(B) {
58   if (DI) {
59     SavedLoc = DI->getLocation();
60     DI->CurLoc = SourceLocation();
61   }
62 }
63 
64 SaveAndRestoreLocation::~SaveAndRestoreLocation() {
65   if (DI)
66     DI->EmitLocation(Builder, SavedLoc);
67 }
68 
69 NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
70   : SaveAndRestoreLocation(CGF, B) {
71   if (DI)
72     Builder.SetCurrentDebugLocation(llvm::DebugLoc());
73 }
74 
75 NoLocation::~NoLocation() {
76   if (DI)
77     assert(Builder.getCurrentDebugLocation().isUnknown());
78 }
79 
80 ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
81   : SaveAndRestoreLocation(CGF, B) {
82   if (DI)
83     Builder.SetCurrentDebugLocation(llvm::DebugLoc());
84 }
85 
86 void ArtificialLocation::Emit() {
87   if (DI) {
88     // Sync the Builder.
89     DI->EmitLocation(Builder, SavedLoc);
90     DI->CurLoc = SourceLocation();
91     // Construct a location that has a valid scope, but no line info.
92     assert(!DI->LexicalBlockStack.empty());
93     llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
94     Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
95   }
96 }
97 
98 ArtificialLocation::~ArtificialLocation() {
99   if (DI)
100     assert(Builder.getCurrentDebugLocation().getLine() == 0);
101 }
102 
103 void CGDebugInfo::setLocation(SourceLocation Loc) {
104   // If the new location isn't valid return.
105   if (Loc.isInvalid()) return;
106 
107   CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
108 
109   // If we've changed files in the middle of a lexical scope go ahead
110   // and create a new lexical scope with file node if it's different
111   // from the one in the scope.
112   if (LexicalBlockStack.empty()) return;
113 
114   SourceManager &SM = CGM.getContext().getSourceManager();
115   PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
116   PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
117 
118   if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
119       !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
120     return;
121 
122   llvm::MDNode *LB = LexicalBlockStack.back();
123   llvm::DIScope Scope = llvm::DIScope(LB);
124   if (Scope.isLexicalBlockFile()) {
125     llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
126     llvm::DIDescriptor D
127       = DBuilder.createLexicalBlockFile(LBF.getScope(),
128                                         getOrCreateFile(CurLoc));
129     llvm::MDNode *N = D;
130     LexicalBlockStack.pop_back();
131     LexicalBlockStack.push_back(N);
132   } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
133     llvm::DIDescriptor D
134       = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
135     llvm::MDNode *N = D;
136     LexicalBlockStack.pop_back();
137     LexicalBlockStack.push_back(N);
138   }
139 }
140 
141 /// getContextDescriptor - Get context info for the decl.
142 llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
143   if (!Context)
144     return TheCU;
145 
146   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
147     I = RegionMap.find(Context);
148   if (I != RegionMap.end()) {
149     llvm::Value *V = I->second;
150     return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
151   }
152 
153   // Check namespace.
154   if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
155     return getOrCreateNameSpace(NSDecl);
156 
157   if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
158     if (!RDecl->isDependentType())
159       return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
160                                         getOrCreateMainFile());
161   return TheCU;
162 }
163 
164 /// getFunctionName - Get function name for the given FunctionDecl. If the
165 /// name is constructed on demand (e.g. C++ destructor) then the name
166 /// is stored on the side.
167 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
168   assert (FD && "Invalid FunctionDecl!");
169   IdentifierInfo *FII = FD->getIdentifier();
170   FunctionTemplateSpecializationInfo *Info
171     = FD->getTemplateSpecializationInfo();
172   if (!Info && FII)
173     return FII->getName();
174 
175   // Otherwise construct human readable name for debug info.
176   SmallString<128> NS;
177   llvm::raw_svector_ostream OS(NS);
178   FD->printName(OS);
179 
180   // Add any template specialization args.
181   if (Info) {
182     const TemplateArgumentList *TArgs = Info->TemplateArguments;
183     const TemplateArgument *Args = TArgs->data();
184     unsigned NumArgs = TArgs->size();
185     PrintingPolicy Policy(CGM.getLangOpts());
186     TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
187                                                           Policy);
188   }
189 
190   // Copy this name on the side and use its reference.
191   return internString(OS.str());
192 }
193 
194 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
195   SmallString<256> MethodName;
196   llvm::raw_svector_ostream OS(MethodName);
197   OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
198   const DeclContext *DC = OMD->getDeclContext();
199   if (const ObjCImplementationDecl *OID =
200       dyn_cast<const ObjCImplementationDecl>(DC)) {
201      OS << OID->getName();
202   } else if (const ObjCInterfaceDecl *OID =
203              dyn_cast<const ObjCInterfaceDecl>(DC)) {
204       OS << OID->getName();
205   } else if (const ObjCCategoryImplDecl *OCD =
206              dyn_cast<const ObjCCategoryImplDecl>(DC)){
207       OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
208           OCD->getIdentifier()->getNameStart() << ')';
209   } else if (isa<ObjCProtocolDecl>(DC)) {
210     // We can extract the type of the class from the self pointer.
211     if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
212       QualType ClassTy =
213         cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
214       ClassTy.print(OS, PrintingPolicy(LangOptions()));
215     }
216   }
217   OS << ' ' << OMD->getSelector().getAsString() << ']';
218 
219   return internString(OS.str());
220 }
221 
222 /// getSelectorName - Return selector name. This is used for debugging
223 /// info.
224 StringRef CGDebugInfo::getSelectorName(Selector S) {
225   return internString(S.getAsString());
226 }
227 
228 /// getClassName - Get class name including template argument list.
229 StringRef
230 CGDebugInfo::getClassName(const RecordDecl *RD) {
231   const ClassTemplateSpecializationDecl *Spec
232     = dyn_cast<ClassTemplateSpecializationDecl>(RD);
233   if (!Spec)
234     return RD->getName();
235 
236   const TemplateArgument *Args;
237   unsigned NumArgs;
238   if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
239     const TemplateSpecializationType *TST =
240       cast<TemplateSpecializationType>(TAW->getType());
241     Args = TST->getArgs();
242     NumArgs = TST->getNumArgs();
243   } else {
244     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
245     Args = TemplateArgs.data();
246     NumArgs = TemplateArgs.size();
247   }
248   StringRef Name = RD->getIdentifier()->getName();
249   PrintingPolicy Policy(CGM.getLangOpts());
250   SmallString<128> TemplateArgList;
251   {
252     llvm::raw_svector_ostream OS(TemplateArgList);
253     TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
254                                                           Policy);
255   }
256 
257   // Copy this name on the side and use its reference.
258   return internString(Name, TemplateArgList);
259 }
260 
261 /// getOrCreateFile - Get the file debug info descriptor for the input location.
262 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
263   if (!Loc.isValid())
264     // If Location is not valid then use main input file.
265     return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
266 
267   SourceManager &SM = CGM.getContext().getSourceManager();
268   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
269 
270   if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
271     // If the location is not valid then use main input file.
272     return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
273 
274   // Cache the results.
275   const char *fname = PLoc.getFilename();
276   llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
277     DIFileCache.find(fname);
278 
279   if (it != DIFileCache.end()) {
280     // Verify that the information still exists.
281     if (llvm::Value *V = it->second)
282       return llvm::DIFile(cast<llvm::MDNode>(V));
283   }
284 
285   llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
286 
287   DIFileCache[fname] = F;
288   return F;
289 }
290 
291 /// getOrCreateMainFile - Get the file info for main compile unit.
292 llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
293   return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
294 }
295 
296 /// getLineNumber - Get line number for the location. If location is invalid
297 /// then use current location.
298 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
299   if (Loc.isInvalid() && CurLoc.isInvalid())
300     return 0;
301   SourceManager &SM = CGM.getContext().getSourceManager();
302   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
303   return PLoc.isValid()? PLoc.getLine() : 0;
304 }
305 
306 /// getColumnNumber - Get column number for the location.
307 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
308   // We may not want column information at all.
309   if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
310     return 0;
311 
312   // If the location is invalid then use the current column.
313   if (Loc.isInvalid() && CurLoc.isInvalid())
314     return 0;
315   SourceManager &SM = CGM.getContext().getSourceManager();
316   PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
317   return PLoc.isValid()? PLoc.getColumn() : 0;
318 }
319 
320 StringRef CGDebugInfo::getCurrentDirname() {
321   if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
322     return CGM.getCodeGenOpts().DebugCompilationDir;
323 
324   if (!CWDName.empty())
325     return CWDName;
326   SmallString<256> CWD;
327   llvm::sys::fs::current_path(CWD);
328   return CWDName = internString(CWD);
329 }
330 
331 /// CreateCompileUnit - Create new compile unit.
332 void CGDebugInfo::CreateCompileUnit() {
333 
334   // Get absolute path name.
335   SourceManager &SM = CGM.getContext().getSourceManager();
336   std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
337   if (MainFileName.empty())
338     MainFileName = "<unknown>";
339 
340   // The main file name provided via the "-main-file-name" option contains just
341   // the file name itself with no path information. This file name may have had
342   // a relative path, so we look into the actual file entry for the main
343   // file to determine the real absolute path for the file.
344   std::string MainFileDir;
345   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
346     MainFileDir = MainFile->getDir()->getName();
347     if (MainFileDir != ".") {
348       llvm::SmallString<1024> MainFileDirSS(MainFileDir);
349       llvm::sys::path::append(MainFileDirSS, MainFileName);
350       MainFileName = MainFileDirSS.str();
351     }
352   }
353 
354   // Save filename string.
355   StringRef Filename = internString(MainFileName);
356 
357   // Save split dwarf file string.
358   std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
359   StringRef SplitDwarfFilename = internString(SplitDwarfFile);
360 
361   unsigned LangTag;
362   const LangOptions &LO = CGM.getLangOpts();
363   if (LO.CPlusPlus) {
364     if (LO.ObjC1)
365       LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
366     else
367       LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
368   } else if (LO.ObjC1) {
369     LangTag = llvm::dwarf::DW_LANG_ObjC;
370   } else if (LO.C99) {
371     LangTag = llvm::dwarf::DW_LANG_C99;
372   } else {
373     LangTag = llvm::dwarf::DW_LANG_C89;
374   }
375 
376   std::string Producer = getClangFullVersion();
377 
378   // Figure out which version of the ObjC runtime we have.
379   unsigned RuntimeVers = 0;
380   if (LO.ObjC1)
381     RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
382 
383   // Create new compile unit.
384   // FIXME - Eliminate TheCU.
385   TheCU = DBuilder.createCompileUnit(
386       LangTag, Filename, getCurrentDirname(), Producer, LO.Optimize,
387       CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers, SplitDwarfFilename,
388       DebugKind == CodeGenOptions::DebugLineTablesOnly
389           ? llvm::DIBuilder::LineTablesOnly
390           : llvm::DIBuilder::FullDebug);
391 }
392 
393 /// CreateType - Get the Basic type from the cache or create a new
394 /// one if necessary.
395 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
396   unsigned Encoding = 0;
397   StringRef BTName;
398   switch (BT->getKind()) {
399 #define BUILTIN_TYPE(Id, SingletonId)
400 #define PLACEHOLDER_TYPE(Id, SingletonId) \
401   case BuiltinType::Id:
402 #include "clang/AST/BuiltinTypes.def"
403   case BuiltinType::Dependent:
404     llvm_unreachable("Unexpected builtin type");
405   case BuiltinType::NullPtr:
406     return DBuilder.createNullPtrType();
407   case BuiltinType::Void:
408     return llvm::DIType();
409   case BuiltinType::ObjCClass:
410     if (ClassTy)
411       return ClassTy;
412     ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
413                                          "objc_class", TheCU,
414                                          getOrCreateMainFile(), 0);
415     return ClassTy;
416   case BuiltinType::ObjCId: {
417     // typedef struct objc_class *Class;
418     // typedef struct objc_object {
419     //  Class isa;
420     // } *id;
421 
422     if (ObjTy)
423       return ObjTy;
424 
425     if (!ClassTy)
426       ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
427                                            "objc_class", TheCU,
428                                            getOrCreateMainFile(), 0);
429 
430     unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
431 
432     llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
433 
434     ObjTy =
435         DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
436                                   0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
437 
438     ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
439         ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
440     return ObjTy;
441   }
442   case BuiltinType::ObjCSel: {
443     if (SelTy)
444       return SelTy;
445     SelTy =
446       DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
447                                  "objc_selector", TheCU, getOrCreateMainFile(),
448                                  0);
449     return SelTy;
450   }
451 
452   case BuiltinType::OCLImage1d:
453     return getOrCreateStructPtrType("opencl_image1d_t",
454                                     OCLImage1dDITy);
455   case BuiltinType::OCLImage1dArray:
456     return getOrCreateStructPtrType("opencl_image1d_array_t",
457                                     OCLImage1dArrayDITy);
458   case BuiltinType::OCLImage1dBuffer:
459     return getOrCreateStructPtrType("opencl_image1d_buffer_t",
460                                     OCLImage1dBufferDITy);
461   case BuiltinType::OCLImage2d:
462     return getOrCreateStructPtrType("opencl_image2d_t",
463                                     OCLImage2dDITy);
464   case BuiltinType::OCLImage2dArray:
465     return getOrCreateStructPtrType("opencl_image2d_array_t",
466                                     OCLImage2dArrayDITy);
467   case BuiltinType::OCLImage3d:
468     return getOrCreateStructPtrType("opencl_image3d_t",
469                                     OCLImage3dDITy);
470   case BuiltinType::OCLSampler:
471     return DBuilder.createBasicType("opencl_sampler_t",
472                                     CGM.getContext().getTypeSize(BT),
473                                     CGM.getContext().getTypeAlign(BT),
474                                     llvm::dwarf::DW_ATE_unsigned);
475   case BuiltinType::OCLEvent:
476     return getOrCreateStructPtrType("opencl_event_t",
477                                     OCLEventDITy);
478 
479   case BuiltinType::UChar:
480   case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
481   case BuiltinType::Char_S:
482   case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
483   case BuiltinType::Char16:
484   case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
485   case BuiltinType::UShort:
486   case BuiltinType::UInt:
487   case BuiltinType::UInt128:
488   case BuiltinType::ULong:
489   case BuiltinType::WChar_U:
490   case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
491   case BuiltinType::Short:
492   case BuiltinType::Int:
493   case BuiltinType::Int128:
494   case BuiltinType::Long:
495   case BuiltinType::WChar_S:
496   case BuiltinType::LongLong:  Encoding = llvm::dwarf::DW_ATE_signed; break;
497   case BuiltinType::Bool:      Encoding = llvm::dwarf::DW_ATE_boolean; break;
498   case BuiltinType::Half:
499   case BuiltinType::Float:
500   case BuiltinType::LongDouble:
501   case BuiltinType::Double:    Encoding = llvm::dwarf::DW_ATE_float; break;
502   }
503 
504   switch (BT->getKind()) {
505   case BuiltinType::Long:      BTName = "long int"; break;
506   case BuiltinType::LongLong:  BTName = "long long int"; break;
507   case BuiltinType::ULong:     BTName = "long unsigned int"; break;
508   case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
509   default:
510     BTName = BT->getName(CGM.getLangOpts());
511     break;
512   }
513   // Bit size, align and offset of the type.
514   uint64_t Size = CGM.getContext().getTypeSize(BT);
515   uint64_t Align = CGM.getContext().getTypeAlign(BT);
516   llvm::DIType DbgTy =
517     DBuilder.createBasicType(BTName, Size, Align, Encoding);
518   return DbgTy;
519 }
520 
521 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
522   // Bit size, align and offset of the type.
523   unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
524   if (Ty->isComplexIntegerType())
525     Encoding = llvm::dwarf::DW_ATE_lo_user;
526 
527   uint64_t Size = CGM.getContext().getTypeSize(Ty);
528   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
529   llvm::DIType DbgTy =
530     DBuilder.createBasicType("complex", Size, Align, Encoding);
531 
532   return DbgTy;
533 }
534 
535 /// CreateCVRType - Get the qualified type from the cache or create
536 /// a new one if necessary.
537 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
538   QualifierCollector Qc;
539   const Type *T = Qc.strip(Ty);
540 
541   // Ignore these qualifiers for now.
542   Qc.removeObjCGCAttr();
543   Qc.removeAddressSpace();
544   Qc.removeObjCLifetime();
545 
546   // We will create one Derived type for one qualifier and recurse to handle any
547   // additional ones.
548   unsigned Tag;
549   if (Qc.hasConst()) {
550     Tag = llvm::dwarf::DW_TAG_const_type;
551     Qc.removeConst();
552   } else if (Qc.hasVolatile()) {
553     Tag = llvm::dwarf::DW_TAG_volatile_type;
554     Qc.removeVolatile();
555   } else if (Qc.hasRestrict()) {
556     Tag = llvm::dwarf::DW_TAG_restrict_type;
557     Qc.removeRestrict();
558   } else {
559     assert(Qc.empty() && "Unknown type qualifier for debug info");
560     return getOrCreateType(QualType(T, 0), Unit);
561   }
562 
563   llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
564 
565   // No need to fill in the Name, Line, Size, Alignment, Offset in case of
566   // CVR derived types.
567   llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
568 
569   return DbgTy;
570 }
571 
572 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
573                                      llvm::DIFile Unit) {
574 
575   // The frontend treats 'id' as a typedef to an ObjCObjectType,
576   // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
577   // debug info, we want to emit 'id' in both cases.
578   if (Ty->isObjCQualifiedIdType())
579       return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
580 
581   llvm::DIType DbgTy =
582     CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
583                           Ty->getPointeeType(), Unit);
584   return DbgTy;
585 }
586 
587 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
588                                      llvm::DIFile Unit) {
589   return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
590                                Ty->getPointeeType(), Unit);
591 }
592 
593 /// In C++ mode, types have linkage, so we can rely on the ODR and
594 /// on their mangled names, if they're external.
595 static SmallString<256>
596 getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
597                      llvm::DICompileUnit TheCU) {
598   SmallString<256> FullName;
599   // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
600   // For now, only apply ODR with C++.
601   const TagDecl *TD = Ty->getDecl();
602   if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
603       !TD->isExternallyVisible())
604     return FullName;
605   // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
606   if (CGM.getTarget().getCXXABI().isMicrosoft())
607     return FullName;
608 
609   // TODO: This is using the RTTI name. Is there a better way to get
610   // a unique string for a type?
611   llvm::raw_svector_ostream Out(FullName);
612   CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
613   Out.flush();
614   return FullName;
615 }
616 
617 // Creates a forward declaration for a RecordDecl in the given context.
618 llvm::DICompositeType
619 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
620                                       llvm::DIDescriptor Ctx) {
621   const RecordDecl *RD = Ty->getDecl();
622   if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
623     return llvm::DICompositeType(T);
624   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
625   unsigned Line = getLineNumber(RD->getLocation());
626   StringRef RDName = getClassName(RD);
627 
628   unsigned Tag = 0;
629   if (RD->isStruct() || RD->isInterface())
630     Tag = llvm::dwarf::DW_TAG_structure_type;
631   else if (RD->isUnion())
632     Tag = llvm::dwarf::DW_TAG_union_type;
633   else {
634     assert(RD->isClass());
635     Tag = llvm::dwarf::DW_TAG_class_type;
636   }
637 
638   // Create the type.
639   SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
640   return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0,
641                                     FullName);
642 }
643 
644 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
645                                                 const Type *Ty,
646                                                 QualType PointeeTy,
647                                                 llvm::DIFile Unit) {
648   if (Tag == llvm::dwarf::DW_TAG_reference_type ||
649       Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
650     return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
651 
652   // Bit size, align and offset of the type.
653   // Size is always the size of a pointer. We can't use getTypeSize here
654   // because that does not return the correct value for references.
655   unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
656   uint64_t Size = CGM.getTarget().getPointerWidth(AS);
657   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
658 
659   return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
660                                     Align);
661 }
662 
663 llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
664                                                    llvm::DIType &Cache) {
665   if (Cache)
666     return Cache;
667   Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
668                                      TheCU, getOrCreateMainFile(), 0);
669   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
670   Cache = DBuilder.createPointerType(Cache, Size);
671   return Cache;
672 }
673 
674 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
675                                      llvm::DIFile Unit) {
676   if (BlockLiteralGeneric)
677     return BlockLiteralGeneric;
678 
679   SmallVector<llvm::Value *, 8> EltTys;
680   llvm::DIType FieldTy;
681   QualType FType;
682   uint64_t FieldSize, FieldOffset;
683   unsigned FieldAlign;
684   llvm::DIArray Elements;
685   llvm::DIType EltTy, DescTy;
686 
687   FieldOffset = 0;
688   FType = CGM.getContext().UnsignedLongTy;
689   EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
690   EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
691 
692   Elements = DBuilder.getOrCreateArray(EltTys);
693   EltTys.clear();
694 
695   unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
696   unsigned LineNo = getLineNumber(CurLoc);
697 
698   EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
699                                     Unit, LineNo, FieldOffset, 0,
700                                     Flags, llvm::DIType(), Elements);
701 
702   // Bit size, align and offset of the type.
703   uint64_t Size = CGM.getContext().getTypeSize(Ty);
704 
705   DescTy = DBuilder.createPointerType(EltTy, Size);
706 
707   FieldOffset = 0;
708   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
709   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
710   FType = CGM.getContext().IntTy;
711   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
712   EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
713   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
714   EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
715 
716   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
717   FieldTy = DescTy;
718   FieldSize = CGM.getContext().getTypeSize(Ty);
719   FieldAlign = CGM.getContext().getTypeAlign(Ty);
720   FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
721                                       LineNo, FieldSize, FieldAlign,
722                                       FieldOffset, 0, FieldTy);
723   EltTys.push_back(FieldTy);
724 
725   FieldOffset += FieldSize;
726   Elements = DBuilder.getOrCreateArray(EltTys);
727 
728   EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
729                                     Unit, LineNo, FieldOffset, 0,
730                                     Flags, llvm::DIType(), Elements);
731 
732   BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
733   return BlockLiteralGeneric;
734 }
735 
736 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
737   // Typedefs are derived from some other type.  If we have a typedef of a
738   // typedef, make sure to emit the whole chain.
739   llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
740   if (!Src)
741     return llvm::DIType();
742   // We don't set size information, but do specify where the typedef was
743   // declared.
744   SourceLocation Loc = Ty->getDecl()->getLocation();
745   llvm::DIFile File = getOrCreateFile(Loc);
746   unsigned Line = getLineNumber(Loc);
747   const TypedefNameDecl *TyDecl = Ty->getDecl();
748 
749   llvm::DIDescriptor TypedefContext =
750     getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
751 
752   return
753     DBuilder.createTypedef(Src, TyDecl->getName(), File, Line, TypedefContext);
754 }
755 
756 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
757                                      llvm::DIFile Unit) {
758   SmallVector<llvm::Value *, 16> EltTys;
759 
760   // Add the result type at least.
761   EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
762 
763   // Set up remainder of arguments if there is a prototype.
764   // otherwise emit it as a variadic function.
765   if (isa<FunctionNoProtoType>(Ty))
766     EltTys.push_back(DBuilder.createUnspecifiedParameter());
767   else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
768     for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
769       EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
770     if (FPT->isVariadic())
771       EltTys.push_back(DBuilder.createUnspecifiedParameter());
772   }
773 
774   llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
775   return DBuilder.createSubroutineType(Unit, EltTypeArray);
776 }
777 
778 
779 llvm::DIType CGDebugInfo::createFieldType(StringRef name,
780                                           QualType type,
781                                           uint64_t sizeInBitsOverride,
782                                           SourceLocation loc,
783                                           AccessSpecifier AS,
784                                           uint64_t offsetInBits,
785                                           llvm::DIFile tunit,
786                                           llvm::DIScope scope) {
787   llvm::DIType debugType = getOrCreateType(type, tunit);
788 
789   // Get the location for the field.
790   llvm::DIFile file = getOrCreateFile(loc);
791   unsigned line = getLineNumber(loc);
792 
793   uint64_t sizeInBits = 0;
794   unsigned alignInBits = 0;
795   if (!type->isIncompleteArrayType()) {
796     std::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
797 
798     if (sizeInBitsOverride)
799       sizeInBits = sizeInBitsOverride;
800   }
801 
802   unsigned flags = 0;
803   if (AS == clang::AS_private)
804     flags |= llvm::DIDescriptor::FlagPrivate;
805   else if (AS == clang::AS_protected)
806     flags |= llvm::DIDescriptor::FlagProtected;
807 
808   return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
809                                    alignInBits, offsetInBits, flags, debugType);
810 }
811 
812 /// CollectRecordLambdaFields - Helper for CollectRecordFields.
813 void CGDebugInfo::
814 CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
815                           SmallVectorImpl<llvm::Value *> &elements,
816                           llvm::DIType RecordTy) {
817   // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
818   // has the name and the location of the variable so we should iterate over
819   // both concurrently.
820   const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
821   RecordDecl::field_iterator Field = CXXDecl->field_begin();
822   unsigned fieldno = 0;
823   for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
824          E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
825     const LambdaExpr::Capture C = *I;
826     if (C.capturesVariable()) {
827       VarDecl *V = C.getCapturedVar();
828       llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
829       StringRef VName = V->getName();
830       uint64_t SizeInBitsOverride = 0;
831       if (Field->isBitField()) {
832         SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
833         assert(SizeInBitsOverride && "found named 0-width bitfield");
834       }
835       llvm::DIType fieldType
836         = createFieldType(VName, Field->getType(), SizeInBitsOverride,
837                           C.getLocation(), Field->getAccess(),
838                           layout.getFieldOffset(fieldno), VUnit, RecordTy);
839       elements.push_back(fieldType);
840     } else {
841       // TODO: Need to handle 'this' in some way by probably renaming the
842       // this of the lambda class and having a field member of 'this' or
843       // by using AT_object_pointer for the function and having that be
844       // used as 'this' for semantic references.
845       assert(C.capturesThis() && "Field that isn't captured and isn't this?");
846       FieldDecl *f = *Field;
847       llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
848       QualType type = f->getType();
849       llvm::DIType fieldType
850         = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
851                           layout.getFieldOffset(fieldno), VUnit, RecordTy);
852 
853       elements.push_back(fieldType);
854     }
855   }
856 }
857 
858 /// Helper for CollectRecordFields.
859 llvm::DIDerivedType
860 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
861                                      llvm::DIType RecordTy) {
862   // Create the descriptor for the static variable, with or without
863   // constant initializers.
864   llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
865   llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
866 
867   unsigned LineNumber = getLineNumber(Var->getLocation());
868   StringRef VName = Var->getName();
869   llvm::Constant *C = NULL;
870   if (Var->getInit()) {
871     const APValue *Value = Var->evaluateValue();
872     if (Value) {
873       if (Value->isInt())
874         C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
875       if (Value->isFloat())
876         C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
877     }
878   }
879 
880   unsigned Flags = 0;
881   AccessSpecifier Access = Var->getAccess();
882   if (Access == clang::AS_private)
883     Flags |= llvm::DIDescriptor::FlagPrivate;
884   else if (Access == clang::AS_protected)
885     Flags |= llvm::DIDescriptor::FlagProtected;
886 
887   llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
888       RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
889   StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
890   return GV;
891 }
892 
893 /// CollectRecordNormalField - Helper for CollectRecordFields.
894 void CGDebugInfo::
895 CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
896                          llvm::DIFile tunit,
897                          SmallVectorImpl<llvm::Value *> &elements,
898                          llvm::DIType RecordTy) {
899   StringRef name = field->getName();
900   QualType type = field->getType();
901 
902   // Ignore unnamed fields unless they're anonymous structs/unions.
903   if (name.empty() && !type->isRecordType())
904     return;
905 
906   uint64_t SizeInBitsOverride = 0;
907   if (field->isBitField()) {
908     SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
909     assert(SizeInBitsOverride && "found named 0-width bitfield");
910   }
911 
912   llvm::DIType fieldType
913     = createFieldType(name, type, SizeInBitsOverride,
914                       field->getLocation(), field->getAccess(),
915                       OffsetInBits, tunit, RecordTy);
916 
917   elements.push_back(fieldType);
918 }
919 
920 /// CollectRecordFields - A helper function to collect debug info for
921 /// record fields. This is used while creating debug info entry for a Record.
922 void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
923                                       llvm::DIFile tunit,
924                                       SmallVectorImpl<llvm::Value *> &elements,
925                                       llvm::DICompositeType RecordTy) {
926   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
927 
928   if (CXXDecl && CXXDecl->isLambda())
929     CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
930   else {
931     const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
932 
933     // Field number for non-static fields.
934     unsigned fieldNo = 0;
935 
936     // Static and non-static members should appear in the same order as
937     // the corresponding declarations in the source program.
938     for (const auto *I : record->decls())
939       if (const auto *V = dyn_cast<VarDecl>(I)) {
940         // Reuse the existing static member declaration if one exists
941         llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
942             StaticDataMemberCache.find(V->getCanonicalDecl());
943         if (MI != StaticDataMemberCache.end()) {
944           assert(MI->second &&
945                  "Static data member declaration should still exist");
946           elements.push_back(
947               llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
948         } else
949           elements.push_back(CreateRecordStaticField(V, RecordTy));
950       } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
951         CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
952                                  tunit, elements, RecordTy);
953 
954         // Bump field number for next field.
955         ++fieldNo;
956       }
957   }
958 }
959 
960 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
961 /// function type is not updated to include implicit "this" pointer. Use this
962 /// routine to get a method type which includes "this" pointer.
963 llvm::DICompositeType
964 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
965                                    llvm::DIFile Unit) {
966   const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
967   if (Method->isStatic())
968     return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
969   return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
970                                        Func, Unit);
971 }
972 
973 llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
974     QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
975   // Add "this" pointer.
976   llvm::DIArray Args = llvm::DICompositeType(
977       getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
978   assert (Args.getNumElements() && "Invalid number of arguments!");
979 
980   SmallVector<llvm::Value *, 16> Elts;
981 
982   // First element is always return type. For 'void' functions it is NULL.
983   Elts.push_back(Args.getElement(0));
984 
985   // "this" pointer is always first argument.
986   const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
987   if (isa<ClassTemplateSpecializationDecl>(RD)) {
988     // Create pointer type directly in this case.
989     const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
990     QualType PointeeTy = ThisPtrTy->getPointeeType();
991     unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
992     uint64_t Size = CGM.getTarget().getPointerWidth(AS);
993     uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
994     llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
995     llvm::DIType ThisPtrType =
996       DBuilder.createPointerType(PointeeType, Size, Align);
997     TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
998     // TODO: This and the artificial type below are misleading, the
999     // types aren't artificial the argument is, but the current
1000     // metadata doesn't represent that.
1001     ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1002     Elts.push_back(ThisPtrType);
1003   } else {
1004     llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1005     TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1006     ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1007     Elts.push_back(ThisPtrType);
1008   }
1009 
1010   // Copy rest of the arguments.
1011   for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1012     Elts.push_back(Args.getElement(i));
1013 
1014   llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1015 
1016   unsigned Flags = 0;
1017   if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1018     Flags |= llvm::DIDescriptor::FlagLValueReference;
1019   if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1020     Flags |= llvm::DIDescriptor::FlagRValueReference;
1021 
1022   return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
1023 }
1024 
1025 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1026 /// inside a function.
1027 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1028   if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1029     return isFunctionLocalClass(NRD);
1030   if (isa<FunctionDecl>(RD->getDeclContext()))
1031     return true;
1032   return false;
1033 }
1034 
1035 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1036 /// a single member function GlobalDecl.
1037 llvm::DISubprogram
1038 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1039                                      llvm::DIFile Unit,
1040                                      llvm::DIType RecordTy) {
1041   bool IsCtorOrDtor =
1042     isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1043 
1044   StringRef MethodName = getFunctionName(Method);
1045   llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
1046 
1047   // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1048   // make sense to give a single ctor/dtor a linkage name.
1049   StringRef MethodLinkageName;
1050   if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1051     MethodLinkageName = CGM.getMangledName(Method);
1052 
1053   // Get the location for the method.
1054   llvm::DIFile MethodDefUnit;
1055   unsigned MethodLine = 0;
1056   if (!Method->isImplicit()) {
1057     MethodDefUnit = getOrCreateFile(Method->getLocation());
1058     MethodLine = getLineNumber(Method->getLocation());
1059   }
1060 
1061   // Collect virtual method info.
1062   llvm::DIType ContainingType;
1063   unsigned Virtuality = 0;
1064   unsigned VIndex = 0;
1065 
1066   if (Method->isVirtual()) {
1067     if (Method->isPure())
1068       Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1069     else
1070       Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1071 
1072     // It doesn't make sense to give a virtual destructor a vtable index,
1073     // since a single destructor has two entries in the vtable.
1074     // FIXME: Add proper support for debug info for virtual calls in
1075     // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1076     // lookup if we have multiple or virtual inheritance.
1077     if (!isa<CXXDestructorDecl>(Method) &&
1078         !CGM.getTarget().getCXXABI().isMicrosoft())
1079       VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1080     ContainingType = RecordTy;
1081   }
1082 
1083   unsigned Flags = 0;
1084   if (Method->isImplicit())
1085     Flags |= llvm::DIDescriptor::FlagArtificial;
1086   AccessSpecifier Access = Method->getAccess();
1087   if (Access == clang::AS_private)
1088     Flags |= llvm::DIDescriptor::FlagPrivate;
1089   else if (Access == clang::AS_protected)
1090     Flags |= llvm::DIDescriptor::FlagProtected;
1091   if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1092     if (CXXC->isExplicit())
1093       Flags |= llvm::DIDescriptor::FlagExplicit;
1094   } else if (const CXXConversionDecl *CXXC =
1095              dyn_cast<CXXConversionDecl>(Method)) {
1096     if (CXXC->isExplicit())
1097       Flags |= llvm::DIDescriptor::FlagExplicit;
1098   }
1099   if (Method->hasPrototype())
1100     Flags |= llvm::DIDescriptor::FlagPrototyped;
1101   if (Method->getRefQualifier() == RQ_LValue)
1102     Flags |= llvm::DIDescriptor::FlagLValueReference;
1103   if (Method->getRefQualifier() == RQ_RValue)
1104     Flags |= llvm::DIDescriptor::FlagRValueReference;
1105 
1106   llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1107   llvm::DISubprogram SP =
1108     DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
1109                           MethodDefUnit, MethodLine,
1110                           MethodTy, /*isLocalToUnit=*/false,
1111                           /* isDefinition=*/ false,
1112                           Virtuality, VIndex, ContainingType,
1113                           Flags, CGM.getLangOpts().Optimize, NULL,
1114                           TParamsArray);
1115 
1116   SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1117 
1118   return SP;
1119 }
1120 
1121 /// CollectCXXMemberFunctions - A helper function to collect debug info for
1122 /// C++ member functions. This is used while creating debug info entry for
1123 /// a Record.
1124 void CGDebugInfo::
1125 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1126                           SmallVectorImpl<llvm::Value *> &EltTys,
1127                           llvm::DIType RecordTy) {
1128 
1129   // Since we want more than just the individual member decls if we
1130   // have templated functions iterate over every declaration to gather
1131   // the functions.
1132   for(const auto *I : RD->decls()) {
1133     if (const auto *Method = dyn_cast<CXXMethodDecl>(I)) {
1134       // Reuse the existing member function declaration if it exists.
1135       // It may be associated with the declaration of the type & should be
1136       // reused as we're building the definition.
1137       //
1138       // This situation can arise in the vtable-based debug info reduction where
1139       // implicit members are emitted in a non-vtable TU.
1140       llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1141           SPCache.find(Method->getCanonicalDecl());
1142       if (MI == SPCache.end()) {
1143         // If the member is implicit, lazily create it when we see the
1144         // definition, not before. (an ODR-used implicit default ctor that's
1145         // never actually code generated should not produce debug info)
1146         if (!Method->isImplicit())
1147           EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1148       } else
1149         EltTys.push_back(MI->second);
1150     } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(I)) {
1151       // Add any template specializations that have already been seen. Like
1152       // implicit member functions, these may have been added to a declaration
1153       // in the case of vtable-based debug info reduction.
1154       for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1155                                                SE = FTD->spec_end();
1156            SI != SE; ++SI) {
1157         llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1158             SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl());
1159         if (MI != SPCache.end())
1160           EltTys.push_back(MI->second);
1161       }
1162     }
1163   }
1164 }
1165 
1166 /// CollectCXXBases - A helper function to collect debug info for
1167 /// C++ base classes. This is used while creating debug info entry for
1168 /// a Record.
1169 void CGDebugInfo::
1170 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1171                 SmallVectorImpl<llvm::Value *> &EltTys,
1172                 llvm::DIType RecordTy) {
1173 
1174   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1175   for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1176          BE = RD->bases_end(); BI != BE; ++BI) {
1177     unsigned BFlags = 0;
1178     uint64_t BaseOffset;
1179 
1180     const CXXRecordDecl *Base =
1181       cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1182 
1183     if (BI->isVirtual()) {
1184       // virtual base offset offset is -ve. The code generator emits dwarf
1185       // expression where it expects +ve number.
1186       BaseOffset =
1187         0 - CGM.getItaniumVTableContext()
1188                .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1189       BFlags = llvm::DIDescriptor::FlagVirtual;
1190     } else
1191       BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1192     // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1193     // BI->isVirtual() and bits when not.
1194 
1195     AccessSpecifier Access = BI->getAccessSpecifier();
1196     if (Access == clang::AS_private)
1197       BFlags |= llvm::DIDescriptor::FlagPrivate;
1198     else if (Access == clang::AS_protected)
1199       BFlags |= llvm::DIDescriptor::FlagProtected;
1200 
1201     llvm::DIType DTy =
1202       DBuilder.createInheritance(RecordTy,
1203                                  getOrCreateType(BI->getType(), Unit),
1204                                  BaseOffset, BFlags);
1205     EltTys.push_back(DTy);
1206   }
1207 }
1208 
1209 /// CollectTemplateParams - A helper function to collect template parameters.
1210 llvm::DIArray CGDebugInfo::
1211 CollectTemplateParams(const TemplateParameterList *TPList,
1212                       ArrayRef<TemplateArgument> TAList,
1213                       llvm::DIFile Unit) {
1214   SmallVector<llvm::Value *, 16> TemplateParams;
1215   for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1216     const TemplateArgument &TA = TAList[i];
1217     StringRef Name;
1218     if (TPList)
1219       Name = TPList->getParam(i)->getName();
1220     switch (TA.getKind()) {
1221     case TemplateArgument::Type: {
1222       llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1223       llvm::DITemplateTypeParameter TTP =
1224           DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
1225       TemplateParams.push_back(TTP);
1226     } break;
1227     case TemplateArgument::Integral: {
1228       llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1229       llvm::DITemplateValueParameter TVP =
1230           DBuilder.createTemplateValueParameter(
1231               TheCU, Name, TTy,
1232               llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1233       TemplateParams.push_back(TVP);
1234     } break;
1235     case TemplateArgument::Declaration: {
1236       const ValueDecl *D = TA.getAsDecl();
1237       bool InstanceMember = D->isCXXInstanceMember();
1238       QualType T = InstanceMember
1239                        ? CGM.getContext().getMemberPointerType(
1240                              D->getType(), cast<RecordDecl>(D->getDeclContext())
1241                                                ->getTypeForDecl())
1242                        : CGM.getContext().getPointerType(D->getType());
1243       llvm::DIType TTy = getOrCreateType(T, Unit);
1244       llvm::Value *V = 0;
1245       // Variable pointer template parameters have a value that is the address
1246       // of the variable.
1247       if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1248         V = CGM.GetAddrOfGlobalVar(VD);
1249       // Member function pointers have special support for building them, though
1250       // this is currently unsupported in LLVM CodeGen.
1251       if (InstanceMember) {
1252         if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1253           V = CGM.getCXXABI().EmitMemberPointer(method);
1254       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1255         V = CGM.GetAddrOfFunction(FD);
1256       // Member data pointers have special handling too to compute the fixed
1257       // offset within the object.
1258       if (isa<FieldDecl>(D)) {
1259         // These five lines (& possibly the above member function pointer
1260         // handling) might be able to be refactored to use similar code in
1261         // CodeGenModule::getMemberPointerConstant
1262         uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1263         CharUnits chars =
1264             CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1265         V = CGM.getCXXABI().EmitMemberDataPointer(
1266             cast<MemberPointerType>(T.getTypePtr()), chars);
1267       }
1268       llvm::DITemplateValueParameter TVP =
1269           DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1270                                                 V->stripPointerCasts());
1271       TemplateParams.push_back(TVP);
1272     } break;
1273     case TemplateArgument::NullPtr: {
1274       QualType T = TA.getNullPtrType();
1275       llvm::DIType TTy = getOrCreateType(T, Unit);
1276       llvm::Value *V = 0;
1277       // Special case member data pointer null values since they're actually -1
1278       // instead of zero.
1279       if (const MemberPointerType *MPT =
1280               dyn_cast<MemberPointerType>(T.getTypePtr()))
1281         // But treat member function pointers as simple zero integers because
1282         // it's easier than having a special case in LLVM's CodeGen. If LLVM
1283         // CodeGen grows handling for values of non-null member function
1284         // pointers then perhaps we could remove this special case and rely on
1285         // EmitNullMemberPointer for member function pointers.
1286         if (MPT->isMemberDataPointer())
1287           V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1288       if (!V)
1289         V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1290       llvm::DITemplateValueParameter TVP =
1291           DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
1292       TemplateParams.push_back(TVP);
1293     } break;
1294     case TemplateArgument::Template: {
1295       llvm::DITemplateValueParameter TVP =
1296           DBuilder.createTemplateTemplateParameter(
1297               TheCU, Name, llvm::DIType(),
1298               TA.getAsTemplate().getAsTemplateDecl()
1299                   ->getQualifiedNameAsString());
1300       TemplateParams.push_back(TVP);
1301     } break;
1302     case TemplateArgument::Pack: {
1303       llvm::DITemplateValueParameter TVP =
1304           DBuilder.createTemplateParameterPack(
1305               TheCU, Name, llvm::DIType(),
1306               CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1307       TemplateParams.push_back(TVP);
1308     } break;
1309     case TemplateArgument::Expression: {
1310       const Expr *E = TA.getAsExpr();
1311       QualType T = E->getType();
1312       llvm::Value *V = CGM.EmitConstantExpr(E, T);
1313       assert(V && "Expression in template argument isn't constant");
1314       llvm::DIType TTy = getOrCreateType(T, Unit);
1315       llvm::DITemplateValueParameter TVP =
1316           DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1317                                                 V->stripPointerCasts());
1318       TemplateParams.push_back(TVP);
1319     } break;
1320     // And the following should never occur:
1321     case TemplateArgument::TemplateExpansion:
1322     case TemplateArgument::Null:
1323       llvm_unreachable(
1324           "These argument types shouldn't exist in concrete types");
1325     }
1326   }
1327   return DBuilder.getOrCreateArray(TemplateParams);
1328 }
1329 
1330 /// CollectFunctionTemplateParams - A helper function to collect debug
1331 /// info for function template parameters.
1332 llvm::DIArray CGDebugInfo::
1333 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1334   if (FD->getTemplatedKind() ==
1335       FunctionDecl::TK_FunctionTemplateSpecialization) {
1336     const TemplateParameterList *TList =
1337       FD->getTemplateSpecializationInfo()->getTemplate()
1338       ->getTemplateParameters();
1339     return CollectTemplateParams(
1340         TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1341   }
1342   return llvm::DIArray();
1343 }
1344 
1345 /// CollectCXXTemplateParams - A helper function to collect debug info for
1346 /// template parameters.
1347 llvm::DIArray CGDebugInfo::
1348 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1349                          llvm::DIFile Unit) {
1350   llvm::PointerUnion<ClassTemplateDecl *,
1351                      ClassTemplatePartialSpecializationDecl *>
1352     PU = TSpecial->getSpecializedTemplateOrPartial();
1353 
1354   TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1355     PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1356     PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1357   const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1358   return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1359 }
1360 
1361 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1362 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1363   if (VTablePtrType.isValid())
1364     return VTablePtrType;
1365 
1366   ASTContext &Context = CGM.getContext();
1367 
1368   /* Function type */
1369   llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1370   llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1371   llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1372   unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1373   llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1374                                                           "__vtbl_ptr_type");
1375   VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1376   return VTablePtrType;
1377 }
1378 
1379 /// getVTableName - Get vtable name for the given Class.
1380 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1381   // Copy the gdb compatible name on the side and use its reference.
1382   return internString("_vptr$", RD->getNameAsString());
1383 }
1384 
1385 
1386 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1387 /// debug info entry in EltTys vector.
1388 void CGDebugInfo::
1389 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1390                   SmallVectorImpl<llvm::Value *> &EltTys) {
1391   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1392 
1393   // If there is a primary base then it will hold vtable info.
1394   if (RL.getPrimaryBase())
1395     return;
1396 
1397   // If this class is not dynamic then there is not any vtable info to collect.
1398   if (!RD->isDynamicClass())
1399     return;
1400 
1401   unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1402   llvm::DIType VPTR
1403     = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1404                                 0, Size, 0, 0,
1405                                 llvm::DIDescriptor::FlagArtificial,
1406                                 getOrCreateVTablePtrType(Unit));
1407   EltTys.push_back(VPTR);
1408 }
1409 
1410 /// getOrCreateRecordType - Emit record type's standalone debug info.
1411 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1412                                                 SourceLocation Loc) {
1413   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1414   llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1415   return T;
1416 }
1417 
1418 /// getOrCreateInterfaceType - Emit an objective c interface type standalone
1419 /// debug info.
1420 llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
1421                                                    SourceLocation Loc) {
1422   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1423   llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
1424   RetainedTypes.push_back(D.getAsOpaquePtr());
1425   return T;
1426 }
1427 
1428 void CGDebugInfo::completeType(const RecordDecl *RD) {
1429   if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1430       !CGM.getLangOpts().CPlusPlus)
1431     completeRequiredType(RD);
1432 }
1433 
1434 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
1435   if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1436     return;
1437 
1438   if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1439     if (CXXDecl->isDynamicClass())
1440       return;
1441 
1442   QualType Ty = CGM.getContext().getRecordType(RD);
1443   llvm::DIType T = getTypeOrNull(Ty);
1444   if (T && T.isForwardDecl())
1445     completeClassData(RD);
1446 }
1447 
1448 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1449   if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1450     return;
1451   QualType Ty = CGM.getContext().getRecordType(RD);
1452   void* TyPtr = Ty.getAsOpaquePtr();
1453   if (CompletedTypeCache.count(TyPtr))
1454     return;
1455   llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1456   assert(!Res.isForwardDecl());
1457   CompletedTypeCache[TyPtr] = Res;
1458   TypeCache[TyPtr] = Res;
1459 }
1460 
1461 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1462                                         CXXRecordDecl::method_iterator End) {
1463   for (; I != End; ++I)
1464     if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
1465       if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1466           !I->getMemberSpecializationInfo()->isExplicitSpecialization())
1467         return true;
1468   return false;
1469 }
1470 
1471 static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,
1472                                  const RecordDecl *RD,
1473                                  const LangOptions &LangOpts) {
1474   if (DebugKind > CodeGenOptions::LimitedDebugInfo)
1475     return false;
1476 
1477   if (!LangOpts.CPlusPlus)
1478     return false;
1479 
1480   if (!RD->isCompleteDefinitionRequired())
1481     return true;
1482 
1483   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1484 
1485   if (!CXXDecl)
1486     return false;
1487 
1488   if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
1489     return true;
1490 
1491   TemplateSpecializationKind Spec = TSK_Undeclared;
1492   if (const ClassTemplateSpecializationDecl *SD =
1493           dyn_cast<ClassTemplateSpecializationDecl>(RD))
1494     Spec = SD->getSpecializationKind();
1495 
1496   if (Spec == TSK_ExplicitInstantiationDeclaration &&
1497       hasExplicitMemberDefinition(CXXDecl->method_begin(),
1498                                   CXXDecl->method_end()))
1499     return true;
1500 
1501   return false;
1502 }
1503 
1504 /// CreateType - get structure or union type.
1505 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1506   RecordDecl *RD = Ty->getDecl();
1507   llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
1508   if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) {
1509     if (!T)
1510       T = getOrCreateRecordFwdDecl(
1511           Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
1512     return T;
1513   }
1514 
1515   return CreateTypeDefinition(Ty);
1516 }
1517 
1518 llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1519   RecordDecl *RD = Ty->getDecl();
1520 
1521   // Get overall information about the record type for the debug info.
1522   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1523 
1524   // Records and classes and unions can all be recursive.  To handle them, we
1525   // first generate a debug descriptor for the struct as a forward declaration.
1526   // Then (if it is a definition) we go through and get debug info for all of
1527   // its members.  Finally, we create a descriptor for the complete type (which
1528   // may refer to the forward decl if the struct is recursive) and replace all
1529   // uses of the forward declaration with the final definition.
1530 
1531   llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
1532   assert(FwdDecl.isCompositeType() &&
1533          "The debug type of a RecordType should be a llvm::DICompositeType");
1534 
1535   if (FwdDecl.isForwardDecl())
1536     return FwdDecl;
1537 
1538   if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1539     CollectContainingType(CXXDecl, FwdDecl);
1540 
1541   // Push the struct on region stack.
1542   LexicalBlockStack.push_back(&*FwdDecl);
1543   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1544 
1545   // Add this to the completed-type cache while we're completing it recursively.
1546   CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1547 
1548   // Convert all the elements.
1549   SmallVector<llvm::Value *, 16> EltTys;
1550   // what about nested types?
1551 
1552   // Note: The split of CXXDecl information here is intentional, the
1553   // gdb tests will depend on a certain ordering at printout. The debug
1554   // information offsets are still correct if we merge them all together
1555   // though.
1556   const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1557   if (CXXDecl) {
1558     CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1559     CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1560   }
1561 
1562   // Collect data fields (including static variables and any initializers).
1563   CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1564   if (CXXDecl)
1565     CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1566 
1567   LexicalBlockStack.pop_back();
1568   RegionMap.erase(Ty->getDecl());
1569 
1570   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1571   FwdDecl.setTypeArray(Elements);
1572 
1573   RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1574   return FwdDecl;
1575 }
1576 
1577 /// CreateType - get objective-c object type.
1578 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1579                                      llvm::DIFile Unit) {
1580   // Ignore protocols.
1581   return getOrCreateType(Ty->getBaseType(), Unit);
1582 }
1583 
1584 
1585 /// \return true if Getter has the default name for the property PD.
1586 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1587                                  const ObjCMethodDecl *Getter) {
1588   assert(PD);
1589   if (!Getter)
1590     return true;
1591 
1592   assert(Getter->getDeclName().isObjCZeroArgSelector());
1593   return PD->getName() ==
1594     Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1595 }
1596 
1597 /// \return true if Setter has the default name for the property PD.
1598 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1599                                  const ObjCMethodDecl *Setter) {
1600   assert(PD);
1601   if (!Setter)
1602     return true;
1603 
1604   assert(Setter->getDeclName().isObjCOneArgSelector());
1605   return SelectorTable::constructSetterName(PD->getName()) ==
1606     Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1607 }
1608 
1609 /// CreateType - get objective-c interface type.
1610 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1611                                      llvm::DIFile Unit) {
1612   ObjCInterfaceDecl *ID = Ty->getDecl();
1613   if (!ID)
1614     return llvm::DIType();
1615 
1616   // Get overall information about the record type for the debug info.
1617   llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1618   unsigned Line = getLineNumber(ID->getLocation());
1619   unsigned RuntimeLang = TheCU.getLanguage();
1620 
1621   // If this is just a forward declaration return a special forward-declaration
1622   // debug type since we won't be able to lay out the entire type.
1623   ObjCInterfaceDecl *Def = ID->getDefinition();
1624   if (!Def) {
1625     llvm::DIType FwdDecl =
1626       DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1627                                  ID->getName(), TheCU, DefUnit, Line,
1628                                  RuntimeLang);
1629     return FwdDecl;
1630   }
1631 
1632   ID = Def;
1633 
1634   // Bit size, align and offset of the type.
1635   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1636   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1637 
1638   unsigned Flags = 0;
1639   if (ID->getImplementation())
1640     Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1641 
1642   llvm::DICompositeType RealDecl =
1643     DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1644                               Line, Size, Align, Flags,
1645                               llvm::DIType(), llvm::DIArray(), RuntimeLang);
1646 
1647   // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1648   // will find it and we're emitting the complete type.
1649   QualType QualTy = QualType(Ty, 0);
1650   CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
1651 
1652   // Push the struct on region stack.
1653   LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
1654   RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1655 
1656   // Convert all the elements.
1657   SmallVector<llvm::Value *, 16> EltTys;
1658 
1659   ObjCInterfaceDecl *SClass = ID->getSuperClass();
1660   if (SClass) {
1661     llvm::DIType SClassTy =
1662       getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1663     if (!SClassTy.isValid())
1664       return llvm::DIType();
1665 
1666     llvm::DIType InhTag =
1667       DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1668     EltTys.push_back(InhTag);
1669   }
1670 
1671   // Create entries for all of the properties.
1672   for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1673          E = ID->prop_end(); I != E; ++I) {
1674     const ObjCPropertyDecl *PD = *I;
1675     SourceLocation Loc = PD->getLocation();
1676     llvm::DIFile PUnit = getOrCreateFile(Loc);
1677     unsigned PLine = getLineNumber(Loc);
1678     ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1679     ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1680     llvm::MDNode *PropertyNode =
1681       DBuilder.createObjCProperty(PD->getName(),
1682                                   PUnit, PLine,
1683                                   hasDefaultGetterName(PD, Getter) ? "" :
1684                                   getSelectorName(PD->getGetterName()),
1685                                   hasDefaultSetterName(PD, Setter) ? "" :
1686                                   getSelectorName(PD->getSetterName()),
1687                                   PD->getPropertyAttributes(),
1688                                   getOrCreateType(PD->getType(), PUnit));
1689     EltTys.push_back(PropertyNode);
1690   }
1691 
1692   const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1693   unsigned FieldNo = 0;
1694   for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1695        Field = Field->getNextIvar(), ++FieldNo) {
1696     llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1697     if (!FieldTy.isValid())
1698       return llvm::DIType();
1699 
1700     StringRef FieldName = Field->getName();
1701 
1702     // Ignore unnamed fields.
1703     if (FieldName.empty())
1704       continue;
1705 
1706     // Get the location for the field.
1707     llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1708     unsigned FieldLine = getLineNumber(Field->getLocation());
1709     QualType FType = Field->getType();
1710     uint64_t FieldSize = 0;
1711     unsigned FieldAlign = 0;
1712 
1713     if (!FType->isIncompleteArrayType()) {
1714 
1715       // Bit size, align and offset of the type.
1716       FieldSize = Field->isBitField()
1717                       ? Field->getBitWidthValue(CGM.getContext())
1718                       : CGM.getContext().getTypeSize(FType);
1719       FieldAlign = CGM.getContext().getTypeAlign(FType);
1720     }
1721 
1722     uint64_t FieldOffset;
1723     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1724       // We don't know the runtime offset of an ivar if we're using the
1725       // non-fragile ABI.  For bitfields, use the bit offset into the first
1726       // byte of storage of the bitfield.  For other fields, use zero.
1727       if (Field->isBitField()) {
1728         FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1729             CGM, ID, Field);
1730         FieldOffset %= CGM.getContext().getCharWidth();
1731       } else {
1732         FieldOffset = 0;
1733       }
1734     } else {
1735       FieldOffset = RL.getFieldOffset(FieldNo);
1736     }
1737 
1738     unsigned Flags = 0;
1739     if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1740       Flags = llvm::DIDescriptor::FlagProtected;
1741     else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1742       Flags = llvm::DIDescriptor::FlagPrivate;
1743 
1744     llvm::MDNode *PropertyNode = NULL;
1745     if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1746       if (ObjCPropertyImplDecl *PImpD =
1747           ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1748         if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1749           SourceLocation Loc = PD->getLocation();
1750           llvm::DIFile PUnit = getOrCreateFile(Loc);
1751           unsigned PLine = getLineNumber(Loc);
1752           ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1753           ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1754           PropertyNode =
1755             DBuilder.createObjCProperty(PD->getName(),
1756                                         PUnit, PLine,
1757                                         hasDefaultGetterName(PD, Getter) ? "" :
1758                                         getSelectorName(PD->getGetterName()),
1759                                         hasDefaultSetterName(PD, Setter) ? "" :
1760                                         getSelectorName(PD->getSetterName()),
1761                                         PD->getPropertyAttributes(),
1762                                         getOrCreateType(PD->getType(), PUnit));
1763         }
1764       }
1765     }
1766     FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1767                                       FieldLine, FieldSize, FieldAlign,
1768                                       FieldOffset, Flags, FieldTy,
1769                                       PropertyNode);
1770     EltTys.push_back(FieldTy);
1771   }
1772 
1773   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1774   RealDecl.setTypeArray(Elements);
1775 
1776   // If the implementation is not yet set, we do not want to mark it
1777   // as complete. An implementation may declare additional
1778   // private ivars that we would miss otherwise.
1779   if (ID->getImplementation() == 0)
1780     CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
1781 
1782   LexicalBlockStack.pop_back();
1783   return RealDecl;
1784 }
1785 
1786 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1787   llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1788   int64_t Count = Ty->getNumElements();
1789   if (Count == 0)
1790     // If number of elements are not known then this is an unbounded array.
1791     // Use Count == -1 to express such arrays.
1792     Count = -1;
1793 
1794   llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1795   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1796 
1797   uint64_t Size = CGM.getContext().getTypeSize(Ty);
1798   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1799 
1800   return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1801 }
1802 
1803 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1804                                      llvm::DIFile Unit) {
1805   uint64_t Size;
1806   uint64_t Align;
1807 
1808   // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1809   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1810     Size = 0;
1811     Align =
1812       CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1813   } else if (Ty->isIncompleteArrayType()) {
1814     Size = 0;
1815     if (Ty->getElementType()->isIncompleteType())
1816       Align = 0;
1817     else
1818       Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1819   } else if (Ty->isIncompleteType()) {
1820     Size = 0;
1821     Align = 0;
1822   } else {
1823     // Size and align of the whole array, not the element type.
1824     Size = CGM.getContext().getTypeSize(Ty);
1825     Align = CGM.getContext().getTypeAlign(Ty);
1826   }
1827 
1828   // Add the dimensions of the array.  FIXME: This loses CV qualifiers from
1829   // interior arrays, do we care?  Why aren't nested arrays represented the
1830   // obvious/recursive way?
1831   SmallVector<llvm::Value *, 8> Subscripts;
1832   QualType EltTy(Ty, 0);
1833   while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1834     // If the number of elements is known, then count is that number. Otherwise,
1835     // it's -1. This allows us to represent a subrange with an array of 0
1836     // elements, like this:
1837     //
1838     //   struct foo {
1839     //     int x[0];
1840     //   };
1841     int64_t Count = -1;         // Count == -1 is an unbounded array.
1842     if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1843       Count = CAT->getSize().getZExtValue();
1844 
1845     // FIXME: Verify this is right for VLAs.
1846     Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1847     EltTy = Ty->getElementType();
1848   }
1849 
1850   llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1851 
1852   llvm::DIType DbgTy =
1853     DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1854                              SubscriptArray);
1855   return DbgTy;
1856 }
1857 
1858 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1859                                      llvm::DIFile Unit) {
1860   return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1861                                Ty, Ty->getPointeeType(), Unit);
1862 }
1863 
1864 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1865                                      llvm::DIFile Unit) {
1866   return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1867                                Ty, Ty->getPointeeType(), Unit);
1868 }
1869 
1870 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1871                                      llvm::DIFile U) {
1872   llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1873   if (!Ty->getPointeeType()->isFunctionType())
1874     return DBuilder.createMemberPointerType(
1875         getOrCreateType(Ty->getPointeeType(), U), ClassType);
1876 
1877   const FunctionProtoType *FPT =
1878     Ty->getPointeeType()->getAs<FunctionProtoType>();
1879   return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1880       CGM.getContext().getPointerType(QualType(Ty->getClass(),
1881                                                FPT->getTypeQuals())),
1882       FPT, U), ClassType);
1883 }
1884 
1885 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1886                                      llvm::DIFile U) {
1887   // Ignore the atomic wrapping
1888   // FIXME: What is the correct representation?
1889   return getOrCreateType(Ty->getValueType(), U);
1890 }
1891 
1892 /// CreateEnumType - get enumeration type.
1893 llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
1894   const EnumDecl *ED = Ty->getDecl();
1895   uint64_t Size = 0;
1896   uint64_t Align = 0;
1897   if (!ED->getTypeForDecl()->isIncompleteType()) {
1898     Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1899     Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1900   }
1901 
1902   SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1903 
1904   // If this is just a forward declaration, construct an appropriately
1905   // marked node and just return it.
1906   if (!ED->getDefinition()) {
1907     llvm::DIDescriptor EDContext;
1908     EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1909     llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1910     unsigned Line = getLineNumber(ED->getLocation());
1911     StringRef EDName = ED->getName();
1912     return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1913                                       EDName, EDContext, DefUnit, Line, 0,
1914                                       Size, Align, FullName);
1915   }
1916 
1917   // Create DIEnumerator elements for each enumerator.
1918   SmallVector<llvm::Value *, 16> Enumerators;
1919   ED = ED->getDefinition();
1920   for (const auto *Enum : ED->enumerators()) {
1921     Enumerators.push_back(
1922       DBuilder.createEnumerator(Enum->getName(),
1923                                 Enum->getInitVal().getSExtValue()));
1924   }
1925 
1926   // Return a CompositeType for the enum itself.
1927   llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1928 
1929   llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1930   unsigned Line = getLineNumber(ED->getLocation());
1931   llvm::DIDescriptor EnumContext =
1932     getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1933   llvm::DIType ClassTy = ED->isFixed() ?
1934     getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1935   llvm::DIType DbgTy =
1936     DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1937                                    Size, Align, EltArray,
1938                                    ClassTy, FullName);
1939   return DbgTy;
1940 }
1941 
1942 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1943   Qualifiers Quals;
1944   do {
1945     Qualifiers InnerQuals = T.getLocalQualifiers();
1946     // Qualifiers::operator+() doesn't like it if you add a Qualifier
1947     // that is already there.
1948     Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1949     Quals += InnerQuals;
1950     QualType LastT = T;
1951     switch (T->getTypeClass()) {
1952     default:
1953       return C.getQualifiedType(T.getTypePtr(), Quals);
1954     case Type::TemplateSpecialization:
1955       T = cast<TemplateSpecializationType>(T)->desugar();
1956       break;
1957     case Type::TypeOfExpr:
1958       T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1959       break;
1960     case Type::TypeOf:
1961       T = cast<TypeOfType>(T)->getUnderlyingType();
1962       break;
1963     case Type::Decltype:
1964       T = cast<DecltypeType>(T)->getUnderlyingType();
1965       break;
1966     case Type::UnaryTransform:
1967       T = cast<UnaryTransformType>(T)->getUnderlyingType();
1968       break;
1969     case Type::Attributed:
1970       T = cast<AttributedType>(T)->getEquivalentType();
1971       break;
1972     case Type::Elaborated:
1973       T = cast<ElaboratedType>(T)->getNamedType();
1974       break;
1975     case Type::Paren:
1976       T = cast<ParenType>(T)->getInnerType();
1977       break;
1978     case Type::SubstTemplateTypeParm:
1979       T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1980       break;
1981     case Type::Auto:
1982       QualType DT = cast<AutoType>(T)->getDeducedType();
1983       if (DT.isNull())
1984         return T;
1985       T = DT;
1986       break;
1987     }
1988 
1989     assert(T != LastT && "Type unwrapping failed to unwrap!");
1990     (void)LastT;
1991   } while (true);
1992 }
1993 
1994 /// getType - Get the type from the cache or return null type if it doesn't
1995 /// exist.
1996 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1997 
1998   // Unwrap the type as needed for debug information.
1999   Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2000 
2001   // Check for existing entry.
2002   if (Ty->getTypeClass() == Type::ObjCInterface) {
2003     llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
2004     if (V)
2005       return llvm::DIType(cast<llvm::MDNode>(V));
2006     else return llvm::DIType();
2007   }
2008 
2009   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2010     TypeCache.find(Ty.getAsOpaquePtr());
2011   if (it != TypeCache.end()) {
2012     // Verify that the debug info still exists.
2013     if (llvm::Value *V = it->second)
2014       return llvm::DIType(cast<llvm::MDNode>(V));
2015   }
2016 
2017   return llvm::DIType();
2018 }
2019 
2020 /// getCompletedTypeOrNull - Get the type from the cache or return null if it
2021 /// doesn't exist.
2022 llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
2023 
2024   // Unwrap the type as needed for debug information.
2025   Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2026 
2027   // Check for existing entry.
2028   llvm::Value *V = 0;
2029   llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2030     CompletedTypeCache.find(Ty.getAsOpaquePtr());
2031   if (it != CompletedTypeCache.end())
2032     V = it->second;
2033   else {
2034     V = getCachedInterfaceTypeOrNull(Ty);
2035   }
2036 
2037   // Verify that any cached debug info still exists.
2038   return llvm::DIType(cast_or_null<llvm::MDNode>(V));
2039 }
2040 
2041 void CGDebugInfo::completeTemplateDefinition(
2042     const ClassTemplateSpecializationDecl &SD) {
2043   if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2044     return;
2045 
2046   completeClassData(&SD);
2047   // In case this type has no member function definitions being emitted, ensure
2048   // it is retained
2049   RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2050 }
2051 
2052 /// getCachedInterfaceTypeOrNull - Get the type from the interface
2053 /// cache, unless it needs to regenerated. Otherwise return null.
2054 llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2055   // Is there a cached interface that hasn't changed?
2056   llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2057     ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2058 
2059   if (it1 != ObjCInterfaceCache.end())
2060     if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2061       if (Checksum(Decl) == it1->second.second)
2062         // Return cached forward declaration.
2063         return it1->second.first;
2064 
2065   return 0;
2066 }
2067 
2068 /// getOrCreateType - Get the type from the cache or create a new
2069 /// one if necessary.
2070 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
2071   if (Ty.isNull())
2072     return llvm::DIType();
2073 
2074   // Unwrap the type as needed for debug information.
2075   Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2076 
2077   if (llvm::DIType T = getCompletedTypeOrNull(Ty))
2078     return T;
2079 
2080   // Otherwise create the type.
2081   llvm::DIType Res = CreateTypeNode(Ty, Unit);
2082   void* TyPtr = Ty.getAsOpaquePtr();
2083 
2084   // And update the type cache.
2085   TypeCache[TyPtr] = Res;
2086 
2087   // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2088   // into the cache - but getTypeOrNull has a special case for cached interface
2089   // types. We should probably just pull that out as a special case for the
2090   // "else" block below & skip the otherwise needless lookup.
2091   llvm::DIType TC = getTypeOrNull(Ty);
2092   if (TC && TC.isForwardDecl())
2093     ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2094   else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2095     // Interface types may have elements added to them by a
2096     // subsequent implementation or extension, so we keep them in
2097     // the ObjCInterfaceCache together with a checksum. Instead of
2098     // the (possibly) incomplete interface type, we return a forward
2099     // declaration that gets RAUW'd in CGDebugInfo::finalize().
2100     std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2101     if (V.first)
2102       return llvm::DIType(cast<llvm::MDNode>(V.first));
2103     TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2104                                     Decl->getName(), TheCU, Unit,
2105                                     getLineNumber(Decl->getLocation()),
2106                                     TheCU.getLanguage());
2107     // Store the forward declaration in the cache.
2108     V.first = TC;
2109     V.second = Checksum(Decl);
2110 
2111     // Register the type for replacement in finalize().
2112     ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2113 
2114     return TC;
2115   }
2116 
2117   if (!Res.isForwardDecl())
2118     CompletedTypeCache[TyPtr] = Res;
2119 
2120   return Res;
2121 }
2122 
2123 /// Currently the checksum of an interface includes the number of
2124 /// ivars and property accessors.
2125 unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
2126   // The assumption is that the number of ivars can only increase
2127   // monotonically, so it is safe to just use their current number as
2128   // a checksum.
2129   unsigned Sum = 0;
2130   for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2131        Ivar != 0; Ivar = Ivar->getNextIvar())
2132     ++Sum;
2133 
2134   return Sum;
2135 }
2136 
2137 ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2138   switch (Ty->getTypeClass()) {
2139   case Type::ObjCObjectPointer:
2140     return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2141                                     ->getPointeeType());
2142   case Type::ObjCInterface:
2143     return cast<ObjCInterfaceType>(Ty)->getDecl();
2144   default:
2145     return 0;
2146   }
2147 }
2148 
2149 /// CreateTypeNode - Create a new debug type node.
2150 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
2151   // Handle qualifiers, which recursively handles what they refer to.
2152   if (Ty.hasLocalQualifiers())
2153     return CreateQualifiedType(Ty, Unit);
2154 
2155   const char *Diag = 0;
2156 
2157   // Work out details of type.
2158   switch (Ty->getTypeClass()) {
2159 #define TYPE(Class, Base)
2160 #define ABSTRACT_TYPE(Class, Base)
2161 #define NON_CANONICAL_TYPE(Class, Base)
2162 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2163 #include "clang/AST/TypeNodes.def"
2164     llvm_unreachable("Dependent types cannot show up in debug information");
2165 
2166   case Type::ExtVector:
2167   case Type::Vector:
2168     return CreateType(cast<VectorType>(Ty), Unit);
2169   case Type::ObjCObjectPointer:
2170     return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2171   case Type::ObjCObject:
2172     return CreateType(cast<ObjCObjectType>(Ty), Unit);
2173   case Type::ObjCInterface:
2174     return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2175   case Type::Builtin:
2176     return CreateType(cast<BuiltinType>(Ty));
2177   case Type::Complex:
2178     return CreateType(cast<ComplexType>(Ty));
2179   case Type::Pointer:
2180     return CreateType(cast<PointerType>(Ty), Unit);
2181   case Type::Adjusted:
2182   case Type::Decayed:
2183     // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2184     return CreateType(
2185         cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
2186   case Type::BlockPointer:
2187     return CreateType(cast<BlockPointerType>(Ty), Unit);
2188   case Type::Typedef:
2189     return CreateType(cast<TypedefType>(Ty), Unit);
2190   case Type::Record:
2191     return CreateType(cast<RecordType>(Ty));
2192   case Type::Enum:
2193     return CreateEnumType(cast<EnumType>(Ty));
2194   case Type::FunctionProto:
2195   case Type::FunctionNoProto:
2196     return CreateType(cast<FunctionType>(Ty), Unit);
2197   case Type::ConstantArray:
2198   case Type::VariableArray:
2199   case Type::IncompleteArray:
2200     return CreateType(cast<ArrayType>(Ty), Unit);
2201 
2202   case Type::LValueReference:
2203     return CreateType(cast<LValueReferenceType>(Ty), Unit);
2204   case Type::RValueReference:
2205     return CreateType(cast<RValueReferenceType>(Ty), Unit);
2206 
2207   case Type::MemberPointer:
2208     return CreateType(cast<MemberPointerType>(Ty), Unit);
2209 
2210   case Type::Atomic:
2211     return CreateType(cast<AtomicType>(Ty), Unit);
2212 
2213   case Type::Attributed:
2214   case Type::TemplateSpecialization:
2215   case Type::Elaborated:
2216   case Type::Paren:
2217   case Type::SubstTemplateTypeParm:
2218   case Type::TypeOfExpr:
2219   case Type::TypeOf:
2220   case Type::Decltype:
2221   case Type::UnaryTransform:
2222   case Type::PackExpansion:
2223     llvm_unreachable("type should have been unwrapped!");
2224   case Type::Auto:
2225     Diag = "auto";
2226     break;
2227   }
2228 
2229   assert(Diag && "Fall through without a diagnostic?");
2230   unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2231                                "debug information for %0 is not yet supported");
2232   CGM.getDiags().Report(DiagID)
2233     << Diag;
2234   return llvm::DIType();
2235 }
2236 
2237 /// getOrCreateLimitedType - Get the type from the cache or create a new
2238 /// limited type if necessary.
2239 llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2240                                                  llvm::DIFile Unit) {
2241   QualType QTy(Ty, 0);
2242 
2243   llvm::DICompositeType T(getTypeOrNull(QTy));
2244 
2245   // We may have cached a forward decl when we could have created
2246   // a non-forward decl. Go ahead and create a non-forward decl
2247   // now.
2248   if (T && !T.isForwardDecl()) return T;
2249 
2250   // Otherwise create the type.
2251   llvm::DICompositeType Res = CreateLimitedType(Ty);
2252 
2253   // Propagate members from the declaration to the definition
2254   // CreateType(const RecordType*) will overwrite this with the members in the
2255   // correct order if the full type is needed.
2256   Res.setTypeArray(T.getTypeArray());
2257 
2258   if (T && T.isForwardDecl())
2259     ReplaceMap.push_back(
2260         std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
2261 
2262   // And update the type cache.
2263   TypeCache[QTy.getAsOpaquePtr()] = Res;
2264   return Res;
2265 }
2266 
2267 // TODO: Currently used for context chains when limiting debug info.
2268 llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2269   RecordDecl *RD = Ty->getDecl();
2270 
2271   // Get overall information about the record type for the debug info.
2272   llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2273   unsigned Line = getLineNumber(RD->getLocation());
2274   StringRef RDName = getClassName(RD);
2275 
2276   llvm::DIDescriptor RDContext =
2277       getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2278 
2279   // If we ended up creating the type during the context chain construction,
2280   // just return that.
2281   // FIXME: this could be dealt with better if the type was recorded as
2282   // completed before we started this (see the CompletedTypeCache usage in
2283   // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2284   // be pushed to before context creation, but after it was known to be
2285   // destined for completion (might still have an issue if this caller only
2286   // required a declaration but the context construction ended up creating a
2287   // definition)
2288   llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2289   if (T && (!T.isForwardDecl() || !RD->getDefinition()))
2290       return T;
2291 
2292   // If this is just a forward or incomplete declaration, construct an
2293   // appropriately marked node and just return it.
2294   const RecordDecl *D = RD->getDefinition();
2295   if (!D || !D->isCompleteDefinition())
2296     return getOrCreateRecordFwdDecl(Ty, RDContext);
2297 
2298   uint64_t Size = CGM.getContext().getTypeSize(Ty);
2299   uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2300   llvm::DICompositeType RealDecl;
2301 
2302   SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2303 
2304   if (RD->isUnion())
2305     RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
2306                                         Size, Align, 0, llvm::DIArray(), 0,
2307                                         FullName);
2308   else if (RD->isClass()) {
2309     // FIXME: This could be a struct type giving a default visibility different
2310     // than C++ class type, but needs llvm metadata changes first.
2311     RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
2312                                         Size, Align, 0, 0, llvm::DIType(),
2313                                         llvm::DIArray(), llvm::DIType(),
2314                                         llvm::DIArray(), FullName);
2315   } else
2316     RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
2317                                          Size, Align, 0, llvm::DIType(),
2318                                          llvm::DIArray(), 0, llvm::DIType(),
2319                                          FullName);
2320 
2321   RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
2322   TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
2323 
2324   if (const ClassTemplateSpecializationDecl *TSpecial =
2325           dyn_cast<ClassTemplateSpecializationDecl>(RD))
2326     RealDecl.setTypeArray(llvm::DIArray(),
2327                           CollectCXXTemplateParams(TSpecial, DefUnit));
2328   return RealDecl;
2329 }
2330 
2331 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2332                                         llvm::DICompositeType RealDecl) {
2333   // A class's primary base or the class itself contains the vtable.
2334   llvm::DICompositeType ContainingType;
2335   const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2336   if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2337     // Seek non-virtual primary base root.
2338     while (1) {
2339       const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2340       const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2341       if (PBT && !BRL.isPrimaryBaseVirtual())
2342         PBase = PBT;
2343       else
2344         break;
2345     }
2346     ContainingType = llvm::DICompositeType(
2347         getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2348                         getOrCreateFile(RD->getLocation())));
2349   } else if (RD->isDynamicClass())
2350     ContainingType = RealDecl;
2351 
2352   RealDecl.setContainingType(ContainingType);
2353 }
2354 
2355 /// CreateMemberType - Create new member and increase Offset by FType's size.
2356 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2357                                            StringRef Name,
2358                                            uint64_t *Offset) {
2359   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2360   uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2361   unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2362   llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2363                                               FieldSize, FieldAlign,
2364                                               *Offset, 0, FieldTy);
2365   *Offset += FieldSize;
2366   return Ty;
2367 }
2368 
2369 llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2370   // We only need a declaration (not a definition) of the type - so use whatever
2371   // we would otherwise do to get a type for a pointee. (forward declarations in
2372   // limited debug info, full definitions (if the type definition is available)
2373   // in unlimited debug info)
2374   if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2375     return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
2376                            getOrCreateFile(TD->getLocation()));
2377   // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2378   // This doesn't handle providing declarations (for functions or variables) for
2379   // entities without definitions in this TU, nor when the definition proceeds
2380   // the call to this function.
2381   // FIXME: This should be split out into more specific maps with support for
2382   // emitting forward declarations and merging definitions with declarations,
2383   // the same way as we do for types.
2384   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2385       DeclCache.find(D->getCanonicalDecl());
2386   if (I == DeclCache.end())
2387     return llvm::DIDescriptor();
2388   llvm::Value *V = I->second;
2389   return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2390 }
2391 
2392 /// getFunctionDeclaration - Return debug info descriptor to describe method
2393 /// declaration for the given method definition.
2394 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2395   if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2396     return llvm::DISubprogram();
2397 
2398   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2399   if (!FD) return llvm::DISubprogram();
2400 
2401   // Setup context.
2402   llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
2403 
2404   llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2405     MI = SPCache.find(FD->getCanonicalDecl());
2406   if (MI == SPCache.end()) {
2407     if (const CXXMethodDecl *MD =
2408             dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
2409       llvm::DICompositeType T(S);
2410       llvm::DISubprogram SP =
2411           CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
2412       return SP;
2413     }
2414   }
2415   if (MI != SPCache.end()) {
2416     llvm::Value *V = MI->second;
2417     llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2418     if (SP.isSubprogram() && !SP.isDefinition())
2419       return SP;
2420   }
2421 
2422   for (auto NextFD : FD->redecls()) {
2423     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2424       MI = SPCache.find(NextFD->getCanonicalDecl());
2425     if (MI != SPCache.end()) {
2426       llvm::Value *V = MI->second;
2427       llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2428       if (SP.isSubprogram() && !SP.isDefinition())
2429         return SP;
2430     }
2431   }
2432   return llvm::DISubprogram();
2433 }
2434 
2435 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2436 // implicit parameter "this".
2437 llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2438                                                            QualType FnType,
2439                                                            llvm::DIFile F) {
2440   if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2441     // Create fake but valid subroutine type. Otherwise
2442     // llvm::DISubprogram::Verify() would return false, and
2443     // subprogram DIE will miss DW_AT_decl_file and
2444     // DW_AT_decl_line fields.
2445     return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
2446 
2447   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2448     return getOrCreateMethodType(Method, F);
2449   if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2450     // Add "self" and "_cmd"
2451     SmallVector<llvm::Value *, 16> Elts;
2452 
2453     // First element is always return type. For 'void' functions it is NULL.
2454     QualType ResultTy = OMethod->getReturnType();
2455 
2456     // Replace the instancetype keyword with the actual type.
2457     if (ResultTy == CGM.getContext().getObjCInstanceType())
2458       ResultTy = CGM.getContext().getPointerType(
2459         QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2460 
2461     Elts.push_back(getOrCreateType(ResultTy, F));
2462     // "self" pointer is always first argument.
2463     QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2464     llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2465     Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
2466     // "_cmd" pointer is always second argument.
2467     llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2468     Elts.push_back(DBuilder.createArtificialType(CmdTy));
2469     // Get rest of the arguments.
2470     for (const auto *PI : OMethod->params())
2471       Elts.push_back(getOrCreateType(PI->getType(), F));
2472 
2473     llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2474     return DBuilder.createSubroutineType(F, EltTypeArray);
2475   }
2476 
2477   // Handle variadic function types; they need an additional
2478   // unspecified parameter.
2479   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2480     if (FD->isVariadic()) {
2481       SmallVector<llvm::Value *, 16> EltTys;
2482       EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2483       if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2484         for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2485           EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2486       EltTys.push_back(DBuilder.createUnspecifiedParameter());
2487       llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
2488       return DBuilder.createSubroutineType(F, EltTypeArray);
2489     }
2490 
2491   return llvm::DICompositeType(getOrCreateType(FnType, F));
2492 }
2493 
2494 /// EmitFunctionStart - Constructs the debug code for entering a function.
2495 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2496                                     llvm::Function *Fn,
2497                                     CGBuilderTy &Builder) {
2498 
2499   StringRef Name;
2500   StringRef LinkageName;
2501 
2502   FnBeginRegionCount.push_back(LexicalBlockStack.size());
2503 
2504   const Decl *D = GD.getDecl();
2505   // Function may lack declaration in source code if it is created by Clang
2506   // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2507   bool HasDecl = (D != 0);
2508   // Use the location of the declaration.
2509   SourceLocation Loc;
2510   if (HasDecl)
2511     Loc = D->getLocation();
2512 
2513   unsigned Flags = 0;
2514   llvm::DIFile Unit = getOrCreateFile(Loc);
2515   llvm::DIDescriptor FDContext(Unit);
2516   llvm::DIArray TParamsArray;
2517   if (!HasDecl) {
2518     // Use llvm function name.
2519     LinkageName = Fn->getName();
2520   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2521     // If there is a DISubprogram for this function available then use it.
2522     llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2523       FI = SPCache.find(FD->getCanonicalDecl());
2524     if (FI != SPCache.end()) {
2525       llvm::Value *V = FI->second;
2526       llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2527       if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2528         llvm::MDNode *SPN = SP;
2529         LexicalBlockStack.push_back(SPN);
2530         RegionMap[D] = llvm::WeakVH(SP);
2531         return;
2532       }
2533     }
2534     Name = getFunctionName(FD);
2535     // Use mangled name as linkage name for C/C++ functions.
2536     if (FD->hasPrototype()) {
2537       LinkageName = CGM.getMangledName(GD);
2538       Flags |= llvm::DIDescriptor::FlagPrototyped;
2539     }
2540     // No need to replicate the linkage name if it isn't different from the
2541     // subprogram name, no need to have it at all unless coverage is enabled or
2542     // debug is set to more than just line tables.
2543     if (LinkageName == Name ||
2544         (!CGM.getCodeGenOpts().EmitGcovArcs &&
2545          !CGM.getCodeGenOpts().EmitGcovNotes &&
2546          DebugKind <= CodeGenOptions::DebugLineTablesOnly))
2547       LinkageName = StringRef();
2548 
2549     if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
2550       if (const NamespaceDecl *NSDecl =
2551               dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2552         FDContext = getOrCreateNameSpace(NSDecl);
2553       else if (const RecordDecl *RDecl =
2554                    dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2555         FDContext = getContextDescriptor(cast<Decl>(RDecl));
2556 
2557       // Collect template parameters.
2558       TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2559     }
2560   } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2561     Name = getObjCMethodName(OMD);
2562     Flags |= llvm::DIDescriptor::FlagPrototyped;
2563   } else {
2564     // Use llvm function name.
2565     Name = Fn->getName();
2566     Flags |= llvm::DIDescriptor::FlagPrototyped;
2567   }
2568   if (!Name.empty() && Name[0] == '\01')
2569     Name = Name.substr(1);
2570 
2571   unsigned LineNo = getLineNumber(Loc);
2572   if (!HasDecl || D->isImplicit())
2573     Flags |= llvm::DIDescriptor::FlagArtificial;
2574 
2575   llvm::DISubprogram SP =
2576       DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2577                               getOrCreateFunctionType(D, FnType, Unit),
2578                               Fn->hasInternalLinkage(), true /*definition*/,
2579                               getLineNumber(CurLoc), Flags,
2580                               CGM.getLangOpts().Optimize, Fn, TParamsArray,
2581                               getFunctionDeclaration(D));
2582   if (HasDecl)
2583     DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
2584 
2585   // Push function on region stack.
2586   llvm::MDNode *SPN = SP;
2587   LexicalBlockStack.push_back(SPN);
2588   if (HasDecl)
2589     RegionMap[D] = llvm::WeakVH(SP);
2590 }
2591 
2592 /// EmitLocation - Emit metadata to indicate a change in line/column
2593 /// information in the source file. If the location is invalid, the
2594 /// previous location will be reused.
2595 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2596                                bool ForceColumnInfo) {
2597   // Update our current location
2598   setLocation(Loc);
2599 
2600   if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2601 
2602   // Don't bother if things are the same as last time.
2603   SourceManager &SM = CGM.getContext().getSourceManager();
2604   if (CurLoc == PrevLoc ||
2605       SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2606     // New Builder may not be in sync with CGDebugInfo.
2607     if (!Builder.getCurrentDebugLocation().isUnknown() &&
2608         Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2609           LexicalBlockStack.back())
2610       return;
2611 
2612   // Update last state.
2613   PrevLoc = CurLoc;
2614 
2615   llvm::MDNode *Scope = LexicalBlockStack.back();
2616   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2617                                   (getLineNumber(CurLoc),
2618                                    getColumnNumber(CurLoc, ForceColumnInfo),
2619                                    Scope));
2620 }
2621 
2622 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2623 /// the stack.
2624 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2625   llvm::DIDescriptor D =
2626     DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2627                                 llvm::DIDescriptor() :
2628                                 llvm::DIDescriptor(LexicalBlockStack.back()),
2629                                 getOrCreateFile(CurLoc),
2630                                 getLineNumber(CurLoc),
2631                                 getColumnNumber(CurLoc),
2632                                 0);
2633   llvm::MDNode *DN = D;
2634   LexicalBlockStack.push_back(DN);
2635 }
2636 
2637 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2638 /// region - beginning of a DW_TAG_lexical_block.
2639 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2640                                         SourceLocation Loc) {
2641   // Set our current location.
2642   setLocation(Loc);
2643 
2644   // Create a new lexical block and push it on the stack.
2645   CreateLexicalBlock(Loc);
2646 
2647   // Emit a line table change for the current location inside the new scope.
2648   Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2649                                   getColumnNumber(Loc),
2650                                   LexicalBlockStack.back()));
2651 }
2652 
2653 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2654 /// region - end of a DW_TAG_lexical_block.
2655 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2656                                       SourceLocation Loc) {
2657   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2658 
2659   // Provide an entry in the line table for the end of the block.
2660   EmitLocation(Builder, Loc);
2661 
2662   LexicalBlockStack.pop_back();
2663 }
2664 
2665 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
2666 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2667   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2668   unsigned RCount = FnBeginRegionCount.back();
2669   assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2670 
2671   // Pop all regions for this function.
2672   while (LexicalBlockStack.size() != RCount)
2673     EmitLexicalBlockEnd(Builder, CurLoc);
2674   FnBeginRegionCount.pop_back();
2675 }
2676 
2677 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2678 // See BuildByRefType.
2679 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2680                                                        uint64_t *XOffset) {
2681 
2682   SmallVector<llvm::Value *, 5> EltTys;
2683   QualType FType;
2684   uint64_t FieldSize, FieldOffset;
2685   unsigned FieldAlign;
2686 
2687   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2688   QualType Type = VD->getType();
2689 
2690   FieldOffset = 0;
2691   FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2692   EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2693   EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2694   FType = CGM.getContext().IntTy;
2695   EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2696   EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2697 
2698   bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2699   if (HasCopyAndDispose) {
2700     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2701     EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2702                                       &FieldOffset));
2703     EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2704                                       &FieldOffset));
2705   }
2706   bool HasByrefExtendedLayout;
2707   Qualifiers::ObjCLifetime Lifetime;
2708   if (CGM.getContext().getByrefLifetime(Type,
2709                                         Lifetime, HasByrefExtendedLayout)
2710       && HasByrefExtendedLayout) {
2711     FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2712     EltTys.push_back(CreateMemberType(Unit, FType,
2713                                       "__byref_variable_layout",
2714                                       &FieldOffset));
2715   }
2716 
2717   CharUnits Align = CGM.getContext().getDeclAlign(VD);
2718   if (Align > CGM.getContext().toCharUnitsFromBits(
2719         CGM.getTarget().getPointerAlign(0))) {
2720     CharUnits FieldOffsetInBytes
2721       = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2722     CharUnits AlignedOffsetInBytes
2723       = FieldOffsetInBytes.RoundUpToAlignment(Align);
2724     CharUnits NumPaddingBytes
2725       = AlignedOffsetInBytes - FieldOffsetInBytes;
2726 
2727     if (NumPaddingBytes.isPositive()) {
2728       llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2729       FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2730                                                     pad, ArrayType::Normal, 0);
2731       EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2732     }
2733   }
2734 
2735   FType = Type;
2736   llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2737   FieldSize = CGM.getContext().getTypeSize(FType);
2738   FieldAlign = CGM.getContext().toBits(Align);
2739 
2740   *XOffset = FieldOffset;
2741   FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2742                                       0, FieldSize, FieldAlign,
2743                                       FieldOffset, 0, FieldTy);
2744   EltTys.push_back(FieldTy);
2745   FieldOffset += FieldSize;
2746 
2747   llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2748 
2749   unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2750 
2751   return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2752                                    llvm::DIType(), Elements);
2753 }
2754 
2755 /// EmitDeclare - Emit local variable declaration debug info.
2756 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2757                               llvm::Value *Storage,
2758                               unsigned ArgNo, CGBuilderTy &Builder) {
2759   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2760   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2761 
2762   bool Unwritten =
2763       VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2764                            cast<Decl>(VD->getDeclContext())->isImplicit());
2765   llvm::DIFile Unit;
2766   if (!Unwritten)
2767     Unit = getOrCreateFile(VD->getLocation());
2768   llvm::DIType Ty;
2769   uint64_t XOffset = 0;
2770   if (VD->hasAttr<BlocksAttr>())
2771     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2772   else
2773     Ty = getOrCreateType(VD->getType(), Unit);
2774 
2775   // If there is no debug info for this type then do not emit debug info
2776   // for this variable.
2777   if (!Ty)
2778     return;
2779 
2780   // Get location information.
2781   unsigned Line = 0;
2782   unsigned Column = 0;
2783   if (!Unwritten) {
2784     Line = getLineNumber(VD->getLocation());
2785     Column = getColumnNumber(VD->getLocation());
2786   }
2787   unsigned Flags = 0;
2788   if (VD->isImplicit())
2789     Flags |= llvm::DIDescriptor::FlagArtificial;
2790   // If this is the first argument and it is implicit then
2791   // give it an object pointer flag.
2792   // FIXME: There has to be a better way to do this, but for static
2793   // functions there won't be an implicit param at arg1 and
2794   // otherwise it is 'self' or 'this'.
2795   if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2796     Flags |= llvm::DIDescriptor::FlagObjectPointer;
2797   if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
2798     if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2799         !VD->getType()->isPointerType())
2800       Flags |= llvm::DIDescriptor::FlagIndirectVariable;
2801 
2802   llvm::MDNode *Scope = LexicalBlockStack.back();
2803 
2804   StringRef Name = VD->getName();
2805   if (!Name.empty()) {
2806     if (VD->hasAttr<BlocksAttr>()) {
2807       CharUnits offset = CharUnits::fromQuantity(32);
2808       SmallVector<llvm::Value *, 9> addr;
2809       llvm::Type *Int64Ty = CGM.Int64Ty;
2810       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2811       // offset of __forwarding field
2812       offset = CGM.getContext().toCharUnitsFromBits(
2813         CGM.getTarget().getPointerWidth(0));
2814       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2815       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2816       addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2817       // offset of x field
2818       offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2819       addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2820 
2821       // Create the descriptor for the variable.
2822       llvm::DIVariable D =
2823         DBuilder.createComplexVariable(Tag,
2824                                        llvm::DIDescriptor(Scope),
2825                                        VD->getName(), Unit, Line, Ty,
2826                                        addr, ArgNo);
2827 
2828       // Insert an llvm.dbg.declare into the current block.
2829       llvm::Instruction *Call =
2830         DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2831       Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2832       return;
2833     } else if (isa<VariableArrayType>(VD->getType()))
2834       Flags |= llvm::DIDescriptor::FlagIndirectVariable;
2835   } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2836     // If VD is an anonymous union then Storage represents value for
2837     // all union fields.
2838     const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2839     if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
2840       for (const auto *Field : RD->fields()) {
2841         llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2842         StringRef FieldName = Field->getName();
2843 
2844         // Ignore unnamed fields. Do not ignore unnamed records.
2845         if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2846           continue;
2847 
2848         // Use VarDecl's Tag, Scope and Line number.
2849         llvm::DIVariable D =
2850           DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2851                                        FieldName, Unit, Line, FieldTy,
2852                                        CGM.getLangOpts().Optimize, Flags,
2853                                        ArgNo);
2854 
2855         // Insert an llvm.dbg.declare into the current block.
2856         llvm::Instruction *Call =
2857           DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2858         Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2859       }
2860       return;
2861     }
2862   }
2863 
2864   // Create the descriptor for the variable.
2865   llvm::DIVariable D =
2866     DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2867                                  Name, Unit, Line, Ty,
2868                                  CGM.getLangOpts().Optimize, Flags, ArgNo);
2869 
2870   // Insert an llvm.dbg.declare into the current block.
2871   llvm::Instruction *Call =
2872     DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2873   Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2874 }
2875 
2876 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2877                                             llvm::Value *Storage,
2878                                             CGBuilderTy &Builder) {
2879   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2880   EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2881 }
2882 
2883 /// Look up the completed type for a self pointer in the TypeCache and
2884 /// create a copy of it with the ObjectPointer and Artificial flags
2885 /// set. If the type is not cached, a new one is created. This should
2886 /// never happen though, since creating a type for the implicit self
2887 /// argument implies that we already parsed the interface definition
2888 /// and the ivar declarations in the implementation.
2889 llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2890                                          llvm::DIType Ty) {
2891   llvm::DIType CachedTy = getTypeOrNull(QualTy);
2892   if (CachedTy) Ty = CachedTy;
2893   else DEBUG(llvm::dbgs() << "No cached type for self.");
2894   return DBuilder.createObjectPointerType(Ty);
2895 }
2896 
2897 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2898                                                     llvm::Value *Storage,
2899                                                     CGBuilderTy &Builder,
2900                                                  const CGBlockInfo &blockInfo) {
2901   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2902   assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2903 
2904   if (Builder.GetInsertBlock() == 0)
2905     return;
2906 
2907   bool isByRef = VD->hasAttr<BlocksAttr>();
2908 
2909   uint64_t XOffset = 0;
2910   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2911   llvm::DIType Ty;
2912   if (isByRef)
2913     Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2914   else
2915     Ty = getOrCreateType(VD->getType(), Unit);
2916 
2917   // Self is passed along as an implicit non-arg variable in a
2918   // block. Mark it as the object pointer.
2919   if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
2920     Ty = CreateSelfType(VD->getType(), Ty);
2921 
2922   // Get location information.
2923   unsigned Line = getLineNumber(VD->getLocation());
2924   unsigned Column = getColumnNumber(VD->getLocation());
2925 
2926   const llvm::DataLayout &target = CGM.getDataLayout();
2927 
2928   CharUnits offset = CharUnits::fromQuantity(
2929     target.getStructLayout(blockInfo.StructureType)
2930           ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2931 
2932   SmallVector<llvm::Value *, 9> addr;
2933   llvm::Type *Int64Ty = CGM.Int64Ty;
2934   if (isa<llvm::AllocaInst>(Storage))
2935     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2936   addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2937   addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2938   if (isByRef) {
2939     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2940     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2941     // offset of __forwarding field
2942     offset = CGM.getContext()
2943                 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2944     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2945     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2946     addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2947     // offset of x field
2948     offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2949     addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2950   }
2951 
2952   // Create the descriptor for the variable.
2953   llvm::DIVariable D =
2954     DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2955                                    llvm::DIDescriptor(LexicalBlockStack.back()),
2956                                    VD->getName(), Unit, Line, Ty, addr);
2957 
2958   // Insert an llvm.dbg.declare into the current block.
2959   llvm::Instruction *Call =
2960     DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2961   Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2962                                         LexicalBlockStack.back()));
2963 }
2964 
2965 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2966 /// variable declaration.
2967 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2968                                            unsigned ArgNo,
2969                                            CGBuilderTy &Builder) {
2970   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2971   EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2972 }
2973 
2974 namespace {
2975   struct BlockLayoutChunk {
2976     uint64_t OffsetInBits;
2977     const BlockDecl::Capture *Capture;
2978   };
2979   bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2980     return l.OffsetInBits < r.OffsetInBits;
2981   }
2982 }
2983 
2984 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2985                                                        llvm::Value *Arg,
2986                                                        llvm::Value *LocalAddr,
2987                                                        CGBuilderTy &Builder) {
2988   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2989   ASTContext &C = CGM.getContext();
2990   const BlockDecl *blockDecl = block.getBlockDecl();
2991 
2992   // Collect some general information about the block's location.
2993   SourceLocation loc = blockDecl->getCaretLocation();
2994   llvm::DIFile tunit = getOrCreateFile(loc);
2995   unsigned line = getLineNumber(loc);
2996   unsigned column = getColumnNumber(loc);
2997 
2998   // Build the debug-info type for the block literal.
2999   getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
3000 
3001   const llvm::StructLayout *blockLayout =
3002     CGM.getDataLayout().getStructLayout(block.StructureType);
3003 
3004   SmallVector<llvm::Value*, 16> fields;
3005   fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
3006                                    blockLayout->getElementOffsetInBits(0),
3007                                    tunit, tunit));
3008   fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
3009                                    blockLayout->getElementOffsetInBits(1),
3010                                    tunit, tunit));
3011   fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
3012                                    blockLayout->getElementOffsetInBits(2),
3013                                    tunit, tunit));
3014   fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
3015                                    blockLayout->getElementOffsetInBits(3),
3016                                    tunit, tunit));
3017   fields.push_back(createFieldType("__descriptor",
3018                                    C.getPointerType(block.NeedsCopyDispose ?
3019                                         C.getBlockDescriptorExtendedType() :
3020                                         C.getBlockDescriptorType()),
3021                                    0, loc, AS_public,
3022                                    blockLayout->getElementOffsetInBits(4),
3023                                    tunit, tunit));
3024 
3025   // We want to sort the captures by offset, not because DWARF
3026   // requires this, but because we're paranoid about debuggers.
3027   SmallVector<BlockLayoutChunk, 8> chunks;
3028 
3029   // 'this' capture.
3030   if (blockDecl->capturesCXXThis()) {
3031     BlockLayoutChunk chunk;
3032     chunk.OffsetInBits =
3033       blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3034     chunk.Capture = 0;
3035     chunks.push_back(chunk);
3036   }
3037 
3038   // Variable captures.
3039   for (BlockDecl::capture_const_iterator
3040          i = blockDecl->capture_begin(), e = blockDecl->capture_end();
3041        i != e; ++i) {
3042     const BlockDecl::Capture &capture = *i;
3043     const VarDecl *variable = capture.getVariable();
3044     const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3045 
3046     // Ignore constant captures.
3047     if (captureInfo.isConstant())
3048       continue;
3049 
3050     BlockLayoutChunk chunk;
3051     chunk.OffsetInBits =
3052       blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3053     chunk.Capture = &capture;
3054     chunks.push_back(chunk);
3055   }
3056 
3057   // Sort by offset.
3058   llvm::array_pod_sort(chunks.begin(), chunks.end());
3059 
3060   for (SmallVectorImpl<BlockLayoutChunk>::iterator
3061          i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3062     uint64_t offsetInBits = i->OffsetInBits;
3063     const BlockDecl::Capture *capture = i->Capture;
3064 
3065     // If we have a null capture, this must be the C++ 'this' capture.
3066     if (!capture) {
3067       const CXXMethodDecl *method =
3068         cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3069       QualType type = method->getThisType(C);
3070 
3071       fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3072                                        offsetInBits, tunit, tunit));
3073       continue;
3074     }
3075 
3076     const VarDecl *variable = capture->getVariable();
3077     StringRef name = variable->getName();
3078 
3079     llvm::DIType fieldType;
3080     if (capture->isByRef()) {
3081       std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3082 
3083       // FIXME: this creates a second copy of this type!
3084       uint64_t xoffset;
3085       fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3086       fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3087       fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3088                                             ptrInfo.first, ptrInfo.second,
3089                                             offsetInBits, 0, fieldType);
3090     } else {
3091       fieldType = createFieldType(name, variable->getType(), 0,
3092                                   loc, AS_public, offsetInBits, tunit, tunit);
3093     }
3094     fields.push_back(fieldType);
3095   }
3096 
3097   SmallString<36> typeName;
3098   llvm::raw_svector_ostream(typeName)
3099     << "__block_literal_" << CGM.getUniqueBlockCount();
3100 
3101   llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3102 
3103   llvm::DIType type =
3104     DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3105                               CGM.getContext().toBits(block.BlockSize),
3106                               CGM.getContext().toBits(block.BlockAlign),
3107                               0, llvm::DIType(), fieldsArray);
3108   type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3109 
3110   // Get overall information about the block.
3111   unsigned flags = llvm::DIDescriptor::FlagArtificial;
3112   llvm::MDNode *scope = LexicalBlockStack.back();
3113 
3114   // Create the descriptor for the parameter.
3115   llvm::DIVariable debugVar =
3116     DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
3117                                  llvm::DIDescriptor(scope),
3118                                  Arg->getName(), tunit, line, type,
3119                                  CGM.getLangOpts().Optimize, flags,
3120                                  cast<llvm::Argument>(Arg)->getArgNo() + 1);
3121 
3122   if (LocalAddr) {
3123     // Insert an llvm.dbg.value into the current block.
3124     llvm::Instruction *DbgVal =
3125       DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
3126                                        Builder.GetInsertBlock());
3127     DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3128   }
3129 
3130   // Insert an llvm.dbg.declare into the current block.
3131   llvm::Instruction *DbgDecl =
3132     DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3133   DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3134 }
3135 
3136 /// If D is an out-of-class definition of a static data member of a class, find
3137 /// its corresponding in-class declaration.
3138 llvm::DIDerivedType
3139 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3140   if (!D->isStaticDataMember())
3141     return llvm::DIDerivedType();
3142   llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3143       StaticDataMemberCache.find(D->getCanonicalDecl());
3144   if (MI != StaticDataMemberCache.end()) {
3145     assert(MI->second && "Static data member declaration should still exist");
3146     return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
3147   }
3148 
3149   // If the member wasn't found in the cache, lazily construct and add it to the
3150   // type (used when a limited form of the type is emitted).
3151   llvm::DICompositeType Ctxt(
3152       getContextDescriptor(cast<Decl>(D->getDeclContext())));
3153   llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
3154   return T;
3155 }
3156 
3157 /// EmitGlobalVariable - Emit information about a global variable.
3158 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3159                                      const VarDecl *D) {
3160   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3161   // Create global variable debug descriptor.
3162   llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3163   unsigned LineNo = getLineNumber(D->getLocation());
3164 
3165   setLocation(D->getLocation());
3166 
3167   QualType T = D->getType();
3168   if (T->isIncompleteArrayType()) {
3169 
3170     // CodeGen turns int[] into int[1] so we'll do the same here.
3171     llvm::APInt ConstVal(32, 1);
3172     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3173 
3174     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3175                                               ArrayType::Normal, 0);
3176   }
3177   StringRef DeclName = D->getName();
3178   StringRef LinkageName;
3179   if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3180       && !isa<ObjCMethodDecl>(D->getDeclContext()))
3181     LinkageName = Var->getName();
3182   if (LinkageName == DeclName)
3183     LinkageName = StringRef();
3184   llvm::DIDescriptor DContext =
3185     getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
3186   llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3187       DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3188       Var->hasInternalLinkage(), Var,
3189       getOrCreateStaticDataMemberDeclarationOrNull(D));
3190   DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
3191 }
3192 
3193 /// EmitGlobalVariable - Emit information about an objective-c interface.
3194 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3195                                      ObjCInterfaceDecl *ID) {
3196   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3197   // Create global variable debug descriptor.
3198   llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3199   unsigned LineNo = getLineNumber(ID->getLocation());
3200 
3201   StringRef Name = ID->getName();
3202 
3203   QualType T = CGM.getContext().getObjCInterfaceType(ID);
3204   if (T->isIncompleteArrayType()) {
3205 
3206     // CodeGen turns int[] into int[1] so we'll do the same here.
3207     llvm::APInt ConstVal(32, 1);
3208     QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3209 
3210     T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3211                                            ArrayType::Normal, 0);
3212   }
3213 
3214   DBuilder.createGlobalVariable(Name, Unit, LineNo,
3215                                 getOrCreateType(T, Unit),
3216                                 Var->hasInternalLinkage(), Var);
3217 }
3218 
3219 /// EmitGlobalVariable - Emit global variable's debug info.
3220 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3221                                      llvm::Constant *Init) {
3222   assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3223   // Create the descriptor for the variable.
3224   llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3225   StringRef Name = VD->getName();
3226   llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3227   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3228     const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3229     assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3230     Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3231   }
3232   // Do not use DIGlobalVariable for enums.
3233   if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3234     return;
3235   llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3236       Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
3237       getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
3238   DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3239 }
3240 
3241 llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3242   if (!LexicalBlockStack.empty())
3243     return llvm::DIScope(LexicalBlockStack.back());
3244   return getContextDescriptor(D);
3245 }
3246 
3247 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3248   if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3249     return;
3250   DBuilder.createImportedModule(
3251       getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3252       getOrCreateNameSpace(UD.getNominatedNamespace()),
3253       getLineNumber(UD.getLocation()));
3254 }
3255 
3256 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3257   if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3258     return;
3259   assert(UD.shadow_size() &&
3260          "We shouldn't be codegening an invalid UsingDecl containing no decls");
3261   // Emitting one decl is sufficient - debuggers can detect that this is an
3262   // overloaded name & provide lookup for all the overloads.
3263   const UsingShadowDecl &USD = **UD.shadow_begin();
3264   if (llvm::DIDescriptor Target =
3265           getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3266     DBuilder.createImportedDeclaration(
3267         getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3268         getLineNumber(USD.getLocation()));
3269 }
3270 
3271 llvm::DIImportedEntity
3272 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3273   if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3274     return llvm::DIImportedEntity(0);
3275   llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3276   if (VH)
3277     return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3278   llvm::DIImportedEntity R(0);
3279   if (const NamespaceAliasDecl *Underlying =
3280           dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3281     // This could cache & dedup here rather than relying on metadata deduping.
3282     R = DBuilder.createImportedModule(
3283         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3284         EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3285         NA.getName());
3286   else
3287     R = DBuilder.createImportedModule(
3288         getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3289         getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3290         getLineNumber(NA.getLocation()), NA.getName());
3291   VH = R;
3292   return R;
3293 }
3294 
3295 /// getOrCreateNamesSpace - Return namespace descriptor for the given
3296 /// namespace decl.
3297 llvm::DINameSpace
3298 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3299   NSDecl = NSDecl->getCanonicalDecl();
3300   llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
3301     NameSpaceCache.find(NSDecl);
3302   if (I != NameSpaceCache.end())
3303     return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
3304 
3305   unsigned LineNo = getLineNumber(NSDecl->getLocation());
3306   llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
3307   llvm::DIDescriptor Context =
3308     getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3309   llvm::DINameSpace NS =
3310     DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3311   NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3312   return NS;
3313 }
3314 
3315 void CGDebugInfo::finalize() {
3316   for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3317          = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3318     llvm::DIType Ty, RepTy;
3319     // Verify that the debug info still exists.
3320     if (llvm::Value *V = VI->second)
3321       Ty = llvm::DIType(cast<llvm::MDNode>(V));
3322 
3323     llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3324       TypeCache.find(VI->first);
3325     if (it != TypeCache.end()) {
3326       // Verify that the debug info still exists.
3327       if (llvm::Value *V = it->second)
3328         RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3329     }
3330 
3331     if (Ty && Ty.isForwardDecl() && RepTy)
3332       Ty.replaceAllUsesWith(RepTy);
3333   }
3334 
3335   // We keep our own list of retained types, because we need to look
3336   // up the final type in the type cache.
3337   for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3338          RE = RetainedTypes.end(); RI != RE; ++RI)
3339     DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3340 
3341   DBuilder.finalize();
3342 }
3343