Bug Summary

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