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