Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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