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