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"
50using namespace clang;
51using namespace clang::CodeGen;
52
53static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
54 auto TI = Ctx.getTypeInfo(Ty);
55 return TI.AlignIsRequired ? TI.Align : 0;
56}
57
58static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
59 return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
60}
61
62static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
63 return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
64}
65
66CGDebugInfo::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
75CGDebugInfo::~CGDebugInfo() {
76 assert(LexicalBlockStack.empty() &&
77 "Region stack mismatch, stack not empty!");
78}
79
80ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
81 SourceLocation TemporaryLocation)
82 : CGF(&CGF) {
83 init(TemporaryLocation);
84}
85
86ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
87 bool DefaultToEmpty,
88 SourceLocation TemporaryLocation)
89 : CGF(&CGF) {
90 init(TemporaryLocation, DefaultToEmpty);
91}
92
93void 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(
119 llvm::DILocation::get(DI->LexicalBlockStack.back()->getContext(), 0, 0,
120 DI->LexicalBlockStack.back(), DI->getInlinedAt()));
121}
122
123ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
124 : CGF(&CGF) {
125 init(E->getExprLoc());
126}
127
128ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
129 : CGF(&CGF) {
130 if (!CGF.getDebugInfo()) {
131 this->CGF = nullptr;
132 return;
133 }
134 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
135 if (Loc)
136 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
137}
138
139ApplyDebugLocation::~ApplyDebugLocation() {
140 // Query CGF so the location isn't overwritten when location updates are
141 // temporarily disabled (for C++ default function arguments)
142 if (CGF)
143 CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
144}
145
146ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,
147 GlobalDecl InlinedFn)
148 : CGF(&CGF) {
149 if (!CGF.getDebugInfo()) {
150 this->CGF = nullptr;
151 return;
152 }
153 auto &DI = *CGF.getDebugInfo();
154 SavedLocation = DI.getLocation();
155 assert((DI.getInlinedAt() ==
156 CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
157 "CGDebugInfo and IRBuilder are out of sync");
158
159 DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
160}
161
162ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
163 if (!CGF)
164 return;
165 auto &DI = *CGF->getDebugInfo();
166 DI.EmitInlineFunctionEnd(CGF->Builder);
167 DI.EmitLocation(CGF->Builder, SavedLocation);
168}
169
170void CGDebugInfo::setLocation(SourceLocation Loc) {
171 // If the new location isn't valid return.
172 if (Loc.isInvalid())
173 return;
174
175 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
176
177 // If we've changed files in the middle of a lexical scope go ahead
178 // and create a new lexical scope with file node if it's different
179 // from the one in the scope.
180 if (LexicalBlockStack.empty())
181 return;
182
183 SourceManager &SM = CGM.getContext().getSourceManager();
184 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
185 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
186 if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
187 return;
188
189 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
190 LexicalBlockStack.pop_back();
191 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
192 LBF->getScope(), getOrCreateFile(CurLoc)));
193 } else if (isa<llvm::DILexicalBlock>(Scope) ||
194 isa<llvm::DISubprogram>(Scope)) {
195 LexicalBlockStack.pop_back();
196 LexicalBlockStack.emplace_back(
197 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
198 }
199}
200
201llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
202 llvm::DIScope *Mod = getParentModuleOrNull(D);
203 return getContextDescriptor(cast<Decl>(D->getDeclContext()),
204 Mod ? Mod : TheCU);
205}
206
207llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
208 llvm::DIScope *Default) {
209 if (!Context)
210 return Default;
211
212 auto I = RegionMap.find(Context);
213 if (I != RegionMap.end()) {
214 llvm::Metadata *V = I->second;
215 return dyn_cast_or_null<llvm::DIScope>(V);
216 }
217
218 // Check namespace.
219 if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
220 return getOrCreateNamespace(NSDecl);
221
222 if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
223 if (!RDecl->isDependentType())
224 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
225 TheCU->getFile());
226 return Default;
227}
228
229PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
230 PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
231
232 // If we're emitting codeview, it's important to try to match MSVC's naming so
233 // that visualizers written for MSVC will trigger for our class names. In
234 // particular, we can't have spaces between arguments of standard templates
235 // like basic_string and vector, but we must have spaces between consecutive
236 // angle brackets that close nested template argument lists.
237 if (CGM.getCodeGenOpts().EmitCodeView) {
238 PP.MSVCFormatting = true;
239 PP.SplitTemplateClosers = true;
240 } else {
241 // For DWARF, printing rules are underspecified.
242 // SplitTemplateClosers yields better interop with GCC and GDB (PR46052).
243 PP.SplitTemplateClosers = true;
244 }
245
246 // Apply -fdebug-prefix-map.
247 PP.Callbacks = &PrintCB;
248 return PP;
249}
250
251StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
252 assert(FD && "Invalid FunctionDecl!");
253 IdentifierInfo *FII = FD->getIdentifier();
254 FunctionTemplateSpecializationInfo *Info =
255 FD->getTemplateSpecializationInfo();
256
257 if (!Info && FII)
258 return FII->getName();
259
260 SmallString<128> NS;
261 llvm::raw_svector_ostream OS(NS);
262 FD->printName(OS);
263
264 // Add any template specialization args.
265 if (Info) {
266 const TemplateArgumentList *TArgs = Info->TemplateArguments;
267 printTemplateArgumentList(OS, TArgs->asArray(), getPrintingPolicy());
268 }
269
270 // Copy this name on the side and use its reference.
271 return internString(OS.str());
272}
273
274StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
275 SmallString<256> MethodName;
276 llvm::raw_svector_ostream OS(MethodName);
277 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
278 const DeclContext *DC = OMD->getDeclContext();
279 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
280 OS << OID->getName();
281 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
282 OS << OID->getName();
283 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
284 if (OC->IsClassExtension()) {
285 OS << OC->getClassInterface()->getName();
286 } else {
287 OS << OC->getIdentifier()->getNameStart() << '('
288 << OC->getIdentifier()->getNameStart() << ')';
289 }
290 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
291 OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
292 }
293 OS << ' ' << OMD->getSelector().getAsString() << ']';
294
295 return internString(OS.str());
296}
297
298StringRef CGDebugInfo::getSelectorName(Selector S) {
299 return internString(S.getAsString());
300}
301
302StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
303 if (isa<ClassTemplateSpecializationDecl>(RD)) {
304 SmallString<128> Name;
305 llvm::raw_svector_ostream OS(Name);
306 PrintingPolicy PP = getPrintingPolicy();
307 PP.PrintCanonicalTypes = true;
308 PP.SuppressInlineNamespace = false;
309 RD->getNameForDiagnostic(OS, PP,
310 /*Qualified*/ false);
311
312 // Copy this name on the side and use its reference.
313 return internString(Name);
314 }
315
316 // quick optimization to avoid having to intern strings that are already
317 // stored reliably elsewhere
318 if (const IdentifierInfo *II = RD->getIdentifier())
319 return II->getName();
320
321 // The CodeView printer in LLVM wants to see the names of unnamed types
322 // because they need to have a unique identifier.
323 // These names are used to reconstruct the fully qualified type names.
324 if (CGM.getCodeGenOpts().EmitCodeView) {
325 if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
326 assert(RD->getDeclContext() == D->getDeclContext() &&
327 "Typedef should not be in another decl context!");
328 assert(D->getDeclName().getAsIdentifierInfo() &&
329 "Typedef was not named!");
330 return D->getDeclName().getAsIdentifierInfo()->getName();
331 }
332
333 if (CGM.getLangOpts().CPlusPlus) {
334 StringRef Name;
335
336 ASTContext &Context = CGM.getContext();
337 if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
338 // Anonymous types without a name for linkage purposes have their
339 // declarator mangled in if they have one.
340 Name = DD->getName();
341 else if (const TypedefNameDecl *TND =
342 Context.getTypedefNameForUnnamedTagDecl(RD))
343 // Anonymous types without a name for linkage purposes have their
344 // associate typedef mangled in if they have one.
345 Name = TND->getName();
346
347 // Give lambdas a display name based on their name mangling.
348 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
349 if (CXXRD->isLambda())
350 return internString(
351 CGM.getCXXABI().getMangleContext().getLambdaString(CXXRD));
352
353 if (!Name.empty()) {
354 SmallString<256> UnnamedType("<unnamed-type-");
355 UnnamedType += Name;
356 UnnamedType += '>';
357 return internString(UnnamedType);
358 }
359 }
360 }
361
362 return StringRef();
363}
364
365Optional<llvm::DIFile::ChecksumKind>
366CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
367 Checksum.clear();
368
369 if (!CGM.getCodeGenOpts().EmitCodeView &&
370 CGM.getCodeGenOpts().DwarfVersion < 5)
371 return None;
372
373 SourceManager &SM = CGM.getContext().getSourceManager();
374 Optional<llvm::MemoryBufferRef> MemBuffer = SM.getBufferOrNone(FID);
375 if (!MemBuffer)
376 return None;
377
378 llvm::MD5 Hash;
379 llvm::MD5::MD5Result Result;
380
381 Hash.update(MemBuffer->getBuffer());
382 Hash.final(Result);
383
384 Hash.stringifyResult(Result, Checksum);
385 return llvm::DIFile::CSK_MD5;
386}
387
388Optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
389 FileID FID) {
390 if (!CGM.getCodeGenOpts().EmbedSource)
391 return None;
392
393 bool SourceInvalid = false;
394 StringRef Source = SM.getBufferData(FID, &SourceInvalid);
395
396 if (SourceInvalid)
397 return None;
398
399 return Source;
400}
401
402llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
403 SourceManager &SM = CGM.getContext().getSourceManager();
404 StringRef FileName;
405 FileID FID;
406
407 if (Loc.isInvalid()) {
408 // The DIFile used by the CU is distinct from the main source file. Call
409 // createFile() below for canonicalization if the source file was specified
410 // with an absolute path.
411 FileName = TheCU->getFile()->getFilename();
412 } else {
413 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
414 FileName = PLoc.getFilename();
415
416 if (FileName.empty()) {
417 FileName = TheCU->getFile()->getFilename();
418 } else {
419 FileName = PLoc.getFilename();
420 }
421 FID = PLoc.getFileID();
422 }
423
424 // Cache the results.
425 auto It = DIFileCache.find(FileName.data());
426 if (It != DIFileCache.end()) {
427 // Verify that the information still exists.
428 if (llvm::Metadata *V = It->second)
429 return cast<llvm::DIFile>(V);
430 }
431
432 SmallString<32> Checksum;
433
434 Optional<llvm::DIFile::ChecksumKind> CSKind = computeChecksum(FID, Checksum);
435 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
436 if (CSKind)
437 CSInfo.emplace(*CSKind, Checksum);
438 return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));
439}
440
441llvm::DIFile *
442CGDebugInfo::createFile(StringRef FileName,
443 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
444 Optional<StringRef> Source) {
445 StringRef Dir;
446 StringRef File;
447 std::string RemappedFile = remapDIPath(FileName);
448 std::string CurDir = remapDIPath(getCurrentDirname());
449 SmallString<128> DirBuf;
450 SmallString<128> FileBuf;
451 if (llvm::sys::path::is_absolute(RemappedFile)) {
452 // Strip the common prefix (if it is more than just "/") from current
453 // directory and FileName for a more space-efficient encoding.
454 auto FileIt = llvm::sys::path::begin(RemappedFile);
455 auto FileE = llvm::sys::path::end(RemappedFile);
456 auto CurDirIt = llvm::sys::path::begin(CurDir);
457 auto CurDirE = llvm::sys::path::end(CurDir);
458 for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
459 llvm::sys::path::append(DirBuf, *CurDirIt);
460 if (std::distance(llvm::sys::path::begin(CurDir), CurDirIt) == 1) {
461 // Don't strip the common prefix if it is only the root "/"
462 // since that would make LLVM diagnostic locations confusing.
463 Dir = {};
464 File = RemappedFile;
465 } else {
466 for (; FileIt != FileE; ++FileIt)
467 llvm::sys::path::append(FileBuf, *FileIt);
468 Dir = DirBuf;
469 File = FileBuf;
470 }
471 } else {
472 Dir = CurDir;
473 File = RemappedFile;
474 }
475 llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
476 DIFileCache[FileName.data()].reset(F);
477 return F;
478}
479
480std::string CGDebugInfo::remapDIPath(StringRef Path) const {
481 if (DebugPrefixMap.empty())
482 return Path.str();
483
484 SmallString<256> P = Path;
485 for (const auto &Entry : DebugPrefixMap)
486 if (llvm::sys::path::replace_path_prefix(P, Entry.first, Entry.second))
487 break;
488 return P.str().str();
489}
490
491unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
492 if (Loc.isInvalid())
493 return 0;
494 SourceManager &SM = CGM.getContext().getSourceManager();
495 return SM.getPresumedLoc(Loc).getLine();
496}
497
498unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
499 // We may not want column information at all.
500 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
501 return 0;
502
503 // If the location is invalid then use the current column.
504 if (Loc.isInvalid() && CurLoc.isInvalid())
505 return 0;
506 SourceManager &SM = CGM.getContext().getSourceManager();
507 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
508 return PLoc.isValid() ? PLoc.getColumn() : 0;
509}
510
511StringRef CGDebugInfo::getCurrentDirname() {
512 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
513 return CGM.getCodeGenOpts().DebugCompilationDir;
514
515 if (!CWDName.empty())
516 return CWDName;
517 SmallString<256> CWD;
518 llvm::sys::fs::current_path(CWD);
519 return CWDName = internString(CWD);
520}
521
522void CGDebugInfo::CreateCompileUnit() {
523 SmallString<32> Checksum;
524 Optional<llvm::DIFile::ChecksumKind> CSKind;
525 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
526
527 // Should we be asking the SourceManager for the main file name, instead of
528 // accepting it as an argument? This just causes the main file name to
529 // mismatch with source locations and create extra lexical scopes or
530 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
531 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
532 // because that's what the SourceManager says)
533
534 // Get absolute path name.
535 SourceManager &SM = CGM.getContext().getSourceManager();
536 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
537 if (MainFileName.empty())
538 MainFileName = "<stdin>";
539
540 // The main file name provided via the "-main-file-name" option contains just
541 // the file name itself with no path information. This file name may have had
542 // a relative path, so we look into the actual file entry for the main
543 // file to determine the real absolute path for the file.
544 std::string MainFileDir;
545 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
546 MainFileDir = std::string(MainFile->getDir()->getName());
547 if (!llvm::sys::path::is_absolute(MainFileName)) {
548 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
549 llvm::sys::path::append(MainFileDirSS, MainFileName);
550 MainFileName =
551 std::string(llvm::sys::path::remove_leading_dotslash(MainFileDirSS));
552 }
553 // If the main file name provided is identical to the input file name, and
554 // if the input file is a preprocessed source, use the module name for
555 // debug info. The module name comes from the name specified in the first
556 // linemarker if the input is a preprocessed source.
557 if (MainFile->getName() == MainFileName &&
558 FrontendOptions::getInputKindForExtension(
559 MainFile->getName().rsplit('.').second)
560 .isPreprocessed())
561 MainFileName = CGM.getModule().getName().str();
562
563 CSKind = computeChecksum(SM.getMainFileID(), Checksum);
564 }
565
566 llvm::dwarf::SourceLanguage LangTag;
567 const LangOptions &LO = CGM.getLangOpts();
568 if (LO.CPlusPlus) {
569 if (LO.ObjC)
570 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
571 else if (LO.CPlusPlus14 && CGM.getCodeGenOpts().DwarfVersion >= 5)
572 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
573 else if (LO.CPlusPlus11 && CGM.getCodeGenOpts().DwarfVersion >= 5)
574 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
575 else
576 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
577 } else if (LO.ObjC) {
578 LangTag = llvm::dwarf::DW_LANG_ObjC;
579 } else if (LO.RenderScript) {
580 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
581 } else if (LO.C99) {
582 LangTag = llvm::dwarf::DW_LANG_C99;
583 } else {
584 LangTag = llvm::dwarf::DW_LANG_C89;
585 }
586
587 std::string Producer = getClangFullVersion();
588
589 // Figure out which version of the ObjC runtime we have.
590 unsigned RuntimeVers = 0;
591 if (LO.ObjC)
592 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
593
594 llvm::DICompileUnit::DebugEmissionKind EmissionKind;
595 switch (DebugKind) {
596 case codegenoptions::NoDebugInfo:
597 case codegenoptions::LocTrackingOnly:
598 EmissionKind = llvm::DICompileUnit::NoDebug;
599 break;
600 case codegenoptions::DebugLineTablesOnly:
601 EmissionKind = llvm::DICompileUnit::LineTablesOnly;
602 break;
603 case codegenoptions::DebugDirectivesOnly:
604 EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
605 break;
606 case codegenoptions::DebugInfoConstructor:
607 case codegenoptions::LimitedDebugInfo:
608 case codegenoptions::FullDebugInfo:
609 case codegenoptions::UnusedTypeInfo:
610 EmissionKind = llvm::DICompileUnit::FullDebug;
611 break;
612 }
613
614 uint64_t DwoId = 0;
615 auto &CGOpts = CGM.getCodeGenOpts();
616 // The DIFile used by the CU is distinct from the main source
617 // file. Its directory part specifies what becomes the
618 // DW_AT_comp_dir (the compilation directory), even if the source
619 // file was specified with an absolute path.
620 if (CSKind)
621 CSInfo.emplace(*CSKind, Checksum);
622 llvm::DIFile *CUFile = DBuilder.createFile(
623 remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
624 getSource(SM, SM.getMainFileID()));
625
626 StringRef Sysroot, SDK;
627 if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
628 Sysroot = CGM.getHeaderSearchOpts().Sysroot;
629 auto B = llvm::sys::path::rbegin(Sysroot);
630 auto E = llvm::sys::path::rend(Sysroot);
631 auto It = std::find_if(B, E, [](auto SDK) { return SDK.endswith(".sdk"); });
632 if (It != E)
633 SDK = *It;
634 }
635
636 // Create new compile unit.
637 TheCU = DBuilder.createCompileUnit(
638 LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
639 LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
640 CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
641 DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
642 CGM.getTarget().getTriple().isNVPTX()
643 ? llvm::DICompileUnit::DebugNameTableKind::None
644 : static_cast<llvm::DICompileUnit::DebugNameTableKind>(
645 CGOpts.DebugNameTable),
646 CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
647}
648
649llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
650 llvm::dwarf::TypeKind Encoding;
651 StringRef BTName;
652 switch (BT->getKind()) {
653#define BUILTIN_TYPE(Id, SingletonId)
654#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
655#include "clang/AST/BuiltinTypes.def"
656 case BuiltinType::Dependent:
657 llvm_unreachable("Unexpected builtin type");
658 case BuiltinType::NullPtr:
659 return DBuilder.createNullPtrType();
660 case BuiltinType::Void:
661 return nullptr;
662 case BuiltinType::ObjCClass:
663 if (!ClassTy)
664 ClassTy =
665 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
666 "objc_class", TheCU, TheCU->getFile(), 0);
667 return ClassTy;
668 case BuiltinType::ObjCId: {
669 // typedef struct objc_class *Class;
670 // typedef struct objc_object {
671 // Class isa;
672 // } *id;
673
674 if (ObjTy)
675 return ObjTy;
676
677 if (!ClassTy)
678 ClassTy =
679 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
680 "objc_class", TheCU, TheCU->getFile(), 0);
681
682 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
683
684 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
685
686 ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
687 0, 0, llvm::DINode::FlagZero, nullptr,
688 llvm::DINodeArray());
689
690 DBuilder.replaceArrays(
691 ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
692 ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
693 llvm::DINode::FlagZero, ISATy)));
694 return ObjTy;
695 }
696 case BuiltinType::ObjCSel: {
697 if (!SelTy)
698 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
699 "objc_selector", TheCU,
700 TheCU->getFile(), 0);
701 return SelTy;
702 }
703
704#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
705 case BuiltinType::Id: \
706 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
707 SingletonId);
708#include "clang/Basic/OpenCLImageTypes.def"
709 case BuiltinType::OCLSampler:
710 return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
711 case BuiltinType::OCLEvent:
712 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
713 case BuiltinType::OCLClkEvent:
714 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
715 case BuiltinType::OCLQueue:
716 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
717 case BuiltinType::OCLReserveID:
718 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
719#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
720 case BuiltinType::Id: \
721 return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
722#include "clang/Basic/OpenCLExtensionTypes.def"
723
724#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
725#include "clang/Basic/AArch64SVEACLETypes.def"
726 {
727 ASTContext::BuiltinVectorTypeInfo Info =
728 CGM.getContext().getBuiltinVectorTypeInfo(BT);
729 unsigned NumElemsPerVG = (Info.EC.getKnownMinValue() * Info.NumVectors) / 2;
730
731 // Debuggers can't extract 1bit from a vector, so will display a
732 // bitpattern for svbool_t instead.
733 if (Info.ElementType == CGM.getContext().BoolTy) {
734 NumElemsPerVG /= 8;
735 Info.ElementType = CGM.getContext().UnsignedCharTy;
736 }
737
738 auto *LowerBound =
739 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
740 llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
741 SmallVector<int64_t, 9> Expr(
742 {llvm::dwarf::DW_OP_constu, NumElemsPerVG, llvm::dwarf::DW_OP_bregx,
743 /* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul,
744 llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
745 auto *UpperBound = DBuilder.createExpression(Expr);
746
747 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
748 /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
749 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
750 llvm::DIType *ElemTy =
751 getOrCreateType(Info.ElementType, TheCU->getFile());
752 auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
753 return DBuilder.createVectorType(/*Size*/ 0, Align, ElemTy,
754 SubscriptArray);
755 }
756 // It doesn't make sense to generate debug info for PowerPC MMA vector types.
757 // So we return a safe type here to avoid generating an error.
758#define PPC_VECTOR_TYPE(Name, Id, size) \
759 case BuiltinType::Id:
760#include "clang/Basic/PPCTypes.def"
761 return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
762
763#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
764#include "clang/Basic/RISCVVTypes.def"
765 {
766 ASTContext::BuiltinVectorTypeInfo Info =
767 CGM.getContext().getBuiltinVectorTypeInfo(BT);
768
769 unsigned ElementCount = Info.EC.getKnownMinValue();
770 unsigned SEW = CGM.getContext().getTypeSize(Info.ElementType);
771
772 bool Fractional = false;
773 unsigned LMUL;
774 unsigned FixedSize = ElementCount * SEW;
775 if (Info.ElementType == CGM.getContext().BoolTy) {
776 // Mask type only occupies one vector register.
777 LMUL = 1;
778 } else if (FixedSize < 64) {
779 // In RVV scalable vector types, we encode 64 bits in the fixed part.
780 Fractional = true;
781 LMUL = 64 / FixedSize;
782 } else {
783 LMUL = FixedSize / 64;
784 }
785
786 // Element count = (VLENB / SEW) x LMUL
787 SmallVector<int64_t, 9> Expr(
788 // The DW_OP_bregx operation has two operands: a register which is
789 // specified by an unsigned LEB128 number, followed by a signed LEB128
790 // offset.
791 {llvm::dwarf::DW_OP_bregx, // Read the contents of a register.
792 4096 + 0xC22, // RISC-V VLENB CSR register.
793 0, // Offset for DW_OP_bregx. It is dummy here.
794 llvm::dwarf::DW_OP_constu,
795 SEW / 8, // SEW is in bits.
796 llvm::dwarf::DW_OP_div, llvm::dwarf::DW_OP_constu, LMUL});
797 if (Fractional)
798 Expr.push_back(llvm::dwarf::DW_OP_div);
799 else
800 Expr.push_back(llvm::dwarf::DW_OP_mul);
801
802 auto *LowerBound =
803 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
804 llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
805 auto *UpperBound = DBuilder.createExpression(Expr);
806 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
807 /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
808 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
809 llvm::DIType *ElemTy =
810 getOrCreateType(Info.ElementType, TheCU->getFile());
811
812 auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
813 return DBuilder.createVectorType(/*Size=*/0, Align, ElemTy,
814 SubscriptArray);
815 }
816 case BuiltinType::UChar:
817 case BuiltinType::Char_U:
818 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
819 break;
820 case BuiltinType::Char_S:
821 case BuiltinType::SChar:
822 Encoding = llvm::dwarf::DW_ATE_signed_char;
823 break;
824 case BuiltinType::Char8:
825 case BuiltinType::Char16:
826 case BuiltinType::Char32:
827 Encoding = llvm::dwarf::DW_ATE_UTF;
828 break;
829 case BuiltinType::UShort:
830 case BuiltinType::UInt:
831 case BuiltinType::UInt128:
832 case BuiltinType::ULong:
833 case BuiltinType::WChar_U:
834 case BuiltinType::ULongLong:
835 Encoding = llvm::dwarf::DW_ATE_unsigned;
836 break;
837 case BuiltinType::Short:
838 case BuiltinType::Int:
839 case BuiltinType::Int128:
840 case BuiltinType::Long:
841 case BuiltinType::WChar_S:
842 case BuiltinType::LongLong:
843 Encoding = llvm::dwarf::DW_ATE_signed;
844 break;
845 case BuiltinType::Bool:
846 Encoding = llvm::dwarf::DW_ATE_boolean;
847 break;
848 case BuiltinType::Half:
849 case BuiltinType::Float:
850 case BuiltinType::LongDouble:
851 case BuiltinType::Float16:
852 case BuiltinType::BFloat16:
853 case BuiltinType::Float128:
854 case BuiltinType::Double:
855 // FIXME: For targets where long double and __float128 have the same size,
856 // they are currently indistinguishable in the debugger without some
857 // special treatment. However, there is currently no consensus on encoding
858 // and this should be updated once a DWARF encoding exists for distinct
859 // floating point types of the same size.
860 Encoding = llvm::dwarf::DW_ATE_float;
861 break;
862 case BuiltinType::ShortAccum:
863 case BuiltinType::Accum:
864 case BuiltinType::LongAccum:
865 case BuiltinType::ShortFract:
866 case BuiltinType::Fract:
867 case BuiltinType::LongFract:
868 case BuiltinType::SatShortFract:
869 case BuiltinType::SatFract:
870 case BuiltinType::SatLongFract:
871 case BuiltinType::SatShortAccum:
872 case BuiltinType::SatAccum:
873 case BuiltinType::SatLongAccum:
874 Encoding = llvm::dwarf::DW_ATE_signed_fixed;
875 break;
876 case BuiltinType::UShortAccum:
877 case BuiltinType::UAccum:
878 case BuiltinType::ULongAccum:
879 case BuiltinType::UShortFract:
880 case BuiltinType::UFract:
881 case BuiltinType::ULongFract:
882 case BuiltinType::SatUShortAccum:
883 case BuiltinType::SatUAccum:
884 case BuiltinType::SatULongAccum:
885 case BuiltinType::SatUShortFract:
886 case BuiltinType::SatUFract:
887 case BuiltinType::SatULongFract:
888 Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
889 break;
890 }
891
892 switch (BT->getKind()) {
893 case BuiltinType::Long:
894 BTName = "long int";
895 break;
896 case BuiltinType::LongLong:
897 BTName = "long long int";
898 break;
899 case BuiltinType::ULong:
900 BTName = "long unsigned int";
901 break;
902 case BuiltinType::ULongLong:
903 BTName = "long long unsigned int";
904 break;
905 default:
906 BTName = BT->getName(CGM.getLangOpts());
907 break;
908 }
909 // Bit size and offset of the type.
910 uint64_t Size = CGM.getContext().getTypeSize(BT);
911 return DBuilder.createBasicType(BTName, Size, Encoding);
912}
913
914llvm::DIType *CGDebugInfo::CreateType(const AutoType *Ty) {
915 return DBuilder.createUnspecifiedType("auto");
916}
917
918llvm::DIType *CGDebugInfo::CreateType(const ExtIntType *Ty) {
919
920 StringRef Name = Ty->isUnsigned() ? "unsigned _ExtInt" : "_ExtInt";
921 llvm::dwarf::TypeKind Encoding = Ty->isUnsigned()
922 ? llvm::dwarf::DW_ATE_unsigned
923 : llvm::dwarf::DW_ATE_signed;
924
925 return DBuilder.createBasicType(Name, CGM.getContext().getTypeSize(Ty),
926 Encoding);
927}
928
929llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
930 // Bit size and offset of the type.
931 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
932 if (Ty->isComplexIntegerType())
933 Encoding = llvm::dwarf::DW_ATE_lo_user;
934
935 uint64_t Size = CGM.getContext().getTypeSize(Ty);
936 return DBuilder.createBasicType("complex", Size, Encoding);
937}
938
939llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
940 llvm::DIFile *Unit) {
941 QualifierCollector Qc;
942 const Type *T = Qc.strip(Ty);
943
944 // Ignore these qualifiers for now.
945 Qc.removeObjCGCAttr();
946 Qc.removeAddressSpace();
947 Qc.removeObjCLifetime();
948
949 // We will create one Derived type for one qualifier and recurse to handle any
950 // additional ones.
951 llvm::dwarf::Tag Tag;
952 if (Qc.hasConst()) {
953 Tag = llvm::dwarf::DW_TAG_const_type;
954 Qc.removeConst();
955 } else if (Qc.hasVolatile()) {
956 Tag = llvm::dwarf::DW_TAG_volatile_type;
957 Qc.removeVolatile();
958 } else if (Qc.hasRestrict()) {
959 Tag = llvm::dwarf::DW_TAG_restrict_type;
960 Qc.removeRestrict();
961 } else {
962 assert(Qc.empty() && "Unknown type qualifier for debug info");
963 return getOrCreateType(QualType(T, 0), Unit);
964 }
965
966 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
967
968 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
969 // CVR derived types.
970 return DBuilder.createQualifiedType(Tag, FromTy);
971}
972
973llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
974 llvm::DIFile *Unit) {
975
976 // The frontend treats 'id' as a typedef to an ObjCObjectType,
977 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
978 // debug info, we want to emit 'id' in both cases.
979 if (Ty->isObjCQualifiedIdType())
980 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
981
982 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
983 Ty->getPointeeType(), Unit);
984}
985
986llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
987 llvm::DIFile *Unit) {
988 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
989 Ty->getPointeeType(), Unit);
990}
991
992/// \return whether a C++ mangling exists for the type defined by TD.
993static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
994 switch (TheCU->getSourceLanguage()) {
995 case llvm::dwarf::DW_LANG_C_plus_plus:
996 case llvm::dwarf::DW_LANG_C_plus_plus_11:
997 case llvm::dwarf::DW_LANG_C_plus_plus_14:
998 return true;
999 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
1000 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
1001 default:
1002 return false;
1003 }
1004}
1005
1006// Determines if the debug info for this tag declaration needs a type
1007// identifier. The purpose of the unique identifier is to deduplicate type
1008// information for identical types across TUs. Because of the C++ one definition
1009// rule (ODR), it is valid to assume that the type is defined the same way in
1010// every TU and its debug info is equivalent.
1011//
1012// C does not have the ODR, and it is common for codebases to contain multiple
1013// different definitions of a struct with the same name in different TUs.
1014// Therefore, if the type doesn't have a C++ mangling, don't give it an
1015// identifer. Type information in C is smaller and simpler than C++ type
1016// information, so the increase in debug info size is negligible.
1017//
1018// If the type is not externally visible, it should be unique to the current TU,
1019// and should not need an identifier to participate in type deduplication.
1020// However, when emitting CodeView, the format internally uses these
1021// unique type name identifers for references between debug info. For example,
1022// the method of a class in an anonymous namespace uses the identifer to refer
1023// to its parent class. The Microsoft C++ ABI attempts to provide unique names
1024// for such types, so when emitting CodeView, always use identifiers for C++
1025// types. This may create problems when attempting to emit CodeView when the MS
1026// C++ ABI is not in use.
1027static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
1028 llvm::DICompileUnit *TheCU) {
1029 // We only add a type identifier for types with C++ name mangling.
1030 if (!hasCXXMangling(TD, TheCU))
1031 return false;
1032
1033 // Externally visible types with C++ mangling need a type identifier.
1034 if (TD->isExternallyVisible())
1035 return true;
1036
1037 // CodeView types with C++ mangling need a type identifier.
1038 if (CGM.getCodeGenOpts().EmitCodeView)
1039 return true;
1040
1041 return false;
1042}
1043
1044// Returns a unique type identifier string if one exists, or an empty string.
1045static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
1046 llvm::DICompileUnit *TheCU) {
1047 SmallString<256> Identifier;
1048 const TagDecl *TD = Ty->getDecl();
1049
1050 if (!needsTypeIdentifier(TD, CGM, TheCU))
1051 return Identifier;
1052 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
1053 if (RD->getDefinition())
1054 if (RD->isDynamicClass() &&
1055 CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
1056 return Identifier;
1057
1058 // TODO: This is using the RTTI name. Is there a better way to get
1059 // a unique string for a type?
1060 llvm::raw_svector_ostream Out(Identifier);
1061 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
1062 return Identifier;
1063}
1064
1065/// \return the appropriate DWARF tag for a composite type.
1066static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
1067 llvm::dwarf::Tag Tag;
1068 if (RD->isStruct() || RD->isInterface())
1069 Tag = llvm::dwarf::DW_TAG_structure_type;
1070 else if (RD->isUnion())
1071 Tag = llvm::dwarf::DW_TAG_union_type;
1072 else {
1073 // FIXME: This could be a struct type giving a default visibility different
1074 // than C++ class type, but needs llvm metadata changes first.
1075 assert(RD->isClass());
1076 Tag = llvm::dwarf::DW_TAG_class_type;
1077 }
1078 return Tag;
1079}
1080
1081llvm::DICompositeType *
1082CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
1083 llvm::DIScope *Ctx) {
1084 const RecordDecl *RD = Ty->getDecl();
1085 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
1086 return cast<llvm::DICompositeType>(T);
1087 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1088 const unsigned Line =
1089 getLineNumber(RD->getLocation().isValid() ? RD->getLocation() : CurLoc);
1090 StringRef RDName = getClassName(RD);
1091
1092 uint64_t Size = 0;
1093 uint32_t Align = 0;
1094
1095 const RecordDecl *D = RD->getDefinition();
1096 if (D && D->isCompleteDefinition())
1097 Size = CGM.getContext().getTypeSize(Ty);
1098
1099 llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl;
1100
1101 // Add flag to nontrivial forward declarations. To be consistent with MSVC,
1102 // add the flag if a record has no definition because we don't know whether
1103 // it will be trivial or not.
1104 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1105 if (!CXXRD->hasDefinition() ||
1106 (CXXRD->hasDefinition() && !CXXRD->isTrivial()))
1107 Flags |= llvm::DINode::FlagNonTrivial;
1108
1109 // Create the type.
1110 SmallString<256> Identifier;
1111 // Don't include a linkage name in line tables only.
1112 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
1113 Identifier = getTypeIdentifier(Ty, CGM, TheCU);
1114 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
1115 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags,
1116 Identifier);
1117 if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
1118 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1119 DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
1120 CollectCXXTemplateParams(TSpecial, DefUnit));
1121 ReplaceMap.emplace_back(
1122 std::piecewise_construct, std::make_tuple(Ty),
1123 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
1124 return RetTy;
1125}
1126
1127llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
1128 const Type *Ty,
1129 QualType PointeeTy,
1130 llvm::DIFile *Unit) {
1131 // Bit size, align and offset of the type.
1132 // Size is always the size of a pointer. We can't use getTypeSize here
1133 // because that does not return the correct value for references.
1134 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
1135 uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
1136 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
1137 Optional<unsigned> DWARFAddressSpace =
1138 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
1139
1140 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1141 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
1142 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
1143 Size, Align, DWARFAddressSpace);
1144 else
1145 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
1146 Align, DWARFAddressSpace);
1147}
1148
1149llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1150 llvm::DIType *&Cache) {
1151 if (Cache)
1152 return Cache;
1153 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
1154 TheCU, TheCU->getFile(), 0);
1155 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1156 Cache = DBuilder.createPointerType(Cache, Size);
1157 return Cache;
1158}
1159
1160uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1161 const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1162 unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
1163 QualType FType;
1164
1165 // Advanced by calls to CreateMemberType in increments of FType, then
1166 // returned as the overall size of the default elements.
1167 uint64_t FieldOffset = 0;
1168
1169 // Blocks in OpenCL have unique constraints which make the standard fields
1170 // redundant while requiring size and align fields for enqueue_kernel. See
1171 // initializeForBlockHeader in CGBlocks.cpp
1172 if (CGM.getLangOpts().OpenCL) {
1173 FType = CGM.getContext().IntTy;
1174 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1175 EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1176 } else {
1177 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1178 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1179 FType = CGM.getContext().IntTy;
1180 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1181 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1182 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1183 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1184 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1185 uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1186 uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
1187 EltTys.push_back(DBuilder.createMemberType(
1188 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1189 FieldOffset, llvm::DINode::FlagZero, DescTy));
1190 FieldOffset += FieldSize;
1191 }
1192
1193 return FieldOffset;
1194}
1195
1196llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1197 llvm::DIFile *Unit) {
1198 SmallVector<llvm::Metadata *, 8> EltTys;
1199 QualType FType;
1200 uint64_t FieldOffset;
1201 llvm::DINodeArray Elements;
1202
1203 FieldOffset = 0;
1204 FType = CGM.getContext().UnsignedLongTy;
1205 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1206 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1207
1208 Elements = DBuilder.getOrCreateArray(EltTys);
1209 EltTys.clear();
1210
1211 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1212
1213 auto *EltTy =
1214 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1215 FieldOffset, 0, Flags, nullptr, Elements);
1216
1217 // Bit size, align and offset of the type.
1218 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1219
1220 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1221
1222 FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1223 0, EltTys);
1224
1225 Elements = DBuilder.getOrCreateArray(EltTys);
1226
1227 // The __block_literal_generic structs are marked with a special
1228 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1229 // the debugger needs to know about. To allow type uniquing, emit
1230 // them without a name or a location.
1231 EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
1232 Flags, nullptr, Elements);
1233
1234 return DBuilder.createPointerType(EltTy, Size);
1235}
1236
1237llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1238 llvm::DIFile *Unit) {
1239 assert(Ty->isTypeAlias());
1240 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1241
1242 auto *AliasDecl =
1243 cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
1244 ->getTemplatedDecl();
1245
1246 if (AliasDecl->hasAttr<NoDebugAttr>())
1247 return Src;
1248
1249 SmallString<128> NS;
1250 llvm::raw_svector_ostream OS(NS);
1251 Ty->getTemplateName().print(OS, getPrintingPolicy(), /*qualified*/ false);
1252 printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy());
1253
1254 SourceLocation Loc = AliasDecl->getLocation();
1255 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1256 getLineNumber(Loc),
1257 getDeclContextDescriptor(AliasDecl));
1258}
1259
1260llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1261 llvm::DIFile *Unit) {
1262 llvm::DIType *Underlying =
1263 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1264
1265 if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1266 return Underlying;
1267
1268 // We don't set size information, but do specify where the typedef was
1269 // declared.
1270 SourceLocation Loc = Ty->getDecl()->getLocation();
1271
1272 uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
1273 // Typedefs are derived from some other type.
1274 return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1275 getOrCreateFile(Loc), getLineNumber(Loc),
1276 getDeclContextDescriptor(Ty->getDecl()), Align);
1277}
1278
1279static unsigned getDwarfCC(CallingConv CC) {
1280 switch (CC) {
1281 case CC_C:
1282 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1283 return 0;
1284
1285 case CC_X86StdCall:
1286 return llvm::dwarf::DW_CC_BORLAND_stdcall;
1287 case CC_X86FastCall:
1288 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1289 case CC_X86ThisCall:
1290 return llvm::dwarf::DW_CC_BORLAND_thiscall;
1291 case CC_X86VectorCall:
1292 return llvm::dwarf::DW_CC_LLVM_vectorcall;
1293 case CC_X86Pascal:
1294 return llvm::dwarf::DW_CC_BORLAND_pascal;
1295 case CC_Win64:
1296 return llvm::dwarf::DW_CC_LLVM_Win64;
1297 case CC_X86_64SysV:
1298 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1299 case CC_AAPCS:
1300 case CC_AArch64VectorCall:
1301 return llvm::dwarf::DW_CC_LLVM_AAPCS;
1302 case CC_AAPCS_VFP:
1303 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1304 case CC_IntelOclBicc:
1305 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
1306 case CC_SpirFunction:
1307 return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1308 case CC_OpenCLKernel:
1309 return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
1310 case CC_Swift:
1311 return llvm::dwarf::DW_CC_LLVM_Swift;
1312 case CC_PreserveMost:
1313 return llvm::dwarf::DW_CC_LLVM_PreserveMost;
1314 case CC_PreserveAll:
1315 return llvm::dwarf::DW_CC_LLVM_PreserveAll;
1316 case CC_X86RegCall:
1317 return llvm::dwarf::DW_CC_LLVM_X86RegCall;
1318 }
1319 return 0;
1320}
1321
1322llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1323 llvm::DIFile *Unit) {
1324 SmallVector<llvm::Metadata *, 16> EltTys;
1325
1326 // Add the result type at least.
1327 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1328
1329 // Set up remainder of arguments if there is a prototype.
1330 // otherwise emit it as a variadic function.
1331 if (isa<FunctionNoProtoType>(Ty))
1332 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1333 else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
1334 for (const QualType &ParamType : FPT->param_types())
1335 EltTys.push_back(getOrCreateType(ParamType, Unit));
1336 if (FPT->isVariadic())
1337 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1338 }
1339
1340 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1341 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
1342 getDwarfCC(Ty->getCallConv()));
1343}
1344
1345/// Convert an AccessSpecifier into the corresponding DINode flag.
1346/// As an optimization, return 0 if the access specifier equals the
1347/// default for the containing type.
1348static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1349 const RecordDecl *RD) {
1350 AccessSpecifier Default = clang::AS_none;
1351 if (RD && RD->isClass())
1352 Default = clang::AS_private;
1353 else if (RD && (RD->isStruct() || RD->isUnion()))
1354 Default = clang::AS_public;
1355
1356 if (Access == Default)
1357 return llvm::DINode::FlagZero;
1358
1359 switch (Access) {
1360 case clang::AS_private:
1361 return llvm::DINode::FlagPrivate;
1362 case clang::AS_protected:
1363 return llvm::DINode::FlagProtected;
1364 case clang::AS_public:
1365 return llvm::DINode::FlagPublic;
1366 case clang::AS_none:
1367 return llvm::DINode::FlagZero;
1368 }
1369 llvm_unreachable("unexpected access enumerator");
1370}
1371
1372llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1373 llvm::DIScope *RecordTy,
1374 const RecordDecl *RD) {
1375 StringRef Name = BitFieldDecl->getName();
1376 QualType Ty = BitFieldDecl->getType();
1377 SourceLocation Loc = BitFieldDecl->getLocation();
1378 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1379 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1380
1381 // Get the location for the field.
1382 llvm::DIFile *File = getOrCreateFile(Loc);
1383 unsigned Line = getLineNumber(Loc);
1384
1385 const CGBitFieldInfo &BitFieldInfo =
1386 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1387 uint64_t SizeInBits = BitFieldInfo.Size;
1388 assert(SizeInBits > 0 && "found named 0-width bitfield");
1389 uint64_t StorageOffsetInBits =
1390 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1391 uint64_t Offset = BitFieldInfo.Offset;
1392 // The bit offsets for big endian machines are reversed for big
1393 // endian target, compensate for that as the DIDerivedType requires
1394 // un-reversed offsets.
1395 if (CGM.getDataLayout().isBigEndian())
1396 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1397 uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1398 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1399 return DBuilder.createBitFieldMemberType(
1400 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1401 Flags, DebugType);
1402}
1403
1404llvm::DIType *
1405CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
1406 AccessSpecifier AS, uint64_t offsetInBits,
1407 uint32_t AlignInBits, llvm::DIFile *tunit,
1408 llvm::DIScope *scope, const RecordDecl *RD) {
1409 llvm::DIType *debugType = getOrCreateType(type, tunit);
1410
1411 // Get the location for the field.
1412 llvm::DIFile *file = getOrCreateFile(loc);
1413 const unsigned line = getLineNumber(loc.isValid() ? loc : CurLoc);
1414
1415 uint64_t SizeInBits = 0;
1416 auto Align = AlignInBits;
1417 if (!type->isIncompleteArrayType()) {
1418 TypeInfo TI = CGM.getContext().getTypeInfo(type);
1419 SizeInBits = TI.Width;
1420 if (!Align)
1421 Align = getTypeAlignIfRequired(type, CGM.getContext());
1422 }
1423
1424 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1425 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1426 offsetInBits, flags, debugType);
1427}
1428
1429void CGDebugInfo::CollectRecordLambdaFields(
1430 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1431 llvm::DIType *RecordTy) {
1432 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1433 // has the name and the location of the variable so we should iterate over
1434 // both concurrently.
1435 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1436 RecordDecl::field_iterator Field = CXXDecl->field_begin();
1437 unsigned fieldno = 0;
1438 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
1439 E = CXXDecl->captures_end();
1440 I != E; ++I, ++Field, ++fieldno) {
1441 const LambdaCapture &C = *I;
1442 if (C.capturesVariable()) {
1443 SourceLocation Loc = C.getLocation();
1444 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1445 VarDecl *V = C.getCapturedVar();
1446 StringRef VName = V->getName();
1447 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1448 auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1449 llvm::DIType *FieldType = createFieldType(
1450 VName, Field->getType(), Loc, Field->getAccess(),
1451 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1452 elements.push_back(FieldType);
1453 } else if (C.capturesThis()) {
1454 // TODO: Need to handle 'this' in some way by probably renaming the
1455 // this of the lambda class and having a field member of 'this' or
1456 // by using AT_object_pointer for the function and having that be
1457 // used as 'this' for semantic references.
1458 FieldDecl *f = *Field;
1459 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1460 QualType type = f->getType();
1461 llvm::DIType *fieldType = createFieldType(
1462 "this", type, f->getLocation(), f->getAccess(),
1463 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1464
1465 elements.push_back(fieldType);
1466 }
1467 }
1468}
1469
1470llvm::DIDerivedType *
1471CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1472 const RecordDecl *RD) {
1473 // Create the descriptor for the static variable, with or without
1474 // constant initializers.
1475 Var = Var->getCanonicalDecl();
1476 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1477 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1478
1479 unsigned LineNumber = getLineNumber(Var->getLocation());
1480 StringRef VName = Var->getName();
1481 llvm::Constant *C = nullptr;
1482 if (Var->getInit()) {
1483 const APValue *Value = Var->evaluateValue();
1484 if (Value) {
1485 if (Value->isInt())
1486 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1487 if (Value->isFloat())
1488 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1489 }
1490 }
1491
1492 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1493 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1494 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1495 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
1496 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1497 return GV;
1498}
1499
1500void CGDebugInfo::CollectRecordNormalField(
1501 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1502 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1503 const RecordDecl *RD) {
1504 StringRef name = field->getName();
1505 QualType type = field->getType();
1506
1507 // Ignore unnamed fields unless they're anonymous structs/unions.
1508 if (name.empty() && !type->isRecordType())
1509 return;
1510
1511 llvm::DIType *FieldType;
1512 if (field->isBitField()) {
1513 FieldType = createBitFieldType(field, RecordTy, RD);
1514 } else {
1515 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1516 FieldType =
1517 createFieldType(name, type, field->getLocation(), field->getAccess(),
1518 OffsetInBits, Align, tunit, RecordTy, RD);
1519 }
1520
1521 elements.push_back(FieldType);
1522}
1523
1524void CGDebugInfo::CollectRecordNestedType(
1525 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1526 QualType Ty = CGM.getContext().getTypeDeclType(TD);
1527 // Injected class names are not considered nested records.
1528 if (isa<InjectedClassNameType>(Ty))
1529 return;
1530 SourceLocation Loc = TD->getLocation();
1531 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1532 elements.push_back(nestedType);
1533}
1534
1535void CGDebugInfo::CollectRecordFields(
1536 const RecordDecl *record, llvm::DIFile *tunit,
1537 SmallVectorImpl<llvm::Metadata *> &elements,
1538 llvm::DICompositeType *RecordTy) {
1539 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1540
1541 if (CXXDecl && CXXDecl->isLambda())
1542 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1543 else {
1544 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1545
1546 // Field number for non-static fields.
1547 unsigned fieldNo = 0;
1548
1549 // Static and non-static members should appear in the same order as
1550 // the corresponding declarations in the source program.
1551 for (const auto *I : record->decls())
1552 if (const auto *V = dyn_cast<VarDecl>(I)) {
1553 if (V->hasAttr<NoDebugAttr>())
1554 continue;
1555
1556 // Skip variable template specializations when emitting CodeView. MSVC
1557 // doesn't emit them.
1558 if (CGM.getCodeGenOpts().EmitCodeView &&
1559 isa<VarTemplateSpecializationDecl>(V))
1560 continue;
1561
1562 if (isa<VarTemplatePartialSpecializationDecl>(V))
1563 continue;
1564
1565 // Reuse the existing static member declaration if one exists
1566 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1567 if (MI != StaticDataMemberCache.end()) {
1568 assert(MI->second &&
1569 "Static data member declaration should still exist");
1570 elements.push_back(MI->second);
1571 } else {
1572 auto Field = CreateRecordStaticField(V, RecordTy, record);
1573 elements.push_back(Field);
1574 }
1575 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1576 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1577 elements, RecordTy, record);
1578
1579 // Bump field number for next field.
1580 ++fieldNo;
1581 } else if (CGM.getCodeGenOpts().EmitCodeView) {
1582 // Debug info for nested types is included in the member list only for
1583 // CodeView.
1584 if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1585 if (!nestedType->isImplicit() &&
1586 nestedType->getDeclContext() == record)
1587 CollectRecordNestedType(nestedType, elements);
1588 }
1589 }
1590}
1591
1592llvm::DISubroutineType *
1593CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1594 llvm::DIFile *Unit, bool decl) {
1595 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1596 if (Method->isStatic())
1597 return cast_or_null<llvm::DISubroutineType>(
1598 getOrCreateType(QualType(Func, 0), Unit));
1599 return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit, decl);
1600}
1601
1602llvm::DISubroutineType *
1603CGDebugInfo::getOrCreateInstanceMethodType(QualType ThisPtr,
1604 const FunctionProtoType *Func,
1605 llvm::DIFile *Unit, bool decl) {
1606 // Add "this" pointer.
1607 llvm::DITypeRefArray Args(
1608 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
1609 ->getTypeArray());
1610 assert(Args.size() && "Invalid number of arguments!");
1611
1612 SmallVector<llvm::Metadata *, 16> Elts;
1613 // First element is always return type. For 'void' functions it is NULL.
1614 QualType temp = Func->getReturnType();
1615 if (temp->getTypeClass() == Type::Auto && decl)
1616 Elts.push_back(CreateType(cast<AutoType>(temp)));
1617 else
1618 Elts.push_back(Args[0]);
1619
1620 // "this" pointer is always first argument.
1621 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1622 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1623 // Create pointer type directly in this case.
1624 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1625 QualType PointeeTy = ThisPtrTy->getPointeeType();
1626 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1627 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1628 auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
1629 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1630 llvm::DIType *ThisPtrType =
1631 DBuilder.createPointerType(PointeeType, Size, Align);
1632 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1633 // TODO: This and the artificial type below are misleading, the
1634 // types aren't artificial the argument is, but the current
1635 // metadata doesn't represent that.
1636 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1637 Elts.push_back(ThisPtrType);
1638 } else {
1639 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1640 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1641 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1642 Elts.push_back(ThisPtrType);
1643 }
1644
1645 // Copy rest of the arguments.
1646 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1647 Elts.push_back(Args[i]);
1648
1649 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1650
1651 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1652 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1653 Flags |= llvm::DINode::FlagLValueReference;
1654 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1655 Flags |= llvm::DINode::FlagRValueReference;
1656
1657 return DBuilder.createSubroutineType(EltTypeArray, Flags,
1658 getDwarfCC(Func->getCallConv()));
1659}
1660
1661/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1662/// inside a function.
1663static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1664 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1665 return isFunctionLocalClass(NRD);
1666 if (isa<FunctionDecl>(RD->getDeclContext()))
1667 return true;
1668 return false;
1669}
1670
1671llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1672 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1673 bool IsCtorOrDtor =
1674 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1675
1676 StringRef MethodName = getFunctionName(Method);
1677 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit, true);
1678
1679 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1680 // make sense to give a single ctor/dtor a linkage name.
1681 StringRef MethodLinkageName;
1682 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1683 // property to use here. It may've been intended to model "is non-external
1684 // type" but misses cases of non-function-local but non-external classes such
1685 // as those in anonymous namespaces as well as the reverse - external types
1686 // that are function local, such as those in (non-local) inline functions.
1687 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1688 MethodLinkageName = CGM.getMangledName(Method);
1689
1690 // Get the location for the method.
1691 llvm::DIFile *MethodDefUnit = nullptr;
1692 unsigned MethodLine = 0;
1693 if (!Method->isImplicit()) {
1694 MethodDefUnit = getOrCreateFile(Method->getLocation());
1695 MethodLine = getLineNumber(Method->getLocation());
1696 }
1697
1698 // Collect virtual method info.
1699 llvm::DIType *ContainingType = nullptr;
1700 unsigned VIndex = 0;
1701 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1702 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
1703 int ThisAdjustment = 0;
1704
1705 if (Method->isVirtual()) {
1706 if (Method->isPure())
1707 SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
1708 else
1709 SPFlags |= llvm::DISubprogram::SPFlagVirtual;
1710
1711 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1712 // It doesn't make sense to give a virtual destructor a vtable index,
1713 // since a single destructor has two entries in the vtable.
1714 if (!isa<CXXDestructorDecl>(Method))
1715 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1716 } else {
1717 // Emit MS ABI vftable information. There is only one entry for the
1718 // deleting dtor.
1719 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1720 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
1721 MethodVFTableLocation ML =
1722 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1723 VIndex = ML.Index;
1724
1725 // CodeView only records the vftable offset in the class that introduces
1726 // the virtual method. This is possible because, unlike Itanium, the MS
1727 // C++ ABI does not include all virtual methods from non-primary bases in
1728 // the vtable for the most derived class. For example, if C inherits from
1729 // A and B, C's primary vftable will not include B's virtual methods.
1730 if (Method->size_overridden_methods() == 0)
1731 Flags |= llvm::DINode::FlagIntroducedVirtual;
1732
1733 // The 'this' adjustment accounts for both the virtual and non-virtual
1734 // portions of the adjustment. Presumably the debugger only uses it when
1735 // it knows the dynamic type of an object.
1736 ThisAdjustment = CGM.getCXXABI()
1737 .getVirtualFunctionPrologueThisAdjustment(GD)
1738 .getQuantity();
1739 }
1740 ContainingType = RecordTy;
1741 }
1742
1743 // We're checking for deleted C++ special member functions
1744 // [Ctors,Dtors, Copy/Move]
1745 auto checkAttrDeleted = [&](const auto *Method) {
1746 if (Method->getCanonicalDecl()->isDeleted())
1747 SPFlags |= llvm::DISubprogram::SPFlagDeleted;
1748 };
1749
1750 switch (Method->getKind()) {
1751
1752 case Decl::CXXConstructor:
1753 case Decl::CXXDestructor:
1754 checkAttrDeleted(Method);
1755 break;
1756 case Decl::CXXMethod:
1757 if (Method->isCopyAssignmentOperator() ||
1758 Method->isMoveAssignmentOperator())
1759 checkAttrDeleted(Method);
1760 break;
1761 default:
1762 break;
1763 }
1764
1765 if (Method->isNoReturn())
1766 Flags |= llvm::DINode::FlagNoReturn;
1767
1768 if (Method->isStatic())
1769 Flags |= llvm::DINode::FlagStaticMember;
1770 if (Method->isImplicit())
1771 Flags |= llvm::DINode::FlagArtificial;
1772 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1773 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1774 if (CXXC->isExplicit())
1775 Flags |= llvm::DINode::FlagExplicit;
1776 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
1777 if (CXXC->isExplicit())
1778 Flags |= llvm::DINode::FlagExplicit;
1779 }
1780 if (Method->hasPrototype())
1781 Flags |= llvm::DINode::FlagPrototyped;
1782 if (Method->getRefQualifier() == RQ_LValue)
1783 Flags |= llvm::DINode::FlagLValueReference;
1784 if (Method->getRefQualifier() == RQ_RValue)
1785 Flags |= llvm::DINode::FlagRValueReference;
1786 if (!Method->isExternallyVisible())
1787 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
1788 if (CGM.getLangOpts().Optimize)
1789 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
1790
1791 // In this debug mode, emit type info for a class when its constructor type
1792 // info is emitted.
1793 if (DebugKind == codegenoptions::DebugInfoConstructor)
1794 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1795 completeUnusedClass(*CD->getParent());
1796
1797 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1798 llvm::DISubprogram *SP = DBuilder.createMethod(
1799 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1800 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
1801 TParamsArray.get());
1802
1803 SPCache[Method->getCanonicalDecl()].reset(SP);
1804
1805 return SP;
1806}
1807
1808void CGDebugInfo::CollectCXXMemberFunctions(
1809 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1810 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1811
1812 // Since we want more than just the individual member decls if we
1813 // have templated functions iterate over every declaration to gather
1814 // the functions.
1815 for (const auto *I : RD->decls()) {
1816 const auto *Method = dyn_cast<CXXMethodDecl>(I);
1817 // If the member is implicit, don't add it to the member list. This avoids
1818 // the member being added to type units by LLVM, while still allowing it
1819 // to be emitted into the type declaration/reference inside the compile
1820 // unit.
1821 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1822 // FIXME: Handle Using(Shadow?)Decls here to create
1823 // DW_TAG_imported_declarations inside the class for base decls brought into
1824 // derived classes. GDB doesn't seem to notice/leverage these when I tried
1825 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1826 // referenced)
1827 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
1828 continue;
1829
1830 if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
1831 continue;
1832
1833 // Reuse the existing member function declaration if it exists.
1834 // It may be associated with the declaration of the type & should be
1835 // reused as we're building the definition.
1836 //
1837 // This situation can arise in the vtable-based debug info reduction where
1838 // implicit members are emitted in a non-vtable TU.
1839 auto MI = SPCache.find(Method->getCanonicalDecl());
1840 EltTys.push_back(MI == SPCache.end()
1841 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1842 : static_cast<llvm::Metadata *>(MI->second));
1843 }
1844}
1845
1846void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1847 SmallVectorImpl<llvm::Metadata *> &EltTys,
1848 llvm::DIType *RecordTy) {
1849 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1850 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1851 llvm::DINode::FlagZero);
1852
1853 // If we are generating CodeView debug info, we also need to emit records for
1854 // indirect virtual base classes.
1855 if (CGM.getCodeGenOpts().EmitCodeView) {
1856 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1857 llvm::DINode::FlagIndirectVirtualBase);
1858 }
1859}
1860
1861void CGDebugInfo::CollectCXXBasesAux(
1862 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1863 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1864 const CXXRecordDecl::base_class_const_range &Bases,
1865 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
1866 llvm::DINode::DIFlags StartingFlags) {
1867 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1868 for (const auto &BI : Bases) {
1869 const auto *Base =
1870 cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
1871 if (!SeenTypes.insert(Base).second)
1872 continue;
1873 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1874 llvm::DINode::DIFlags BFlags = StartingFlags;
1875 uint64_t BaseOffset;
1876 uint32_t VBPtrOffset = 0;
1877
1878 if (BI.isVirtual()) {
1879 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1880 // virtual base offset offset is -ve. The code generator emits dwarf
1881 // expression where it expects +ve number.
1882 BaseOffset = 0 - CGM.getItaniumVTableContext()
1883 .getVirtualBaseOffsetOffset(RD, Base)
1884 .getQuantity();
1885 } else {
1886 // In the MS ABI, store the vbtable offset, which is analogous to the
1887 // vbase offset offset in Itanium.
1888 BaseOffset =
1889 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1890 VBPtrOffset = CGM.getContext()
1891 .getASTRecordLayout(RD)
1892 .getVBPtrOffset()
1893 .getQuantity();
1894 }
1895 BFlags |= llvm::DINode::FlagVirtual;
1896 } else
1897 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1898 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1899 // BI->isVirtual() and bits when not.
1900
1901 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1902 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
1903 VBPtrOffset, BFlags);
1904 EltTys.push_back(DTy);
1905 }
1906}
1907
1908llvm::DINodeArray
1909CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1910 ArrayRef<TemplateArgument> TAList,
1911 llvm::DIFile *Unit) {
1912 SmallVector<llvm::Metadata *, 16> TemplateParams;
1913 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1914 const TemplateArgument &TA = TAList[i];
1915 StringRef Name;
1916 bool defaultParameter = false;
1917 if (TPList)
1918 Name = TPList->getParam(i)->getName();
1919 switch (TA.getKind()) {
1920 case TemplateArgument::Type: {
1921 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1922
1923 if (TPList)
1924 if (auto *templateType =
1925 dyn_cast_or_null<TemplateTypeParmDecl>(TPList->getParam(i)))
1926 if (templateType->hasDefaultArgument())
1927 defaultParameter =
1928 templateType->getDefaultArgument() == TA.getAsType();
1929
1930 TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
1931 TheCU, Name, TTy, defaultParameter));
1932
1933 } break;
1934 case TemplateArgument::Integral: {
1935 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
1936 if (TPList && CGM.getCodeGenOpts().DwarfVersion >= 5)
1937 if (auto *templateType =
1938 dyn_cast_or_null<NonTypeTemplateParmDecl>(TPList->getParam(i)))
1939 if (templateType->hasDefaultArgument() &&
1940 !templateType->getDefaultArgument()->isValueDependent())
1941 defaultParameter = llvm::APSInt::isSameValue(
1942 templateType->getDefaultArgument()->EvaluateKnownConstInt(
1943 CGM.getContext()),
1944 TA.getAsIntegral());
1945
1946 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1947 TheCU, Name, TTy, defaultParameter,
1948 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
1949 } break;
1950 case TemplateArgument::Declaration: {
1951 const ValueDecl *D = TA.getAsDecl();
1952 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
1953 llvm::DIType *TTy = getOrCreateType(T, Unit);
1954 llvm::Constant *V = nullptr;
1955 // Skip retrieve the value if that template parameter has cuda device
1956 // attribute, i.e. that value is not available at the host side.
1957 if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
1958 !D->hasAttr<CUDADeviceAttr>()) {
1959 const CXXMethodDecl *MD;
1960 // Variable pointer template parameters have a value that is the address
1961 // of the variable.
1962 if (const auto *VD = dyn_cast<VarDecl>(D))
1963 V = CGM.GetAddrOfGlobalVar(VD);
1964 // Member function pointers have special support for building them,
1965 // though this is currently unsupported in LLVM CodeGen.
1966 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1967 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1968 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1969 V = CGM.GetAddrOfFunction(FD);
1970 // Member data pointers have special handling too to compute the fixed
1971 // offset within the object.
1972 else if (const auto *MPT =
1973 dyn_cast<