Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/lib/CodeGen/CGDebugInfo.cpp

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

/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/DependenceFlags.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/TemplateName.h"
23#include "clang/Basic/AddressSpaces.h"
24#include "clang/Basic/AttrKinds.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/ExceptionSpecificationType.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/Visibility.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/APSInt.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/None.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/Twine.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/PointerLikeTypeTraits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include "llvm/Support/type_traits.h"
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <cstring>
54#include <string>
55#include <type_traits>
56#include <utility>
57
58namespace clang {
59
60class ExtQuals;
61class QualType;
62class ConceptDecl;
63class TagDecl;
64class Type;
65
66enum {
67 TypeAlignmentInBits = 4,
68 TypeAlignment = 1 << TypeAlignmentInBits
69};
70
71namespace serialization {
72 template <class T> class AbstractTypeReader;
73 template <class T> class AbstractTypeWriter;
74}
75
76} // namespace clang
77
78namespace llvm {
79
80 template <typename T>
81 struct PointerLikeTypeTraits;
82 template<>
83 struct PointerLikeTypeTraits< ::clang::Type*> {
84 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
85
86 static inline ::clang::Type *getFromVoidPointer(void *P) {
87 return static_cast< ::clang::Type*>(P);
88 }
89
90 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
91 };
92
93 template<>
94 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
95 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
96
97 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
98 return static_cast< ::clang::ExtQuals*>(P);
99 }
100
101 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
102 };
103
104} // namespace llvm
105
106namespace clang {
107
108class ASTContext;
109template <typename> class CanQual;
110class CXXRecordDecl;
111class DeclContext;
112class EnumDecl;
113class Expr;
114class ExtQualsTypeCommonBase;
115class FunctionDecl;
116class IdentifierInfo;
117class NamedDecl;
118class ObjCInterfaceDecl;
119class ObjCProtocolDecl;
120class ObjCTypeParamDecl;
121struct PrintingPolicy;
122class RecordDecl;
123class Stmt;
124class TagDecl;
125class TemplateArgument;
126class TemplateArgumentListInfo;
127class TemplateArgumentLoc;
128class TemplateTypeParmDecl;
129class TypedefNameDecl;
130class UnresolvedUsingTypenameDecl;
131
132using CanQualType = CanQual<Type>;
133
134// Provide forward declarations for all of the *Type classes.
135#define TYPE(Class, Base) class Class##Type;
136#include "clang/AST/TypeNodes.inc"
137
138/// The collection of all-type qualifiers we support.
139/// Clang supports five independent qualifiers:
140/// * C99: const, volatile, and restrict
141/// * MS: __unaligned
142/// * Embedded C (TR18037): address spaces
143/// * Objective C: the GC attributes (none, weak, or strong)
144class Qualifiers {
145public:
146 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
147 Const = 0x1,
148 Restrict = 0x2,
149 Volatile = 0x4,
150 CVRMask = Const | Volatile | Restrict
151 };
152
153 enum GC {
154 GCNone = 0,
155 Weak,
156 Strong
157 };
158
159 enum ObjCLifetime {
160 /// There is no lifetime qualification on this type.
161 OCL_None,
162
163 /// This object can be modified without requiring retains or
164 /// releases.
165 OCL_ExplicitNone,
166
167 /// Assigning into this object requires the old value to be
168 /// released and the new value to be retained. The timing of the
169 /// release of the old value is inexact: it may be moved to
170 /// immediately after the last known point where the value is
171 /// live.
172 OCL_Strong,
173
174 /// Reading or writing from this object requires a barrier call.
175 OCL_Weak,
176
177 /// Assigning into this object requires a lifetime extension.
178 OCL_Autoreleasing
179 };
180
181 enum {
182 /// The maximum supported address space number.
183 /// 23 bits should be enough for anyone.
184 MaxAddressSpace = 0x7fffffu,
185
186 /// The width of the "fast" qualifier mask.
187 FastWidth = 3,
188
189 /// The fast qualifier mask.
190 FastMask = (1 << FastWidth) - 1
191 };
192
193 /// Returns the common set of qualifiers while removing them from
194 /// the given sets.
195 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
196 // If both are only CVR-qualified, bit operations are sufficient.
197 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
198 Qualifiers Q;
199 Q.Mask = L.Mask & R.Mask;
200 L.Mask &= ~Q.Mask;
201 R.Mask &= ~Q.Mask;
202 return Q;
203 }
204
205 Qualifiers Q;
206 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
207 Q.addCVRQualifiers(CommonCRV);
208 L.removeCVRQualifiers(CommonCRV);
209 R.removeCVRQualifiers(CommonCRV);
210
211 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
212 Q.setObjCGCAttr(L.getObjCGCAttr());
213 L.removeObjCGCAttr();
214 R.removeObjCGCAttr();
215 }
216
217 if (L.getObjCLifetime() == R.getObjCLifetime()) {
218 Q.setObjCLifetime(L.getObjCLifetime());
219 L.removeObjCLifetime();
220 R.removeObjCLifetime();
221 }
222
223 if (L.getAddressSpace() == R.getAddressSpace()) {
224 Q.setAddressSpace(L.getAddressSpace());
225 L.removeAddressSpace();
226 R.removeAddressSpace();
227 }
228 return Q;
229 }
230
231 static Qualifiers fromFastMask(unsigned Mask) {
232 Qualifiers Qs;
233 Qs.addFastQualifiers(Mask);
234 return Qs;
235 }
236
237 static Qualifiers fromCVRMask(unsigned CVR) {
238 Qualifiers Qs;
239 Qs.addCVRQualifiers(CVR);
240 return Qs;
241 }
242
243 static Qualifiers fromCVRUMask(unsigned CVRU) {
244 Qualifiers Qs;
245 Qs.addCVRUQualifiers(CVRU);
246 return Qs;
247 }
248
249 // Deserialize qualifiers from an opaque representation.
250 static Qualifiers fromOpaqueValue(unsigned opaque) {
251 Qualifiers Qs;
252 Qs.Mask = opaque;
253 return Qs;
254 }
255
256 // Serialize these qualifiers into an opaque representation.
257 unsigned getAsOpaqueValue() const {
258 return Mask;
259 }
260
261 bool hasConst() const { return Mask & Const; }
262 bool hasOnlyConst() const { return Mask == Const; }
263 void removeConst() { Mask &= ~Const; }
264 void addConst() { Mask |= Const; }
265
266 bool hasVolatile() const { return Mask & Volatile; }
267 bool hasOnlyVolatile() const { return Mask == Volatile; }
268 void removeVolatile() { Mask &= ~Volatile; }
269 void addVolatile() { Mask |= Volatile; }
270
271 bool hasRestrict() const { return Mask & Restrict; }
272 bool hasOnlyRestrict() const { return Mask == Restrict; }
273 void removeRestrict() { Mask &= ~Restrict; }
274 void addRestrict() { Mask |= Restrict; }
275
276 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
277 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
278 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
279
280 void setCVRQualifiers(unsigned mask) {
281 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 281, __PRETTY_FUNCTION__))
;
282 Mask = (Mask & ~CVRMask) | mask;
283 }
284 void removeCVRQualifiers(unsigned mask) {
285 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 285, __PRETTY_FUNCTION__))
;
286 Mask &= ~mask;
287 }
288 void removeCVRQualifiers() {
289 removeCVRQualifiers(CVRMask);
290 }
291 void addCVRQualifiers(unsigned mask) {
292 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 292, __PRETTY_FUNCTION__))
;
293 Mask |= mask;
294 }
295 void addCVRUQualifiers(unsigned mask) {
296 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 296, __PRETTY_FUNCTION__))
;
297 Mask |= mask;
298 }
299
300 bool hasUnaligned() const { return Mask & UMask; }
301 void setUnaligned(bool flag) {
302 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
303 }
304 void removeUnaligned() { Mask &= ~UMask; }
305 void addUnaligned() { Mask |= UMask; }
306
307 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
308 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
309 void setObjCGCAttr(GC type) {
310 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
311 }
312 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
313 void addObjCGCAttr(GC type) {
314 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 314, __PRETTY_FUNCTION__))
;
315 setObjCGCAttr(type);
316 }
317 Qualifiers withoutObjCGCAttr() const {
318 Qualifiers qs = *this;
319 qs.removeObjCGCAttr();
320 return qs;
321 }
322 Qualifiers withoutObjCLifetime() const {
323 Qualifiers qs = *this;
324 qs.removeObjCLifetime();
325 return qs;
326 }
327 Qualifiers withoutAddressSpace() const {
328 Qualifiers qs = *this;
329 qs.removeAddressSpace();
330 return qs;
331 }
332
333 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
334 ObjCLifetime getObjCLifetime() const {
335 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
336 }
337 void setObjCLifetime(ObjCLifetime type) {
338 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
339 }
340 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
341 void addObjCLifetime(ObjCLifetime type) {
342 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 342, __PRETTY_FUNCTION__))
;
343 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 343, __PRETTY_FUNCTION__))
;
344 Mask |= (type << LifetimeShift);
345 }
346
347 /// True if the lifetime is neither None or ExplicitNone.
348 bool hasNonTrivialObjCLifetime() const {
349 ObjCLifetime lifetime = getObjCLifetime();
350 return (lifetime > OCL_ExplicitNone);
351 }
352
353 /// True if the lifetime is either strong or weak.
354 bool hasStrongOrWeakObjCLifetime() const {
355 ObjCLifetime lifetime = getObjCLifetime();
356 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
357 }
358
359 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
360 LangAS getAddressSpace() const {
361 return static_cast<LangAS>(Mask >> AddressSpaceShift);
362 }
363 bool hasTargetSpecificAddressSpace() const {
364 return isTargetAddressSpace(getAddressSpace());
365 }
366 /// Get the address space attribute value to be printed by diagnostics.
367 unsigned getAddressSpaceAttributePrintValue() const {
368 auto Addr = getAddressSpace();
369 // This function is not supposed to be used with language specific
370 // address spaces. If that happens, the diagnostic message should consider
371 // printing the QualType instead of the address space value.
372 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 372, __PRETTY_FUNCTION__))
;
373 if (Addr != LangAS::Default)
374 return toTargetAddressSpace(Addr);
375 // TODO: The diagnostic messages where Addr may be 0 should be fixed
376 // since it cannot differentiate the situation where 0 denotes the default
377 // address space or user specified __attribute__((address_space(0))).
378 return 0;
379 }
380 void setAddressSpace(LangAS space) {
381 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 381, __PRETTY_FUNCTION__))
;
382 Mask = (Mask & ~AddressSpaceMask)
383 | (((uint32_t) space) << AddressSpaceShift);
384 }
385 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
386 void addAddressSpace(LangAS space) {
387 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 387, __PRETTY_FUNCTION__))
;
388 setAddressSpace(space);
389 }
390
391 // Fast qualifiers are those that can be allocated directly
392 // on a QualType object.
393 bool hasFastQualifiers() const { return getFastQualifiers(); }
394 unsigned getFastQualifiers() const { return Mask & FastMask; }
395 void setFastQualifiers(unsigned mask) {
396 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 396, __PRETTY_FUNCTION__))
;
397 Mask = (Mask & ~FastMask) | mask;
398 }
399 void removeFastQualifiers(unsigned mask) {
400 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 400, __PRETTY_FUNCTION__))
;
401 Mask &= ~mask;
402 }
403 void removeFastQualifiers() {
404 removeFastQualifiers(FastMask);
405 }
406 void addFastQualifiers(unsigned mask) {
407 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 407, __PRETTY_FUNCTION__))
;
408 Mask |= mask;
409 }
410
411 /// Return true if the set contains any qualifiers which require an ExtQuals
412 /// node to be allocated.
413 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
414 Qualifiers getNonFastQualifiers() const {
415 Qualifiers Quals = *this;
416 Quals.setFastQualifiers(0);
417 return Quals;
418 }
419
420 /// Return true if the set contains any qualifiers.
421 bool hasQualifiers() const { return Mask; }
422 bool empty() const { return !Mask; }
423
424 /// Add the qualifiers from the given set to this set.
425 void addQualifiers(Qualifiers Q) {
426 // If the other set doesn't have any non-boolean qualifiers, just
427 // bit-or it in.
428 if (!(Q.Mask & ~CVRMask))
429 Mask |= Q.Mask;
430 else {
431 Mask |= (Q.Mask & CVRMask);
432 if (Q.hasAddressSpace())
433 addAddressSpace(Q.getAddressSpace());
434 if (Q.hasObjCGCAttr())
435 addObjCGCAttr(Q.getObjCGCAttr());
436 if (Q.hasObjCLifetime())
437 addObjCLifetime(Q.getObjCLifetime());
438 }
439 }
440
441 /// Remove the qualifiers from the given set from this set.
442 void removeQualifiers(Qualifiers Q) {
443 // If the other set doesn't have any non-boolean qualifiers, just
444 // bit-and the inverse in.
445 if (!(Q.Mask & ~CVRMask))
446 Mask &= ~Q.Mask;
447 else {
448 Mask &= ~(Q.Mask & CVRMask);
449 if (getObjCGCAttr() == Q.getObjCGCAttr())
450 removeObjCGCAttr();
451 if (getObjCLifetime() == Q.getObjCLifetime())
452 removeObjCLifetime();
453 if (getAddressSpace() == Q.getAddressSpace())
454 removeAddressSpace();
455 }
456 }
457
458 /// Add the qualifiers from the given set to this set, given that
459 /// they don't conflict.
460 void addConsistentQualifiers(Qualifiers qs) {
461 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 462, __PRETTY_FUNCTION__))
462 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 462, __PRETTY_FUNCTION__))
;
463 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 464, __PRETTY_FUNCTION__))
464 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 464, __PRETTY_FUNCTION__))
;
465 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 466, __PRETTY_FUNCTION__))
466 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 466, __PRETTY_FUNCTION__))
;
467 Mask |= qs.Mask;
468 }
469
470 /// Returns true if address space A is equal to or a superset of B.
471 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
472 /// overlapping address spaces.
473 /// CL1.1 or CL1.2:
474 /// every address space is a superset of itself.
475 /// CL2.0 adds:
476 /// __generic is a superset of any address space except for __constant.
477 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
478 // Address spaces must match exactly.
479 return A == B ||
480 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
481 // for __constant can be used as __generic.
482 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
483 // We also define global_device and global_host address spaces,
484 // to distinguish global pointers allocated on host from pointers
485 // allocated on device, which are a subset of __global.
486 (A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
487 B == LangAS::opencl_global_host)) ||
488 // Consider pointer size address spaces to be equivalent to default.
489 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
490 (isPtrSizeAddressSpace(B) || B == LangAS::Default));
491 }
492
493 /// Returns true if the address space in these qualifiers is equal to or
494 /// a superset of the address space in the argument qualifiers.
495 bool isAddressSpaceSupersetOf(Qualifiers other) const {
496 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
497 }
498
499 /// Determines if these qualifiers compatibly include another set.
500 /// Generally this answers the question of whether an object with the other
501 /// qualifiers can be safely used as an object with these qualifiers.
502 bool compatiblyIncludes(Qualifiers other) const {
503 return isAddressSpaceSupersetOf(other) &&
504 // ObjC GC qualifiers can match, be added, or be removed, but can't
505 // be changed.
506 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
507 !other.hasObjCGCAttr()) &&
508 // ObjC lifetime qualifiers must match exactly.
509 getObjCLifetime() == other.getObjCLifetime() &&
510 // CVR qualifiers may subset.
511 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
512 // U qualifier may superset.
513 (!other.hasUnaligned() || hasUnaligned());
514 }
515
516 /// Determines if these qualifiers compatibly include another set of
517 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
518 ///
519 /// One set of Objective-C lifetime qualifiers compatibly includes the other
520 /// if the lifetime qualifiers match, or if both are non-__weak and the
521 /// including set also contains the 'const' qualifier, or both are non-__weak
522 /// and one is None (which can only happen in non-ARC modes).
523 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
524 if (getObjCLifetime() == other.getObjCLifetime())
525 return true;
526
527 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
528 return false;
529
530 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
531 return true;
532
533 return hasConst();
534 }
535
536 /// Determine whether this set of qualifiers is a strict superset of
537 /// another set of qualifiers, not considering qualifier compatibility.
538 bool isStrictSupersetOf(Qualifiers Other) const;
539
540 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
541 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
542
543 explicit operator bool() const { return hasQualifiers(); }
544
545 Qualifiers &operator+=(Qualifiers R) {
546 addQualifiers(R);
547 return *this;
548 }
549
550 // Union two qualifier sets. If an enumerated qualifier appears
551 // in both sets, use the one from the right.
552 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
553 L += R;
554 return L;
555 }
556
557 Qualifiers &operator-=(Qualifiers R) {
558 removeQualifiers(R);
559 return *this;
560 }
561
562 /// Compute the difference between two qualifier sets.
563 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
564 L -= R;
565 return L;
566 }
567
568 std::string getAsString() const;
569 std::string getAsString(const PrintingPolicy &Policy) const;
570
571 static std::string getAddrSpaceAsString(LangAS AS);
572
573 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
574 void print(raw_ostream &OS, const PrintingPolicy &Policy,
575 bool appendSpaceIfNonEmpty = false) const;
576
577 void Profile(llvm::FoldingSetNodeID &ID) const {
578 ID.AddInteger(Mask);
579 }
580
581private:
582 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
583 // |C R V|U|GCAttr|Lifetime|AddressSpace|
584 uint32_t Mask = 0;
585
586 static const uint32_t UMask = 0x8;
587 static const uint32_t UShift = 3;
588 static const uint32_t GCAttrMask = 0x30;
589 static const uint32_t GCAttrShift = 4;
590 static const uint32_t LifetimeMask = 0x1C0;
591 static const uint32_t LifetimeShift = 6;
592 static const uint32_t AddressSpaceMask =
593 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
594 static const uint32_t AddressSpaceShift = 9;
595};
596
597/// A std::pair-like structure for storing a qualified type split
598/// into its local qualifiers and its locally-unqualified type.
599struct SplitQualType {
600 /// The locally-unqualified type.
601 const Type *Ty = nullptr;
602
603 /// The local qualifiers.
604 Qualifiers Quals;
605
606 SplitQualType() = default;
607 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
608
609 SplitQualType getSingleStepDesugaredType() const; // end of this file
610
611 // Make std::tie work.
612 std::pair<const Type *,Qualifiers> asPair() const {
613 return std::pair<const Type *, Qualifiers>(Ty, Quals);
614 }
615
616 friend bool operator==(SplitQualType a, SplitQualType b) {
617 return a.Ty == b.Ty && a.Quals == b.Quals;
618 }
619 friend bool operator!=(SplitQualType a, SplitQualType b) {
620 return a.Ty != b.Ty || a.Quals != b.Quals;
621 }
622};
623
624/// The kind of type we are substituting Objective-C type arguments into.
625///
626/// The kind of substitution affects the replacement of type parameters when
627/// no concrete type information is provided, e.g., when dealing with an
628/// unspecialized type.
629enum class ObjCSubstitutionContext {
630 /// An ordinary type.
631 Ordinary,
632
633 /// The result type of a method or function.
634 Result,
635
636 /// The parameter type of a method or function.
637 Parameter,
638
639 /// The type of a property.
640 Property,
641
642 /// The superclass of a type.
643 Superclass,
644};
645
646/// A (possibly-)qualified type.
647///
648/// For efficiency, we don't store CV-qualified types as nodes on their
649/// own: instead each reference to a type stores the qualifiers. This
650/// greatly reduces the number of nodes we need to allocate for types (for
651/// example we only need one for 'int', 'const int', 'volatile int',
652/// 'const volatile int', etc).
653///
654/// As an added efficiency bonus, instead of making this a pair, we
655/// just store the two bits we care about in the low bits of the
656/// pointer. To handle the packing/unpacking, we make QualType be a
657/// simple wrapper class that acts like a smart pointer. A third bit
658/// indicates whether there are extended qualifiers present, in which
659/// case the pointer points to a special structure.
660class QualType {
661 friend class QualifierCollector;
662
663 // Thankfully, these are efficiently composable.
664 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
665 Qualifiers::FastWidth> Value;
666
667 const ExtQuals *getExtQualsUnsafe() const {
668 return Value.getPointer().get<const ExtQuals*>();
669 }
670
671 const Type *getTypePtrUnsafe() const {
672 return Value.getPointer().get<const Type*>();
673 }
674
675 const ExtQualsTypeCommonBase *getCommonPtr() const {
676 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 676, __PRETTY_FUNCTION__))
;
677 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
678 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
679 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
680 }
681
682public:
683 QualType() = default;
684 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
685 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
686
687 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
688 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
689
690 /// Retrieves a pointer to the underlying (unqualified) type.
691 ///
692 /// This function requires that the type not be NULL. If the type might be
693 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
694 const Type *getTypePtr() const;
695
696 const Type *getTypePtrOrNull() const;
697
698 /// Retrieves a pointer to the name of the base type.
699 const IdentifierInfo *getBaseTypeIdentifier() const;
700
701 /// Divides a QualType into its unqualified type and a set of local
702 /// qualifiers.
703 SplitQualType split() const;
704
705 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
706
707 static QualType getFromOpaquePtr(const void *Ptr) {
708 QualType T;
709 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
710 return T;
711 }
712
713 const Type &operator*() const {
714 return *getTypePtr();
715 }
716
717 const Type *operator->() const {
718 return getTypePtr();
719 }
720
721 bool isCanonical() const;
722 bool isCanonicalAsParam() const;
723
724 /// Return true if this QualType doesn't point to a type yet.
725 bool isNull() const {
726 return Value.getPointer().isNull();
727 }
728
729 /// Determine whether this particular QualType instance has the
730 /// "const" qualifier set, without looking through typedefs that may have
731 /// added "const" at a different level.
732 bool isLocalConstQualified() const {
733 return (getLocalFastQualifiers() & Qualifiers::Const);
734 }
735
736 /// Determine whether this type is const-qualified.
737 bool isConstQualified() const;
738
739 /// Determine whether this particular QualType instance has the
740 /// "restrict" qualifier set, without looking through typedefs that may have
741 /// added "restrict" at a different level.
742 bool isLocalRestrictQualified() const {
743 return (getLocalFastQualifiers() & Qualifiers::Restrict);
744 }
745
746 /// Determine whether this type is restrict-qualified.
747 bool isRestrictQualified() const;
748
749 /// Determine whether this particular QualType instance has the
750 /// "volatile" qualifier set, without looking through typedefs that may have
751 /// added "volatile" at a different level.
752 bool isLocalVolatileQualified() const {
753 return (getLocalFastQualifiers() & Qualifiers::Volatile);
754 }
755
756 /// Determine whether this type is volatile-qualified.
757 bool isVolatileQualified() const;
758
759 /// Determine whether this particular QualType instance has any
760 /// qualifiers, without looking through any typedefs that might add
761 /// qualifiers at a different level.
762 bool hasLocalQualifiers() const {
763 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
764 }
765
766 /// Determine whether this type has any qualifiers.
767 bool hasQualifiers() const;
768
769 /// Determine whether this particular QualType instance has any
770 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
771 /// instance.
772 bool hasLocalNonFastQualifiers() const {
773 return Value.getPointer().is<const ExtQuals*>();
774 }
775
776 /// Retrieve the set of qualifiers local to this particular QualType
777 /// instance, not including any qualifiers acquired through typedefs or
778 /// other sugar.
779 Qualifiers getLocalQualifiers() const;
780
781 /// Retrieve the set of qualifiers applied to this type.
782 Qualifiers getQualifiers() const;
783
784 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
785 /// local to this particular QualType instance, not including any qualifiers
786 /// acquired through typedefs or other sugar.
787 unsigned getLocalCVRQualifiers() const {
788 return getLocalFastQualifiers();
789 }
790
791 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
792 /// applied to this type.
793 unsigned getCVRQualifiers() const;
794
795 bool isConstant(const ASTContext& Ctx) const {
796 return QualType::isConstant(*this, Ctx);
797 }
798
799 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
800 bool isPODType(const ASTContext &Context) const;
801
802 /// Return true if this is a POD type according to the rules of the C++98
803 /// standard, regardless of the current compilation's language.
804 bool isCXX98PODType(const ASTContext &Context) const;
805
806 /// Return true if this is a POD type according to the more relaxed rules
807 /// of the C++11 standard, regardless of the current compilation's language.
808 /// (C++0x [basic.types]p9). Note that, unlike
809 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
810 bool isCXX11PODType(const ASTContext &Context) const;
811
812 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
813 bool isTrivialType(const ASTContext &Context) const;
814
815 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
816 bool isTriviallyCopyableType(const ASTContext &Context) const;
817
818
819 /// Returns true if it is a class and it might be dynamic.
820 bool mayBeDynamicClass() const;
821
822 /// Returns true if it is not a class or if the class might not be dynamic.
823 bool mayBeNotDynamicClass() const;
824
825 // Don't promise in the API that anything besides 'const' can be
826 // easily added.
827
828 /// Add the `const` type qualifier to this QualType.
829 void addConst() {
830 addFastQualifiers(Qualifiers::Const);
831 }
832 QualType withConst() const {
833 return withFastQualifiers(Qualifiers::Const);
834 }
835
836 /// Add the `volatile` type qualifier to this QualType.
837 void addVolatile() {
838 addFastQualifiers(Qualifiers::Volatile);
839 }
840 QualType withVolatile() const {
841 return withFastQualifiers(Qualifiers::Volatile);
842 }
843
844 /// Add the `restrict` qualifier to this QualType.
845 void addRestrict() {
846 addFastQualifiers(Qualifiers::Restrict);
847 }
848 QualType withRestrict() const {
849 return withFastQualifiers(Qualifiers::Restrict);
850 }
851
852 QualType withCVRQualifiers(unsigned CVR) const {
853 return withFastQualifiers(CVR);
854 }
855
856 void addFastQualifiers(unsigned TQs) {
857 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 858, __PRETTY_FUNCTION__))
858 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 858, __PRETTY_FUNCTION__))
;
859 Value.setInt(Value.getInt() | TQs);
860 }
861
862 void removeLocalConst();
863 void removeLocalVolatile();
864 void removeLocalRestrict();
865 void removeLocalCVRQualifiers(unsigned Mask);
866
867 void removeLocalFastQualifiers() { Value.setInt(0); }
868 void removeLocalFastQualifiers(unsigned Mask) {
869 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-12~++20200806111125+5446ec85070/clang/include/clang/AST/Type.h"
, 869, __PRETTY_FUNCTION__))
;
870 Value.setInt(Value.getInt() & ~Mask);
871 }
872
873 // Creates a type with the given qualifiers in addition to any
874 // qualifiers already on this type.
875 QualType withFastQualifiers(unsigned TQs) const {
876 QualType T = *this;
877 T.addFastQualifiers(TQs);
878 return T;
879 }
880
881 // Creates a type with exactly the given fast qualifiers, removing
882 // any existing fast qualifiers.
883 QualType withExactLocalFastQualifiers(unsigned TQs) const {
884 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
885 }
886
887 // Removes fast qualifiers, but leaves any extended qualifiers in place.
888 QualType withoutLocalFastQualifiers() const {
889 QualType T = *this;
890 T.removeLocalFastQualifiers();
891 return T;
892 }
893
894 QualType getCanonicalType() const;
895
896 /// Return this type with all of the instance-specific qualifiers
897 /// removed, but without removing any qualifiers that may have been applied
898 /// through typedefs.
899 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
900
901 /// Retrieve the unqualified variant of the given type,
902 /// removing as little sugar as possible.
903 ///
904 /// This routine looks through various kinds of sugar to find the
905 /// least-desugared type that is unqualified. For example, given:
906 ///
907 /// \code
908 /// typedef int Integer;
909 /// typedef const Integer CInteger;
910 /// typedef CInteger DifferenceType;
911 /// \endcode
912 ///
913 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
914 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
915 ///
916 /// The resulting type might still be qualified if it's sugar for an array
917 /// type. To strip qualifiers even from within a sugared array type, use
918 /// ASTContext::getUnqualifiedArrayType.
919 inline QualType getUnqualifiedType() const;
920
921 /// Retrieve the unqualified variant of the given type, removing as little
922 /// sugar as possible.
923 ///
924 /// Like getUnqualifiedType(), but also returns the set of
925 /// qualifiers that were built up.
926 ///
927 /// The resulting type might still be qualified if it's sugar for an array
928 /// type. To strip qualifiers even from within a sugared array type, use
929 /// ASTContext::getUnqualifiedArrayType.
930 inline SplitQualType getSplitUnqualifiedType() const;
931
932 /// Determine whether this type is more qualified than the other
933 /// given type, requiring exact equality for non-CVR qualifiers.
934 bool isMoreQualifiedThan(QualType Other) const;
935
936 /// Determine whether this type is at least as qualified as the other
937 /// given type, requiring exact equality for non-CVR qualifiers.
938 bool isAtLeastAsQualifiedAs(QualType Other) const;
939
940 QualType getNonReferenceType() const;
941
942 /// Determine the type of a (typically non-lvalue) expression with the
943 /// specified result type.
944 ///
945 /// This routine should be used for expressions for which the return type is
946 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
947 /// an lvalue. It removes a top-level reference (since there are no
948 /// expressions of reference type) and deletes top-level cvr-qualifiers
949 /// from non-class types (in C++) or all types (in C).
950 QualType getNonLValueExprType(const ASTContext &Context) const;
951
952 /// Remove an outer pack expansion type (if any) from this type. Used as part
953 /// of converting the type of a declaration to the type of an expression that
954 /// references that expression. It's meaningless for an expression to have a
955 /// pack expansion type.
956 QualType getNonPackExpansionType() const;
957
958 /// Return the specified type with any "sugar" removed from
959 /// the type. This takes off typedefs, typeof's etc. If the outer level of
960 /// the type is already concrete, it returns it unmodified. This is similar
961 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
962 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
963 /// concrete.
964 ///
965 /// Qualifiers are left in place.
966 QualType getDesugaredType(const ASTContext &Context) const {
967 return getDesugaredType(*this, Context);
968 }
969
970 SplitQualType getSplitDesugaredType() const {
971 return getSplitDesugaredType(*this);
972 }
973
974 /// Return the specified type with one level of "sugar" removed from
975 /// the type.
976 ///
977 /// This routine takes off the first typedef, typeof, etc. If the outer level
978 /// of the type is already concrete, it returns it unmodified.
979 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
980 return getSingleStepDesugaredTypeImpl(*this, Context);
981 }
982
983 /// Returns the specified type after dropping any
984 /// outer-level parentheses.
985 QualType IgnoreParens() const {
986 if (isa<ParenType>(*this))
987 return QualType::IgnoreParens(*this);
988 return *this;
989 }
990