Bug Summary

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