Bug Summary

File:clang/lib/CodeGen/CGDebugInfo.cpp
Warning:line 1976, column 13
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGDebugInfo.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/CodeGen -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/CodeGen/CGDebugInfo.cpp

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/CodeGen/CGDebugInfo.cpp

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

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include/llvm/ADT/Optional.h

1//===- Optional.h - Simple variant for passing optional values --*- C++ -*-===//
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 file provides Optional, a template class modeled in the spirit of
10// OCaml's 'opt' variant. The idea is to strongly type whether or not
11// a value can be optional.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_OPTIONAL_H
16#define LLVM_ADT_OPTIONAL_H
17
18#include "llvm/ADT/Hashing.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/STLForwardCompat.h"
21#include "llvm/Support/Compiler.h"
22#include "llvm/Support/type_traits.h"
23#include <cassert>
24#include <memory>
25#include <new>
26#include <utility>
27
28namespace llvm {
29
30class raw_ostream;
31
32namespace optional_detail {
33
34/// Storage for any type.
35//
36// The specialization condition intentionally uses
37// llvm::is_trivially_copy_constructible instead of
38// std::is_trivially_copy_constructible. GCC versions prior to 7.4 may
39// instantiate the copy constructor of `T` when
40// std::is_trivially_copy_constructible is instantiated. This causes
41// compilation to fail if we query the trivially copy constructible property of
42// a class which is not copy constructible.
43//
44// The current implementation of OptionalStorage insists that in order to use
45// the trivial specialization, the value_type must be trivially copy
46// constructible and trivially copy assignable due to =default implementations
47// of the copy/move constructor/assignment. It does not follow that this is
48// necessarily the case std::is_trivially_copyable is true (hence the expanded
49// specialization condition).
50//
51// The move constructible / assignable conditions emulate the remaining behavior
52// of std::is_trivially_copyable.
53template <typename T, bool = (llvm::is_trivially_copy_constructible<T>::value &&
54 std::is_trivially_copy_assignable<T>::value &&
55 (std::is_trivially_move_constructible<T>::value ||
56 !std::is_move_constructible<T>::value) &&
57 (std::is_trivially_move_assignable<T>::value ||
58 !std::is_move_assignable<T>::value))>
59class OptionalStorage {
60 union {
61 char empty;
62 T value;
63 };
64 bool hasVal;
65
66public:
67 ~OptionalStorage() { reset(); }
68
69 constexpr OptionalStorage() noexcept : empty(), hasVal(false) {}
70
71 constexpr OptionalStorage(OptionalStorage const &other) : OptionalStorage() {
72 if (other.hasValue()) {
73 emplace(other.value);
74 }
75 }
76 constexpr OptionalStorage(OptionalStorage &&other) : OptionalStorage() {
77 if (other.hasValue()) {
78 emplace(std::move(other.value));
79 }
80 }
81
82 template <class... Args>
83 constexpr explicit OptionalStorage(in_place_t, Args &&... args)
84 : value(std::forward<Args>(args)...), hasVal(true) {}
85
86 void reset() noexcept {
87 if (hasVal) {
88 value.~T();
89 hasVal = false;
90 }
91 }
92
93 constexpr bool hasValue() const noexcept { return hasVal; }
94
95 T &getValue() LLVM_LVALUE_FUNCTION& noexcept {
96 assert(hasVal)(static_cast<void> (0));
97 return value;
98 }
99 constexpr T const &getValue() const LLVM_LVALUE_FUNCTION& noexcept {
100 assert(hasVal)(static_cast<void> (0));
101 return value;
102 }
103#if LLVM_HAS_RVALUE_REFERENCE_THIS1
104 T &&getValue() && noexcept {
105 assert(hasVal)(static_cast<void> (0));
106 return std::move(value);
107 }
108#endif
109
110 template <class... Args> void emplace(Args &&... args) {
111 reset();
112 ::new ((void *)std::addressof(value)) T(std::forward<Args>(args)...);
113 hasVal = true;
114 }
115
116 OptionalStorage &operator=(T const &y) {
117 if (hasValue()) {
118 value = y;
119 } else {
120 ::new ((void *)std::addressof(value)) T(y);
121 hasVal = true;
122 }
123 return *this;
124 }
125 OptionalStorage &operator=(T &&y) {
126 if (hasValue()) {
127 value = std::move(y);
128 } else {
129 ::new ((void *)std::addressof(value)) T(std::move(y));
130 hasVal = true;
131 }
132 return *this;
133 }
134
135 OptionalStorage &operator=(OptionalStorage const &other) {
136 if (other.hasValue()) {
137 if (hasValue()) {
138 value = other.value;
139 } else {
140 ::new ((void *)std::addressof(value)) T(other.value);
141 hasVal = true;
142 }
143 } else {
144 reset();
145 }
146 return *this;
147 }
148
149 OptionalStorage &operator=(OptionalStorage &&other) {
150 if (other.hasValue()) {
151 if (hasValue()) {
152 value = std::move(other.value);
153 } else {
154 ::new ((void *)std::addressof(value)) T(std::move(other.value));
155 hasVal = true;
156 }
157 } else {
158 reset();
159 }
160 return *this;
161 }
162};
163
164template <typename T> class OptionalStorage<T, true> {
165 union {
166 char empty;
167 T value;
168 };
169 bool hasVal = false;
170
171public:
172 ~OptionalStorage() = default;
173
174 constexpr OptionalStorage() noexcept : empty{} {}
175
176 constexpr OptionalStorage(OptionalStorage const &other) = default;
177 constexpr OptionalStorage(OptionalStorage &&other) = default;
178
179 OptionalStorage &operator=(OptionalStorage const &other) = default;
180 OptionalStorage &operator=(OptionalStorage &&other) = default;
181
182 template <class... Args>
183 constexpr explicit OptionalStorage(in_place_t, Args &&... args)
184 : value(std::forward<Args>(args)...), hasVal(true) {}
185
186 void reset() noexcept {
187 if (hasVal) {
188 value.~T();
189 hasVal = false;
190 }
191 }
192
193 constexpr bool hasValue() const noexcept { return hasVal; }
25
Returning the value 1, which participates in a condition later
194
195 T &getValue() LLVM_LVALUE_FUNCTION& noexcept {
196 assert(hasVal)(static_cast<void> (0));
197 return value;
198 }
199 constexpr T const &getValue() const LLVM_LVALUE_FUNCTION& noexcept {
200 assert(hasVal)(static_cast<void> (0));
201 return value;
202 }
203#if LLVM_HAS_RVALUE_REFERENCE_THIS1
204 T &&getValue() && noexcept {
205 assert(hasVal)(static_cast<void> (0));
206 return std::move(value);
207 }
208#endif
209
210 template <class... Args> void emplace(Args &&... args) {
211 reset();
212 ::new ((void *)std::addressof(value)) T(std::forward<Args>(args)...);
213 hasVal = true;
214 }
215
216 OptionalStorage &operator=(T const &y) {
217 if (hasValue()) {
218 value = y;
219 } else {
220 ::new ((void *)std::addressof(value)) T(y);
221 hasVal = true;
222 }
223 return *this;
224 }
225 OptionalStorage &operator=(T &&y) {
226 if (hasValue()) {
227 value = std::move(y);
228 } else {
229 ::new ((void *)std::addressof(value)) T(std::move(y));
230 hasVal = true;
231 }
232 return *this;
233 }
234};
235
236} // namespace optional_detail
237
238template <typename T> class Optional {
239 optional_detail::OptionalStorage<T> Storage;
240
241public:
242 using value_type = T;
243
244 constexpr Optional() {}
245 constexpr Optional(NoneType) {}
246
247 constexpr Optional(const T &y) : Storage(in_place, y) {}
248 constexpr Optional(const Optional &O) = default;
249
250 constexpr Optional(T &&y) : Storage(in_place, std::move(y)) {}
251 constexpr Optional(Optional &&O) = default;
252
253 template <typename... ArgTypes>
254 constexpr Optional(in_place_t, ArgTypes &&...Args)
255 : Storage(in_place, std::forward<ArgTypes>(Args)...) {}
256
257 Optional &operator=(T &&y) {
258 Storage = std::move(y);
259 return *this;
260 }
261 Optional &operator=(Optional &&O) = default;
262
263 /// Create a new object by constructing it in place with the given arguments.
264 template <typename... ArgTypes> void emplace(ArgTypes &&... Args) {
265 Storage.emplace(std::forward<ArgTypes>(Args)...);
266 }
267
268 static constexpr Optional create(const T *y) {
269 return y ? Optional(*y) : Optional();
270 }
271
272 Optional &operator=(const T &y) {
273 Storage = y;
274 return *this;
275 }
276 Optional &operator=(const Optional &O) = default;
277
278 void reset() { Storage.reset(); }
279
280 constexpr const T *getPointer() const { return &Storage.getValue(); }
281 T *getPointer() { return &Storage.getValue(); }
282 constexpr const T &getValue() const LLVM_LVALUE_FUNCTION& {
283 return Storage.getValue();
284 }
285 T &getValue() LLVM_LVALUE_FUNCTION& { return Storage.getValue(); }
286
287 constexpr explicit operator bool() const { return hasValue(); }
23
Calling 'Optional::hasValue'
28
Returning from 'Optional::hasValue'
29
Returning the value 1, which participates in a condition later
288 constexpr bool hasValue() const { return Storage.hasValue(); }
24
Calling 'OptionalStorage::hasValue'
26
Returning from 'OptionalStorage::hasValue'
27
Returning the value 1, which participates in a condition later
289 constexpr const T *operator->() const { return getPointer(); }
290 T *operator->() { return getPointer(); }
291 constexpr const T &operator*() const LLVM_LVALUE_FUNCTION& {
292 return getValue();
293 }
294 T &operator*() LLVM_LVALUE_FUNCTION& { return getValue(); }
295
296 template <typename U>
297 constexpr T getValueOr(U &&value) const LLVM_LVALUE_FUNCTION& {
298 return hasValue() ? getValue() : std::forward<U>(value);
299 }
300
301 /// Apply a function to the value if present; otherwise return None.
302 template <class Function>
303 auto map(const Function &F) const LLVM_LVALUE_FUNCTION&
304 -> Optional<decltype(F(getValue()))> {
305 if (*this) return F(getValue());
306 return None;
307 }
308
309#if LLVM_HAS_RVALUE_REFERENCE_THIS1
310 T &&getValue() && { return std::move(Storage.getValue()); }
311 T &&operator*() && { return std::move(Storage.getValue()); }
312
313 template <typename U>
314 T getValueOr(U &&value) && {
315 return hasValue() ? std::move(getValue()) : std::forward<U>(value);
316 }
317
318 /// Apply a function to the value if present; otherwise return None.
319 template <class Function>
320 auto map(const Function &F) &&
321 -> Optional<decltype(F(std::move(*this).getValue()))> {
322 if (*this) return F(std::move(*this).getValue());
323 return None;
324 }
325#endif
326};
327
328template <class T> llvm::hash_code hash_value(const Optional<T> &O) {
329 return O ? hash_combine(true, *O) : hash_value(false);
330}
331
332template <typename T, typename U>
333constexpr bool operator==(const Optional<T> &X, const Optional<U> &Y) {
334 if (X && Y)
335 return *X == *Y;
336 return X.hasValue() == Y.hasValue();
337}
338
339template <typename T, typename U>
340constexpr bool operator!=(const Optional<T> &X, const Optional<U> &Y) {
341 return !(X == Y);
342}
343
344template <typename T, typename U>
345constexpr bool operator<(const Optional<T> &X, const Optional<U> &Y) {
346 if (X && Y)
347 return *X < *Y;
348 return X.hasValue() < Y.hasValue();
349}
350
351template <typename T, typename U>
352constexpr bool operator<=(const Optional<T> &X, const Optional<U> &Y) {
353 return !(Y < X);
354}
355
356template <typename T, typename U>
357constexpr bool operator>(const Optional<T> &X, const Optional<U> &Y) {
358 return Y < X;
359}
360
361template <typename T, typename U>
362constexpr bool operator>=(const Optional<T> &X, const Optional<U> &Y) {
363 return !(X < Y);
364}
365
366template <typename T>
367constexpr bool operator==(const Optional<T> &X, NoneType) {
368 return !X;
369}
370
371template <typename T>
372constexpr bool operator==(NoneType, const Optional<T> &X) {
373 return X == None;
374}
375
376template <typename T>
377constexpr bool operator!=(const Optional<T> &X, NoneType) {
378 return !(X == None);
379}
380
381template <typename T>
382constexpr bool operator!=(NoneType, const Optional<T> &X) {
383 return X != None;
384}
385
386template <typename T> constexpr bool operator<(const Optional<T> &, NoneType) {
387 return false;
388}
389
390template <typename T> constexpr bool operator<(NoneType, const Optional<T> &X) {
391 return X.hasValue();
392}
393
394template <typename T>
395constexpr bool operator<=(const Optional<T> &X, NoneType) {
396 return !(None < X);
397}
398
399template <typename T>
400constexpr bool operator<=(NoneType, const Optional<T> &X) {
401 return !(X < None);
402}
403
404template <typename T> constexpr bool operator>(const Optional<T> &X, NoneType) {
405 return None < X;
406}
407
408template <typename T> constexpr bool operator>(NoneType, const Optional<T> &X) {
409 return X < None;
410}
411
412template <typename T>
413constexpr bool operator>=(const Optional<T> &X, NoneType) {
414 return None <= X;
415}
416
417template <typename T>
418constexpr bool operator>=(NoneType, const Optional<T> &X) {
419 return X <= None;
420}
421
422template <typename T>
423constexpr bool operator==(const Optional<T> &X, const T &Y) {
424 return X && *X == Y;
425}
426
427template <typename T>
428constexpr bool operator==(const T &X, const Optional<T> &Y) {
429 return Y && X == *Y;
430}
431
432template <typename T>
433constexpr bool operator!=(const Optional<T> &X, const T &Y) {
434 return !(X == Y);
435}
436
437template <typename T>
438constexpr bool operator!=(const T &X, const Optional<T> &Y) {
439 return !(X == Y);
440}
441
442template <typename T>
443constexpr bool operator<(const Optional<T> &X, const T &Y) {
444 return !X || *X < Y;
445}
446
447template <typename T>
448constexpr bool operator<(const T &X, const Optional<T> &Y) {
449 return Y && X < *Y;
450}
451
452template <typename T>
453constexpr bool operator<=(const Optional<T> &X, const T &Y) {
454 return !(Y < X);
455}
456
457template <typename T>
458constexpr bool operator<=(const T &X, const Optional<T> &Y) {
459 return !(Y < X);
460}
461
462template <typename T>
463constexpr bool operator>(const Optional<T> &X, const T &Y) {
464 return Y < X;
465}
466
467template <typename T>
468constexpr bool operator>(const T &X, const Optional<T> &Y) {
469 return Y < X;
470}
471
472template <typename T>
473constexpr bool operator>=(const Optional<T> &X, const T &Y) {
474 return !(X < Y);
475}
476
477template <typename T>
478constexpr bool operator>=(const T &X, const Optional<T> &Y) {
479 return !(X < Y);
480}
481
482raw_ostream &operator<<(raw_ostream &OS, NoneType);
483
484template <typename T, typename = decltype(std::declval<raw_ostream &>()
485 << std::declval<const T &>())>
486raw_ostream &operator<<(raw_ostream &OS, const Optional<T> &O) {
487 if (O)
488 OS << *O;
489 else
490 OS << None;
491 return OS;
492}
493
494} // end namespace llvm
495
496#endif // LLVM_ADT_OPTIONAL_H