Bug Summary

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