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