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