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