Bug Summary

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