Bug Summary

File:tools/clang/lib/CodeGen/CGDebugInfo.cpp
Warning:line 3006, column 20
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-eagerly-assume -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-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn325118/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.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-7~svn325118/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-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-02-14-150435-17243-1 -x c++ /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/CodeGen/CGDebugInfo.cpp

/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/CodeGen/CGDebugInfo.cpp

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

/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===//
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 file defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
11// and dyn_cast_or_null<X>() templates.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_CASTING_H
16#define LLVM_SUPPORT_CASTING_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/type_traits.h"
20#include <cassert>
21#include <memory>
22#include <type_traits>
23
24namespace llvm {
25
26//===----------------------------------------------------------------------===//
27// isa<x> Support Templates
28//===----------------------------------------------------------------------===//
29
30// Define a template that can be specialized by smart pointers to reflect the
31// fact that they are automatically dereferenced, and are not involved with the
32// template selection process... the default implementation is a noop.
33//
34template<typename From> struct simplify_type {
35 using SimpleType = From; // The real type this represents...
36
37 // An accessor to get the real value...
38 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
39};
40
41template<typename From> struct simplify_type<const From> {
42 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
43 using SimpleType =
44 typename add_const_past_pointer<NonConstSimpleType>::type;
45 using RetType =
46 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
47
48 static RetType getSimplifiedValue(const From& Val) {
49 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
6
Calling 'simplify_type::getSimplifiedValue'
7
Returning from 'simplify_type::getSimplifiedValue'
31
Calling 'simplify_type::getSimplifiedValue'
32
Returning from 'simplify_type::getSimplifiedValue'
50 }
51};
52
53// The core of the implementation of isa<X> is here; To and From should be
54// the names of classes. This template can be specialized to customize the
55// implementation of isa<> without rewriting it from scratch.
56template <typename To, typename From, typename Enabler = void>
57struct isa_impl {
58 static inline bool doit(const From &Val) {
59 return To::classof(&Val);
13
Calling 'FunctionDecl::classof'
20
Returning from 'FunctionDecl::classof'
38
Calling 'FunctionDecl::classof'
43
Returning from 'FunctionDecl::classof'
60 }
61};
62
63/// \brief Always allow upcasts, and perform no dynamic check for them.
64template <typename To, typename From>
65struct isa_impl<
66 To, From, typename std::enable_if<std::is_base_of<To, From>::value>::type> {
67 static inline bool doit(const From &) { return true; }
68};
69
70template <typename To, typename From> struct isa_impl_cl {
71 static inline bool doit(const From &Val) {
72 return isa_impl<To, From>::doit(Val);
73 }
74};
75
76template <typename To, typename From> struct isa_impl_cl<To, const From> {
77 static inline bool doit(const From &Val) {
78 return isa_impl<To, From>::doit(Val);
79 }
80};
81
82template <typename To, typename From>
83struct isa_impl_cl<To, const std::unique_ptr<From>> {
84 static inline bool doit(const std::unique_ptr<From> &Val) {
85 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 85, __extension__ __PRETTY_FUNCTION__))
;
86 return isa_impl_cl<To, From>::doit(*Val);
87 }
88};
89
90template <typename To, typename From> struct isa_impl_cl<To, From*> {
91 static inline bool doit(const From *Val) {
92 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 92, __extension__ __PRETTY_FUNCTION__))
;
93 return isa_impl<To, From>::doit(*Val);
94 }
95};
96
97template <typename To, typename From> struct isa_impl_cl<To, From*const> {
98 static inline bool doit(const From *Val) {
99 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 99, __extension__ __PRETTY_FUNCTION__))
;
100 return isa_impl<To, From>::doit(*Val);
101 }
102};
103
104template <typename To, typename From> struct isa_impl_cl<To, const From*> {
105 static inline bool doit(const From *Val) {
106 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 106, __extension__ __PRETTY_FUNCTION__))
;
11
Within the expansion of the macro 'assert':
a
Assuming 'Val' is non-null
36
Within the expansion of the macro 'assert':
107 return isa_impl<To, From>::doit(*Val);
12
Calling 'isa_impl::doit'
21
Returning from 'isa_impl::doit'
37
Calling 'isa_impl::doit'
44
Returning from 'isa_impl::doit'
108 }
109};
110
111template <typename To, typename From> struct isa_impl_cl<To, const From*const> {
112 static inline bool doit(const From *Val) {
113 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 113, __extension__ __PRETTY_FUNCTION__))
;
114 return isa_impl<To, From>::doit(*Val);
115 }
116};
117
118template<typename To, typename From, typename SimpleFrom>
119struct isa_impl_wrap {
120 // When From != SimplifiedType, we can simplify the type some more by using
121 // the simplify_type template.
122 static bool doit(const From &Val) {
123 return isa_impl_wrap<To, SimpleFrom,
9
Calling 'isa_impl_wrap::doit'
23
Returning from 'isa_impl_wrap::doit'
34
Calling 'isa_impl_wrap::doit'
46
Returning from 'isa_impl_wrap::doit'
124 typename simplify_type<SimpleFrom>::SimpleType>::doit(
125 simplify_type<const From>::getSimplifiedValue(Val));
5
Calling 'simplify_type::getSimplifiedValue'
8
Returning from 'simplify_type::getSimplifiedValue'
30
Calling 'simplify_type::getSimplifiedValue'
33
Returning from 'simplify_type::getSimplifiedValue'
126 }
127};
128
129template<typename To, typename FromTy>
130struct isa_impl_wrap<To, FromTy, FromTy> {
131 // When From == SimpleType, we are as simple as we are going to get.
132 static bool doit(const FromTy &Val) {
133 return isa_impl_cl<To,FromTy>::doit(Val);
10
Calling 'isa_impl_cl::doit'
22
Returning from 'isa_impl_cl::doit'
35
Calling 'isa_impl_cl::doit'
45
Returning from 'isa_impl_cl::doit'
134 }
135};
136
137// isa<X> - Return true if the parameter to the template is an instance of the
138// template type argument. Used like this:
139//
140// if (isa<Type>(myVal)) { ... }
141//
142template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
143 return isa_impl_wrap<X, const Y,
4
Calling 'isa_impl_wrap::doit'
24
Returning from 'isa_impl_wrap::doit'
29
Calling 'isa_impl_wrap::doit'
47
Returning from 'isa_impl_wrap::doit'
144 typename simplify_type<const Y>::SimpleType>::doit(Val);
145}
146
147//===----------------------------------------------------------------------===//
148// cast<x> Support Templates
149//===----------------------------------------------------------------------===//
150
151template<class To, class From> struct cast_retty;
152
153// Calculate what type the 'cast' function should return, based on a requested
154// type of To and a source type of From.
155template<class To, class From> struct cast_retty_impl {
156 using ret_type = To &; // Normal case, return Ty&
157};
158template<class To, class From> struct cast_retty_impl<To, const From> {
159 using ret_type = const To &; // Normal case, return Ty&
160};
161
162template<class To, class From> struct cast_retty_impl<To, From*> {
163 using ret_type = To *; // Pointer arg case, return Ty*
164};
165
166template<class To, class From> struct cast_retty_impl<To, const From*> {
167 using ret_type = const To *; // Constant pointer arg case, return const Ty*
168};
169
170template<class To, class From> struct cast_retty_impl<To, const From*const> {
171 using ret_type = const To *; // Constant pointer arg case, return const Ty*
172};
173
174template <class To, class From>
175struct cast_retty_impl<To, std::unique_ptr<From>> {
176private:
177 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
178 using ResultType = typename std::remove_pointer<PointerType>::type;
179
180public:
181 using ret_type = std::unique_ptr<ResultType>;
182};
183
184template<class To, class From, class SimpleFrom>
185struct cast_retty_wrap {
186 // When the simplified type and the from type are not the same, use the type
187 // simplifier to reduce the type, then reuse cast_retty_impl to get the
188 // resultant type.
189 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
190};
191
192template<class To, class FromTy>
193struct cast_retty_wrap<To, FromTy, FromTy> {
194 // When the simplified type is equal to the from type, use it directly.
195 using ret_type = typename cast_retty_impl<To,FromTy>::ret_type;
196};
197
198template<class To, class From>
199struct cast_retty {
200 using ret_type = typename cast_retty_wrap<
201 To, From, typename simplify_type<From>::SimpleType>::ret_type;
202};
203
204// Ensure the non-simple values are converted using the simplify_type template
205// that may be specialized by smart pointers...
206//
207template<class To, class From, class SimpleFrom> struct cast_convert_val {
208 // This is not a simple type, use the template to simplify it...
209 static typename cast_retty<To, From>::ret_type doit(From &Val) {
210 return cast_convert_val<To, SimpleFrom,
211 typename simplify_type<SimpleFrom>::SimpleType>::doit(
212 simplify_type<From>::getSimplifiedValue(Val));
213 }
214};
215
216template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> {
217 // This _is_ a simple type, just cast it.
218 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
219 typename cast_retty<To, FromTy>::ret_type Res2
220 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
221 return Res2;
222 }
223};
224
225template <class X> struct is_simple_type {
226 static const bool value =
227 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
228};
229
230// cast<X> - Return the argument parameter cast to the specified type. This
231// casting operator asserts that the type is correct, so it does not return null
232// on failure. It does not allow a null argument (use cast_or_null for that).
233// It is typically used like this:
234//
235// cast<Instruction>(myVal)->getParent()
236//
237template <class X, class Y>
238inline typename std::enable_if<!is_simple_type<Y>::value,
239 typename cast_retty<X, const Y>::ret_type>::type
240cast(const Y &Val) {
241 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 241, __extension__ __PRETTY_FUNCTION__))
;
242 return cast_convert_val<
243 X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val);
244}
245
246template <class X, class Y>
247inline typename cast_retty<X, Y>::ret_type cast(Y &Val) {
248 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 248, __extension__ __PRETTY_FUNCTION__))
;
249 return cast_convert_val<X, Y,
250 typename simplify_type<Y>::SimpleType>::doit(Val);
251}
252
253template <class X, class Y>
254inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) {
255 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 255, __extension__ __PRETTY_FUNCTION__))
;
28
Within the expansion of the macro 'assert':
a
Calling 'isa'
b
Returning from 'isa'
256 return cast_convert_val<X, Y*,
48
Calling 'cast_convert_val::doit'
49
Returning from 'cast_convert_val::doit'
257 typename simplify_type<Y*>::SimpleType>::doit(Val);
258}
259
260template <class X, class Y>
261inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
262cast(std::unique_ptr<Y> &&Val) {
263 assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val.get()) &&
"cast<Ty>() argument of incompatible type!") ? void (0
) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 263, __extension__ __PRETTY_FUNCTION__))
;
264 using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type;
265 return ret_type(
266 cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit(
267 Val.release()));
268}
269
270// cast_or_null<X> - Functionally identical to cast, except that a null value is
271// accepted.
272//
273template <class X, class Y>
274LLVM_NODISCARD[[clang::warn_unused_result]] inline
275 typename std::enable_if<!is_simple_type<Y>::value,
276 typename cast_retty<X, const Y>::ret_type>::type
277 cast_or_null(const Y &Val) {
278 if (!Val)
279 return nullptr;
280 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 280, __extension__ __PRETTY_FUNCTION__))
;
281 return cast<X>(Val);
282}
283
284template <class X, class Y>
285LLVM_NODISCARD[[clang::warn_unused_result]] inline
286 typename std::enable_if<!is_simple_type<Y>::value,
287 typename cast_retty<X, Y>::ret_type>::type
288 cast_or_null(Y &Val) {
289 if (!Val)
290 return nullptr;
291 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 291, __extension__ __PRETTY_FUNCTION__))
;
292 return cast<X>(Val);
293}
294
295template <class X, class Y>
296LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
297cast_or_null(Y *Val) {
298 if (!Val) return nullptr;
299 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 299, __extension__ __PRETTY_FUNCTION__))
;
300 return cast<X>(Val);
301}
302
303template <class X, class Y>
304inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
305cast_or_null(std::unique_ptr<Y> &&Val) {
306 if (!Val)
307 return nullptr;
308 return cast<X>(std::move(Val));
309}
310
311// dyn_cast<X> - Return the argument parameter cast to the specified type. This
312// casting operator returns null if the argument is of the wrong type, so it can
313// be used to test for a type as well as cast if successful. This should be
314// used in the context of an if statement like this:
315//
316// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
317//
318
319template <class X, class Y>
320LLVM_NODISCARD[[clang::warn_unused_result]] inline
321 typename std::enable_if<!is_simple_type<Y>::value,
322 typename cast_retty<X, const Y>::ret_type>::type
323 dyn_cast(const Y &Val) {
324 return isa<X>(Val) ? cast<X>(Val) : nullptr;
325}
326
327template <class X, class Y>
328LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) {
329 return isa<X>(Val) ? cast<X>(Val) : nullptr;
330}
331
332template <class X, class Y>
333LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) {
334 return isa<X>(Val) ? cast<X>(Val) : nullptr;
3
Calling 'isa'
25
Returning from 'isa'
26
'?' condition is true
27
Calling 'cast'
50
Returning from 'cast'
335}
336
337// dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null
338// value is accepted.
339//
340template <class X, class Y>
341LLVM_NODISCARD[[clang::warn_unused_result]] inline
342 typename std::enable_if<!is_simple_type<Y>::value,
343 typename cast_retty<X, const Y>::ret_type>::type
344 dyn_cast_or_null(const Y &Val) {
345 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
346}
347
348template <class X, class Y>
349LLVM_NODISCARD[[clang::warn_unused_result]] inline
350 typename std::enable_if<!is_simple_type<Y>::value,
351 typename cast_retty<X, Y>::ret_type>::type
352 dyn_cast_or_null(Y &Val) {
353 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
354}
355
356template <class X, class Y>
357LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
358dyn_cast_or_null(Y *Val) {
359 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
360}
361
362// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
363// taking ownership of the input pointer iff isa<X>(Val) is true. If the
364// cast is successful, From refers to nullptr on exit and the casted value
365// is returned. If the cast is unsuccessful, the function returns nullptr
366// and From is unchanged.
367template <class X, class Y>
368LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val)
369 -> decltype(cast<X>(Val)) {
370 if (!isa<X>(Val))
371 return nullptr;
372 return cast<X>(std::move(Val));
373}
374
375template <class X, class Y>
376LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val)
377 -> decltype(cast<X>(Val)) {
378 return unique_dyn_cast<X, Y>(Val);
379}
380
381// dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that
382// a null value is accepted.
383template <class X, class Y>
384LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val)
385 -> decltype(cast<X>(Val)) {
386 if (!Val)
387 return nullptr;
388 return unique_dyn_cast<X, Y>(Val);
389}
390
391template <class X, class Y>
392LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val)
393 -> decltype(cast<X>(Val)) {
394 return unique_dyn_cast_or_null<X, Y>(Val);
395}
396
397} // end namespace llvm
398
399#endif // LLVM_SUPPORT_CASTING_H

/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h

1//===- Decl.h - Classes for representing declarations -----------*- C++ -*-===//
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 file defines the Decl subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECL_H
15#define LLVM_CLANG_AST_DECL_H
16
17#include "clang/AST/APValue.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclarationName.h"
20#include "clang/AST/ExternalASTSource.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/Redeclarable.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/AddressSpaces.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/IdentifierTable.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/OperatorKinds.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/PragmaKinds.h"
32#include "clang/Basic/SourceLocation.h"
33#include "clang/Basic/Specifiers.h"
34#include "clang/Basic/Visibility.h"
35#include "llvm/ADT/APSInt.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/iterator_range.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/Compiler.h"
44#include "llvm/Support/TrailingObjects.h"
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <string>
49#include <utility>
50
51namespace clang {
52
53class ASTContext;
54struct ASTTemplateArgumentListInfo;
55class Attr;
56class CompoundStmt;
57class DependentFunctionTemplateSpecializationInfo;
58class EnumDecl;
59class Expr;
60class FunctionTemplateDecl;
61class FunctionTemplateSpecializationInfo;
62class LabelStmt;
63class MemberSpecializationInfo;
64class Module;
65class NamespaceDecl;
66class ParmVarDecl;
67class RecordDecl;
68class Stmt;
69class StringLiteral;
70class TagDecl;
71class TemplateArgumentList;
72class TemplateArgumentListInfo;
73class TemplateParameterList;
74class TypeAliasTemplateDecl;
75class TypeLoc;
76class UnresolvedSetImpl;
77class VarTemplateDecl;
78
79/// A container of type source information.
80///
81/// A client can read the relevant info using TypeLoc wrappers, e.g:
82/// @code
83/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
84/// TL.getStartLoc().print(OS, SrcMgr);
85/// @endcode
86class LLVM_ALIGNAS(8)alignas(8) TypeSourceInfo {
87 // Contains a memory block after the class, used for type source information,
88 // allocated by ASTContext.
89 friend class ASTContext;
90
91 QualType Ty;
92
93 TypeSourceInfo(QualType ty) : Ty(ty) {}
94
95public:
96 /// Return the type wrapped by this type source info.
97 QualType getType() const { return Ty; }
98
99 /// Return the TypeLoc wrapper for the type source info.
100 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
101
102 /// Override the type stored in this TypeSourceInfo. Use with caution!
103 void overrideType(QualType T) { Ty = T; }
104};
105
106/// The top declaration context.
107class TranslationUnitDecl : public Decl, public DeclContext {
108 ASTContext &Ctx;
109
110 /// The (most recently entered) anonymous namespace for this
111 /// translation unit, if one has been created.
112 NamespaceDecl *AnonymousNamespace = nullptr;
113
114 explicit TranslationUnitDecl(ASTContext &ctx);
115
116 virtual void anchor();
117
118public:
119 ASTContext &getASTContext() const { return Ctx; }
120
121 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
122 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
123
124 static TranslationUnitDecl *Create(ASTContext &C);
125
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == TranslationUnit; }
129 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
130 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
131 }
132 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
133 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
134 }
135};
136
137/// Represents a `#pragma comment` line. Always a child of
138/// TranslationUnitDecl.
139class PragmaCommentDecl final
140 : public Decl,
141 private llvm::TrailingObjects<PragmaCommentDecl, char> {
142 friend class ASTDeclReader;
143 friend class ASTDeclWriter;
144 friend TrailingObjects;
145
146 PragmaMSCommentKind CommentKind;
147
148 PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
149 PragmaMSCommentKind CommentKind)
150 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
151
152 virtual void anchor();
153
154public:
155 static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
156 SourceLocation CommentLoc,
157 PragmaMSCommentKind CommentKind,
158 StringRef Arg);
159 static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
160 unsigned ArgSize);
161
162 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
163
164 StringRef getArg() const { return getTrailingObjects<char>(); }
165
166 // Implement isa/cast/dyncast/etc.
167 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
168 static bool classofKind(Kind K) { return K == PragmaComment; }
169};
170
171/// Represents a `#pragma detect_mismatch` line. Always a child of
172/// TranslationUnitDecl.
173class PragmaDetectMismatchDecl final
174 : public Decl,
175 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
176 friend class ASTDeclReader;
177 friend class ASTDeclWriter;
178 friend TrailingObjects;
179
180 size_t ValueStart;
181
182 PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
183 size_t ValueStart)
184 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
185
186 virtual void anchor();
187
188public:
189 static PragmaDetectMismatchDecl *Create(const ASTContext &C,
190 TranslationUnitDecl *DC,
191 SourceLocation Loc, StringRef Name,
192 StringRef Value);
193 static PragmaDetectMismatchDecl *
194 CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
195
196 StringRef getName() const { return getTrailingObjects<char>(); }
197 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
198
199 // Implement isa/cast/dyncast/etc.
200 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
201 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
202};
203
204/// Declaration context for names declared as extern "C" in C++. This
205/// is neither the semantic nor lexical context for such declarations, but is
206/// used to check for conflicts with other extern "C" declarations. Example:
207///
208/// \code
209/// namespace N { extern "C" void f(); } // #1
210/// void N::f() {} // #2
211/// namespace M { extern "C" void f(); } // #3
212/// \endcode
213///
214/// The semantic context of #1 is namespace N and its lexical context is the
215/// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
216/// context is the TU. However, both declarations are also visible in the
217/// extern "C" context.
218///
219/// The declaration at #3 finds it is a redeclaration of \c N::f through
220/// lookup in the extern "C" context.
221class ExternCContextDecl : public Decl, public DeclContext {
222 explicit ExternCContextDecl(TranslationUnitDecl *TU)
223 : Decl(ExternCContext, TU, SourceLocation()),
224 DeclContext(ExternCContext) {}
225
226 virtual void anchor();
227
228public:
229 static ExternCContextDecl *Create(const ASTContext &C,
230 TranslationUnitDecl *TU);
231
232 // Implement isa/cast/dyncast/etc.
233 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
234 static bool classofKind(Kind K) { return K == ExternCContext; }
235 static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
236 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
237 }
238 static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
239 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
240 }
241};
242
243/// This represents a decl that may have a name. Many decls have names such
244/// as ObjCMethodDecl, but not \@class, etc.
245///
246/// Note that not every NamedDecl is actually named (e.g., a struct might
247/// be anonymous), and not every name is an identifier.
248class NamedDecl : public Decl {
249 /// The name of this declaration, which is typically a normal
250 /// identifier but may also be a special kind of name (C++
251 /// constructor, Objective-C selector, etc.)
252 DeclarationName Name;
253
254 virtual void anchor();
255
256private:
257 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__));
258
259protected:
260 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
261 : Decl(DK, DC, L), Name(N) {}
262
263public:
264 /// Get the identifier that names this declaration, if there is one.
265 ///
266 /// This will return NULL if this declaration has no name (e.g., for
267 /// an unnamed class) or if the name is a special name (C++ constructor,
268 /// Objective-C selector, etc.).
269 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
270
271 /// Get the name of identifier for this declaration as a StringRef.
272 ///
273 /// This requires that the declaration have a name and that it be a simple
274 /// identifier.
275 StringRef getName() const {
276 assert(Name.isIdentifier() && "Name is not a simple identifier")(static_cast <bool> (Name.isIdentifier() && "Name is not a simple identifier"
) ? void (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 276, __extension__ __PRETTY_FUNCTION__))
;
277 return getIdentifier() ? getIdentifier()->getName() : "";
278 }
279
280 /// Get a human-readable name for the declaration, even if it is one of the
281 /// special kinds of names (C++ constructor, Objective-C selector, etc).
282 ///
283 /// Creating this name requires expensive string manipulation, so it should
284 /// be called only when performance doesn't matter. For simple declarations,
285 /// getNameAsCString() should suffice.
286 //
287 // FIXME: This function should be renamed to indicate that it is not just an
288 // alternate form of getName(), and clients should move as appropriate.
289 //
290 // FIXME: Deprecated, move clients to getName().
291 std::string getNameAsString() const { return Name.getAsString(); }
292
293 virtual void printName(raw_ostream &os) const;
294
295 /// Get the actual, stored name of the declaration, which may be a special
296 /// name.
297 DeclarationName getDeclName() const { return Name; }
298
299 /// Set the name of this declaration.
300 void setDeclName(DeclarationName N) { Name = N; }
301
302 /// Returns a human-readable qualified name for this declaration, like
303 /// A::B::i, for i being member of namespace A::B.
304 ///
305 /// If the declaration is not a member of context which can be named (record,
306 /// namespace), it will return the same result as printName().
307 ///
308 /// Creating this name is expensive, so it should be called only when
309 /// performance doesn't matter.
310 void printQualifiedName(raw_ostream &OS) const;
311 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
312
313 // FIXME: Remove string version.
314 std::string getQualifiedNameAsString() const;
315
316 /// Appends a human-readable name for this declaration into the given stream.
317 ///
318 /// This is the method invoked by Sema when displaying a NamedDecl
319 /// in a diagnostic. It does not necessarily produce the same
320 /// result as printName(); for example, class template
321 /// specializations are printed with their template arguments.
322 virtual void getNameForDiagnostic(raw_ostream &OS,
323 const PrintingPolicy &Policy,
324 bool Qualified) const;
325
326 /// Determine whether this declaration, if known to be well-formed within
327 /// its context, will replace the declaration OldD if introduced into scope.
328 ///
329 /// A declaration will replace another declaration if, for example, it is
330 /// a redeclaration of the same variable or function, but not if it is a
331 /// declaration of a different kind (function vs. class) or an overloaded
332 /// function.
333 ///
334 /// \param IsKnownNewer \c true if this declaration is known to be newer
335 /// than \p OldD (for instance, if this declaration is newly-created).
336 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
337
338 /// Determine whether this declaration has linkage.
339 bool hasLinkage() const;
340
341 using Decl::isModulePrivate;
342 using Decl::setModulePrivate;
343
344 /// Determine whether this declaration is a C++ class member.
345 bool isCXXClassMember() const {
346 const DeclContext *DC = getDeclContext();
347
348 // C++0x [class.mem]p1:
349 // The enumerators of an unscoped enumeration defined in
350 // the class are members of the class.
351 if (isa<EnumDecl>(DC))
352 DC = DC->getRedeclContext();
353
354 return DC->isRecord();
355 }
356
357 /// Determine whether the given declaration is an instance member of
358 /// a C++ class.
359 bool isCXXInstanceMember() const;
360
361 /// Determine what kind of linkage this entity has.
362 ///
363 /// This is not the linkage as defined by the standard or the codegen notion
364 /// of linkage. It is just an implementation detail that is used to compute
365 /// those.
366 Linkage getLinkageInternal() const;
367
368 /// Get the linkage from a semantic point of view. Entities in
369 /// anonymous namespaces are external (in c++98).
370 Linkage getFormalLinkage() const {
371 return clang::getFormalLinkage(getLinkageInternal());
372 }
373
374 /// True if this decl has external linkage.
375 bool hasExternalFormalLinkage() const {
376 return isExternalFormalLinkage(getLinkageInternal());
377 }
378
379 bool isExternallyVisible() const {
380 return clang::isExternallyVisible(getLinkageInternal());
381 }
382
383 /// Determine whether this declaration can be redeclared in a
384 /// different translation unit.
385 bool isExternallyDeclarable() const {
386 return isExternallyVisible() && !getOwningModuleForLinkage();
387 }
388
389 /// Determines the visibility of this entity.
390 Visibility getVisibility() const {
391 return getLinkageAndVisibility().getVisibility();
392 }
393
394 /// Determines the linkage and visibility of this entity.
395 LinkageInfo getLinkageAndVisibility() const;
396
397 /// Kinds of explicit visibility.
398 enum ExplicitVisibilityKind {
399 /// Do an LV computation for, ultimately, a type.
400 /// Visibility may be restricted by type visibility settings and
401 /// the visibility of template arguments.
402 VisibilityForType,
403
404 /// Do an LV computation for, ultimately, a non-type declaration.
405 /// Visibility may be restricted by value visibility settings and
406 /// the visibility of template arguments.
407 VisibilityForValue
408 };
409
410 /// If visibility was explicitly specified for this
411 /// declaration, return that visibility.
412 Optional<Visibility>
413 getExplicitVisibility(ExplicitVisibilityKind kind) const;
414
415 /// True if the computed linkage is valid. Used for consistency
416 /// checking. Should always return true.
417 bool isLinkageValid() const;
418
419 /// True if something has required us to compute the linkage
420 /// of this declaration.
421 ///
422 /// Language features which can retroactively change linkage (like a
423 /// typedef name for linkage purposes) may need to consider this,
424 /// but hopefully only in transitory ways during parsing.
425 bool hasLinkageBeenComputed() const {
426 return hasCachedLinkage();
427 }
428
429 /// Looks through UsingDecls and ObjCCompatibleAliasDecls for
430 /// the underlying named decl.
431 NamedDecl *getUnderlyingDecl() {
432 // Fast-path the common case.
433 if (this->getKind() != UsingShadow &&
434 this->getKind() != ConstructorUsingShadow &&
435 this->getKind() != ObjCCompatibleAlias &&
436 this->getKind() != NamespaceAlias)
437 return this;
438
439 return getUnderlyingDeclImpl();
440 }
441 const NamedDecl *getUnderlyingDecl() const {
442 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
443 }
444
445 NamedDecl *getMostRecentDecl() {
446 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
447 }
448 const NamedDecl *getMostRecentDecl() const {
449 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
450 }
451
452 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
453
454 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
455 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
456};
457
458inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
459 ND.printName(OS);
460 return OS;
461}
462
463/// Represents the declaration of a label. Labels also have a
464/// corresponding LabelStmt, which indicates the position that the label was
465/// defined at. For normal labels, the location of the decl is the same as the
466/// location of the statement. For GNU local labels (__label__), the decl
467/// location is where the __label__ is.
468class LabelDecl : public NamedDecl {
469 LabelStmt *TheStmt;
470 StringRef MSAsmName;
471 bool MSAsmNameResolved = false;
472
473 /// For normal labels, this is the same as the main declaration
474 /// label, i.e., the location of the identifier; for GNU local labels,
475 /// this is the location of the __label__ keyword.
476 SourceLocation LocStart;
477
478 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
479 LabelStmt *S, SourceLocation StartL)
480 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
481
482 void anchor() override;
483
484public:
485 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
486 SourceLocation IdentL, IdentifierInfo *II);
487 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
488 SourceLocation IdentL, IdentifierInfo *II,
489 SourceLocation GnuLabelL);
490 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
491
492 LabelStmt *getStmt() const { return TheStmt; }
493 void setStmt(LabelStmt *T) { TheStmt = T; }
494
495 bool isGnuLocal() const { return LocStart != getLocation(); }
496 void setLocStart(SourceLocation L) { LocStart = L; }
497
498 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
499 return SourceRange(LocStart, getLocation());
500 }
501
502 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
503 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
504 void setMSAsmLabel(StringRef Name);
505 StringRef getMSAsmLabel() const { return MSAsmName; }
506 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
507
508 // Implement isa/cast/dyncast/etc.
509 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
510 static bool classofKind(Kind K) { return K == Label; }
511};
512
513/// Represent a C++ namespace.
514class NamespaceDecl : public NamedDecl, public DeclContext,
515 public Redeclarable<NamespaceDecl>
516{
517 /// The starting location of the source range, pointing
518 /// to either the namespace or the inline keyword.
519 SourceLocation LocStart;
520
521 /// The ending location of the source range.
522 SourceLocation RBraceLoc;
523
524 /// A pointer to either the anonymous namespace that lives just inside
525 /// this namespace or to the first namespace in the chain (the latter case
526 /// only when this is not the first in the chain), along with a
527 /// boolean value indicating whether this is an inline namespace.
528 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
529
530 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
531 SourceLocation StartLoc, SourceLocation IdLoc,
532 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
533
534 using redeclarable_base = Redeclarable<NamespaceDecl>;
535
536 NamespaceDecl *getNextRedeclarationImpl() override;
537 NamespaceDecl *getPreviousDeclImpl() override;
538 NamespaceDecl *getMostRecentDeclImpl() override;
539
540public:
541 friend class ASTDeclReader;
542 friend class ASTDeclWriter;
543
544 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
545 bool Inline, SourceLocation StartLoc,
546 SourceLocation IdLoc, IdentifierInfo *Id,
547 NamespaceDecl *PrevDecl);
548
549 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
550
551 using redecl_range = redeclarable_base::redecl_range;
552 using redecl_iterator = redeclarable_base::redecl_iterator;
553
554 using redeclarable_base::redecls_begin;
555 using redeclarable_base::redecls_end;
556 using redeclarable_base::redecls;
557 using redeclarable_base::getPreviousDecl;
558 using redeclarable_base::getMostRecentDecl;
559 using redeclarable_base::isFirstDecl;
560
561 /// Returns true if this is an anonymous namespace declaration.
562 ///
563 /// For example:
564 /// \code
565 /// namespace {
566 /// ...
567 /// };
568 /// \endcode
569 /// q.v. C++ [namespace.unnamed]
570 bool isAnonymousNamespace() const {
571 return !getIdentifier();
572 }
573
574 /// Returns true if this is an inline namespace declaration.
575 bool isInline() const {
576 return AnonOrFirstNamespaceAndInline.getInt();
577 }
578
579 /// Set whether this is an inline namespace declaration.
580 void setInline(bool Inline) {
581 AnonOrFirstNamespaceAndInline.setInt(Inline);
582 }
583
584 /// Get the original (first) namespace declaration.
585 NamespaceDecl *getOriginalNamespace();
586
587 /// Get the original (first) namespace declaration.
588 const NamespaceDecl *getOriginalNamespace() const;
589
590 /// Return true if this declaration is an original (first) declaration
591 /// of the namespace. This is false for non-original (subsequent) namespace
592 /// declarations and anonymous namespaces.
593 bool isOriginalNamespace() const;
594
595 /// Retrieve the anonymous namespace nested inside this namespace,
596 /// if any.
597 NamespaceDecl *getAnonymousNamespace() const {
598 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
599 }
600
601 void setAnonymousNamespace(NamespaceDecl *D) {
602 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
603 }
604
605 /// Retrieves the canonical declaration of this namespace.
606 NamespaceDecl *getCanonicalDecl() override {
607 return getOriginalNamespace();
608 }
609 const NamespaceDecl *getCanonicalDecl() const {
610 return getOriginalNamespace();
611 }
612
613 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
614 return SourceRange(LocStart, RBraceLoc);
615 }
616
617 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
618 SourceLocation getRBraceLoc() const { return RBraceLoc; }
619 void setLocStart(SourceLocation L) { LocStart = L; }
620 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
621
622 // Implement isa/cast/dyncast/etc.
623 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
624 static bool classofKind(Kind K) { return K == Namespace; }
625 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
626 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
627 }
628 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
629 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
630 }
631};
632
633/// Represent the declaration of a variable (in which case it is
634/// an lvalue) a function (in which case it is a function designator) or
635/// an enum constant.
636class ValueDecl : public NamedDecl {
637 QualType DeclType;
638
639 void anchor() override;
640
641protected:
642 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
643 DeclarationName N, QualType T)
644 : NamedDecl(DK, DC, L, N), DeclType(T) {}
645
646public:
647 QualType getType() const { return DeclType; }
648 void setType(QualType newType) { DeclType = newType; }
649
650 /// Determine whether this symbol is weakly-imported,
651 /// or declared with the weak or weak-ref attr.
652 bool isWeak() const;
653
654 // Implement isa/cast/dyncast/etc.
655 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
656 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
657};
658
659/// A struct with extended info about a syntactic
660/// name qualifier, to be used for the case of out-of-line declarations.
661struct QualifierInfo {
662 NestedNameSpecifierLoc QualifierLoc;
663
664 /// The number of "outer" template parameter lists.
665 /// The count includes all of the template parameter lists that were matched
666 /// against the template-ids occurring into the NNS and possibly (in the
667 /// case of an explicit specialization) a final "template <>".
668 unsigned NumTemplParamLists = 0;
669
670 /// A new-allocated array of size NumTemplParamLists,
671 /// containing pointers to the "outer" template parameter lists.
672 /// It includes all of the template parameter lists that were matched
673 /// against the template-ids occurring into the NNS and possibly (in the
674 /// case of an explicit specialization) a final "template <>".
675 TemplateParameterList** TemplParamLists = nullptr;
676
677 QualifierInfo() = default;
678 QualifierInfo(const QualifierInfo &) = delete;
679 QualifierInfo& operator=(const QualifierInfo &) = delete;
680
681 /// Sets info about "outer" template parameter lists.
682 void setTemplateParameterListsInfo(ASTContext &Context,
683 ArrayRef<TemplateParameterList *> TPLists);
684};
685
686/// Represents a ValueDecl that came out of a declarator.
687/// Contains type source information through TypeSourceInfo.
688class DeclaratorDecl : public ValueDecl {
689 // A struct representing both a TInfo and a syntactic qualifier,
690 // to be used for the (uncommon) case of out-of-line declarations.
691 struct ExtInfo : public QualifierInfo {
692 TypeSourceInfo *TInfo;
693 };
694
695 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
696
697 /// The start of the source range for this declaration,
698 /// ignoring outer template declarations.
699 SourceLocation InnerLocStart;
700
701 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
702 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
703 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
704
705protected:
706 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
707 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
708 SourceLocation StartL)
709 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
710
711public:
712 friend class ASTDeclReader;
713 friend class ASTDeclWriter;
714
715 TypeSourceInfo *getTypeSourceInfo() const {
716 return hasExtInfo()
717 ? getExtInfo()->TInfo
718 : DeclInfo.get<TypeSourceInfo*>();
719 }
720
721 void setTypeSourceInfo(TypeSourceInfo *TI) {
722 if (hasExtInfo())
723 getExtInfo()->TInfo = TI;
724 else
725 DeclInfo = TI;
726 }
727
728 /// Return start of source range ignoring outer template declarations.
729 SourceLocation getInnerLocStart() const { return InnerLocStart; }
730 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
731
732 /// Return start of source range taking into account any outer template
733 /// declarations.
734 SourceLocation getOuterLocStart() const;
735
736 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
737
738 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
739 return getOuterLocStart();
740 }
741
742 /// Retrieve the nested-name-specifier that qualifies the name of this
743 /// declaration, if it was present in the source.
744 NestedNameSpecifier *getQualifier() const {
745 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
746 : nullptr;
747 }
748
749 /// Retrieve the nested-name-specifier (with source-location
750 /// information) that qualifies the name of this declaration, if it was
751 /// present in the source.
752 NestedNameSpecifierLoc getQualifierLoc() const {
753 return hasExtInfo() ? getExtInfo()->QualifierLoc
754 : NestedNameSpecifierLoc();
755 }
756
757 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
758
759 unsigned getNumTemplateParameterLists() const {
760 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
761 }
762
763 TemplateParameterList *getTemplateParameterList(unsigned index) const {
764 assert(index < getNumTemplateParameterLists())(static_cast <bool> (index < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 764, __extension__ __PRETTY_FUNCTION__))
;
765 return getExtInfo()->TemplParamLists[index];
766 }
767
768 void setTemplateParameterListsInfo(ASTContext &Context,
769 ArrayRef<TemplateParameterList *> TPLists);
770
771 SourceLocation getTypeSpecStartLoc() const;
772
773 // Implement isa/cast/dyncast/etc.
774 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
775 static bool classofKind(Kind K) {
776 return K >= firstDeclarator && K <= lastDeclarator;
777 }
778};
779
780/// Structure used to store a statement, the constant value to
781/// which it was evaluated (if any), and whether or not the statement
782/// is an integral constant expression (if known).
783struct EvaluatedStmt {
784 /// Whether this statement was already evaluated.
785 bool WasEvaluated : 1;
786
787 /// Whether this statement is being evaluated.
788 bool IsEvaluating : 1;
789
790 /// Whether we already checked whether this statement was an
791 /// integral constant expression.
792 bool CheckedICE : 1;
793
794 /// Whether we are checking whether this statement is an
795 /// integral constant expression.
796 bool CheckingICE : 1;
797
798 /// Whether this statement is an integral constant expression,
799 /// or in C++11, whether the statement is a constant expression. Only
800 /// valid if CheckedICE is true.
801 bool IsICE : 1;
802
803 Stmt *Value;
804 APValue Evaluated;
805
806 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
807 CheckingICE(false), IsICE(false) {}
808
809};
810
811/// Represents a variable declaration or definition.
812class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
813public:
814 /// Initialization styles.
815 enum InitializationStyle {
816 /// C-style initialization with assignment
817 CInit,
818
819 /// Call-style initialization (C++98)
820 CallInit,
821
822 /// Direct list-initialization (C++11)
823 ListInit
824 };
825
826 /// Kinds of thread-local storage.
827 enum TLSKind {
828 /// Not a TLS variable.
829 TLS_None,
830
831 /// TLS with a known-constant initializer.
832 TLS_Static,
833
834 /// TLS with a dynamic initializer.
835 TLS_Dynamic
836 };
837
838 /// Return the string used to specify the storage class \p SC.
839 ///
840 /// It is illegal to call this function with SC == None.
841 static const char *getStorageClassSpecifierString(StorageClass SC);
842
843protected:
844 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
845 // have allocated the auxiliary struct of information there.
846 //
847 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
848 // this as *many* VarDecls are ParmVarDecls that don't have default
849 // arguments. We could save some space by moving this pointer union to be
850 // allocated in trailing space when necessary.
851 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
852
853 /// The initializer for this variable or, for a ParmVarDecl, the
854 /// C++ default argument.
855 mutable InitType Init;
856
857private:
858 friend class ASTDeclReader;
859 friend class ASTNodeImporter;
860 friend class StmtIteratorBase;
861
862 class VarDeclBitfields {
863 friend class ASTDeclReader;
864 friend class VarDecl;
865
866 unsigned SClass : 3;
867 unsigned TSCSpec : 2;
868 unsigned InitStyle : 2;
869 };
870 enum { NumVarDeclBits = 7 };
871
872protected:
873 enum { NumParameterIndexBits = 8 };
874
875 enum DefaultArgKind {
876 DAK_None,
877 DAK_Unparsed,
878 DAK_Uninstantiated,
879 DAK_Normal
880 };
881
882 class ParmVarDeclBitfields {
883 friend class ASTDeclReader;
884 friend class ParmVarDecl;
885
886 unsigned : NumVarDeclBits;
887
888 /// Whether this parameter inherits a default argument from a
889 /// prior declaration.
890 unsigned HasInheritedDefaultArg : 1;
891
892 /// Describes the kind of default argument for this parameter. By default
893 /// this is none. If this is normal, then the default argument is stored in
894 /// the \c VarDecl initializer expression unless we were unable to parse
895 /// (even an invalid) expression for the default argument.
896 unsigned DefaultArgKind : 2;
897
898 /// Whether this parameter undergoes K&R argument promotion.
899 unsigned IsKNRPromoted : 1;
900
901 /// Whether this parameter is an ObjC method parameter or not.
902 unsigned IsObjCMethodParam : 1;
903
904 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
905 /// Otherwise, the number of function parameter scopes enclosing
906 /// the function parameter scope in which this parameter was
907 /// declared.
908 unsigned ScopeDepthOrObjCQuals : 7;
909
910 /// The number of parameters preceding this parameter in the
911 /// function parameter scope in which it was declared.
912 unsigned ParameterIndex : NumParameterIndexBits;
913 };
914
915 class NonParmVarDeclBitfields {
916 friend class ASTDeclReader;
917 friend class ImplicitParamDecl;
918 friend class VarDecl;
919
920 unsigned : NumVarDeclBits;
921
922 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
923 /// Whether this variable is a definition which was demoted due to
924 /// module merge.
925 unsigned IsThisDeclarationADemotedDefinition : 1;
926
927 /// Whether this variable is the exception variable in a C++ catch
928 /// or an Objective-C @catch statement.
929 unsigned ExceptionVar : 1;
930
931 /// Whether this local variable could be allocated in the return
932 /// slot of its function, enabling the named return value optimization
933 /// (NRVO).
934 unsigned NRVOVariable : 1;
935
936 /// Whether this variable is the for-range-declaration in a C++0x
937 /// for-range statement.
938 unsigned CXXForRangeDecl : 1;
939
940 /// Whether this variable is an ARC pseudo-__strong
941 /// variable; see isARCPseudoStrong() for details.
942 unsigned ARCPseudoStrong : 1;
943
944 /// Whether this variable is (C++1z) inline.
945 unsigned IsInline : 1;
946
947 /// Whether this variable has (C++1z) inline explicitly specified.
948 unsigned IsInlineSpecified : 1;
949
950 /// Whether this variable is (C++0x) constexpr.
951 unsigned IsConstexpr : 1;
952
953 /// Whether this variable is the implicit variable for a lambda
954 /// init-capture.
955 unsigned IsInitCapture : 1;
956
957 /// Whether this local extern variable's previous declaration was
958 /// declared in the same block scope. This controls whether we should merge
959 /// the type of this declaration with its previous declaration.
960 unsigned PreviousDeclInSameBlockScope : 1;
961
962 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
963 /// something else.
964 unsigned ImplicitParamKind : 3;
965 };
966
967 union {
968 unsigned AllBits;
969 VarDeclBitfields VarDeclBits;
970 ParmVarDeclBitfields ParmVarDeclBits;
971 NonParmVarDeclBitfields NonParmVarDeclBits;
972 };
973
974 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
975 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
976 TypeSourceInfo *TInfo, StorageClass SC);
977
978 using redeclarable_base = Redeclarable<VarDecl>;
979
980 VarDecl *getNextRedeclarationImpl() override {
981 return getNextRedeclaration();
982 }
983
984 VarDecl *getPreviousDeclImpl() override {
985 return getPreviousDecl();
986 }
987
988 VarDecl *getMostRecentDeclImpl() override {
989 return getMostRecentDecl();
990 }
991
992public:
993 using redecl_range = redeclarable_base::redecl_range;
994 using redecl_iterator = redeclarable_base::redecl_iterator;
995
996 using redeclarable_base::redecls_begin;
997 using redeclarable_base::redecls_end;
998 using redeclarable_base::redecls;
999 using redeclarable_base::getPreviousDecl;
1000 using redeclarable_base::getMostRecentDecl;
1001 using redeclarable_base::isFirstDecl;
1002
1003 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1004 SourceLocation StartLoc, SourceLocation IdLoc,
1005 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1006 StorageClass S);
1007
1008 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1009
1010 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1011
1012 /// Returns the storage class as written in the source. For the
1013 /// computed linkage of symbol, see getLinkage.
1014 StorageClass getStorageClass() const {
1015 return (StorageClass) VarDeclBits.SClass;
1016 }
1017 void setStorageClass(StorageClass SC);
1018
1019 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1020 VarDeclBits.TSCSpec = TSC;
1021 assert(VarDeclBits.TSCSpec == TSC && "truncation")(static_cast <bool> (VarDeclBits.TSCSpec == TSC &&
"truncation") ? void (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1021, __extension__ __PRETTY_FUNCTION__))
;
1022 }
1023 ThreadStorageClassSpecifier getTSCSpec() const {
1024 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1025 }
1026 TLSKind getTLSKind() const;
1027
1028 /// Returns true if a variable with function scope is a non-static local
1029 /// variable.
1030 bool hasLocalStorage() const {
1031 if (getStorageClass() == SC_None) {
1032 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1033 // used to describe variables allocated in global memory and which are
1034 // accessed inside a kernel(s) as read-only variables. As such, variables
1035 // in constant address space cannot have local storage.
1036 if (getType().getAddressSpace() == LangAS::opencl_constant)
1037 return false;
1038 // Second check is for C++11 [dcl.stc]p4.
1039 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1040 }
1041
1042 // Global Named Register (GNU extension)
1043 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1044 return false;
1045
1046 // Return true for: Auto, Register.
1047 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1048
1049 return getStorageClass() >= SC_Auto;
1050 }
1051
1052 /// Returns true if a variable with function scope is a static local
1053 /// variable.
1054 bool isStaticLocal() const {
1055 return (getStorageClass() == SC_Static ||
1056 // C++11 [dcl.stc]p4
1057 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1058 && !isFileVarDecl();
1059 }
1060
1061 /// Returns true if a variable has extern or __private_extern__
1062 /// storage.
1063 bool hasExternalStorage() const {
1064 return getStorageClass() == SC_Extern ||
1065 getStorageClass() == SC_PrivateExtern;
1066 }
1067
1068 /// Returns true for all variables that do not have local storage.
1069 ///
1070 /// This includes all global variables as well as static variables declared
1071 /// within a function.
1072 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1073
1074 /// Get the storage duration of this variable, per C++ [basic.stc].
1075 StorageDuration getStorageDuration() const {
1076 return hasLocalStorage() ? SD_Automatic :
1077 getTSCSpec() ? SD_Thread : SD_Static;
1078 }
1079
1080 /// Compute the language linkage.
1081 LanguageLinkage getLanguageLinkage() const;
1082
1083 /// Determines whether this variable is a variable with external, C linkage.
1084 bool isExternC() const;
1085
1086 /// Determines whether this variable's context is, or is nested within,
1087 /// a C++ extern "C" linkage spec.
1088 bool isInExternCContext() const;
1089
1090 /// Determines whether this variable's context is, or is nested within,
1091 /// a C++ extern "C++" linkage spec.
1092 bool isInExternCXXContext() const;
1093
1094 /// Returns true for local variable declarations other than parameters.
1095 /// Note that this includes static variables inside of functions. It also
1096 /// includes variables inside blocks.
1097 ///
1098 /// void foo() { int x; static int y; extern int z; }
1099 bool isLocalVarDecl() const {
1100 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1101 return false;
1102 if (const DeclContext *DC = getLexicalDeclContext())
1103 return DC->getRedeclContext()->isFunctionOrMethod();
1104 return false;
1105 }
1106
1107 /// Similar to isLocalVarDecl but also includes parameters.
1108 bool isLocalVarDeclOrParm() const {
1109 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1110 }
1111
1112 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1113 bool isFunctionOrMethodVarDecl() const {
1114 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1115 return false;
1116 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1117 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1118 }
1119
1120 /// Determines whether this is a static data member.
1121 ///
1122 /// This will only be true in C++, and applies to, e.g., the
1123 /// variable 'x' in:
1124 /// \code
1125 /// struct S {
1126 /// static int x;
1127 /// };
1128 /// \endcode
1129 bool isStaticDataMember() const {
1130 // If it wasn't static, it would be a FieldDecl.
1131 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1132 }
1133
1134 VarDecl *getCanonicalDecl() override;
1135 const VarDecl *getCanonicalDecl() const {
1136 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1137 }
1138
1139 enum DefinitionKind {
1140 /// This declaration is only a declaration.
1141 DeclarationOnly,
1142
1143 /// This declaration is a tentative definition.
1144 TentativeDefinition,
1145
1146 /// This declaration is definitely a definition.
1147 Definition
1148 };
1149
1150 /// Check whether this declaration is a definition. If this could be
1151 /// a tentative definition (in C), don't check whether there's an overriding
1152 /// definition.
1153 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1154 DefinitionKind isThisDeclarationADefinition() const {
1155 return isThisDeclarationADefinition(getASTContext());
1156 }
1157
1158 /// Check whether this variable is defined in this translation unit.
1159 DefinitionKind hasDefinition(ASTContext &) const;
1160 DefinitionKind hasDefinition() const {
1161 return hasDefinition(getASTContext());
1162 }
1163
1164 /// Get the tentative definition that acts as the real definition in a TU.
1165 /// Returns null if there is a proper definition available.
1166 VarDecl *getActingDefinition();
1167 const VarDecl *getActingDefinition() const {
1168 return const_cast<VarDecl*>(this)->getActingDefinition();
1169 }
1170
1171 /// Get the real (not just tentative) definition for this declaration.
1172 VarDecl *getDefinition(ASTContext &);
1173 const VarDecl *getDefinition(ASTContext &C) const {
1174 return const_cast<VarDecl*>(this)->getDefinition(C);
1175 }
1176 VarDecl *getDefinition() {
1177 return getDefinition(getASTContext());
1178 }
1179 const VarDecl *getDefinition() const {
1180 return const_cast<VarDecl*>(this)->getDefinition();
1181 }
1182
1183 /// Determine whether this is or was instantiated from an out-of-line
1184 /// definition of a static data member.
1185 bool isOutOfLine() const override;
1186
1187 /// Returns true for file scoped variable declaration.
1188 bool isFileVarDecl() const {
1189 Kind K = getKind();
1190 if (K == ParmVar || K == ImplicitParam)
1191 return false;
1192
1193 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1194 return true;
1195
1196 if (isStaticDataMember())
1197 return true;
1198
1199 return false;
1200 }
1201
1202 /// Get the initializer for this variable, no matter which
1203 /// declaration it is attached to.
1204 const Expr *getAnyInitializer() const {
1205 const VarDecl *D;
1206 return getAnyInitializer(D);
1207 }
1208
1209 /// Get the initializer for this variable, no matter which
1210 /// declaration it is attached to. Also get that declaration.
1211 const Expr *getAnyInitializer(const VarDecl *&D) const;
1212
1213 bool hasInit() const;
1214 const Expr *getInit() const {
1215 return const_cast<VarDecl *>(this)->getInit();
1216 }
1217 Expr *getInit();
1218
1219 /// Retrieve the address of the initializer expression.
1220 Stmt **getInitAddress();
1221
1222 void setInit(Expr *I);
1223
1224 /// Determine whether this variable's value can be used in a
1225 /// constant expression, according to the relevant language standard.
1226 /// This only checks properties of the declaration, and does not check
1227 /// whether the initializer is in fact a constant expression.
1228 bool isUsableInConstantExpressions(ASTContext &C) const;
1229
1230 EvaluatedStmt *ensureEvaluatedStmt() const;
1231
1232 /// \brief Attempt to evaluate the value of the initializer attached to this
1233 /// declaration, and produce notes explaining why it cannot be evaluated or is
1234 /// not a constant expression. Returns a pointer to the value if evaluation
1235 /// succeeded, 0 otherwise.
1236 APValue *evaluateValue() const;
1237 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1238
1239 /// \brief Return the already-evaluated value of this variable's
1240 /// initializer, or NULL if the value is not yet known. Returns pointer
1241 /// to untyped APValue if the value could not be evaluated.
1242 APValue *getEvaluatedValue() const;
1243
1244 /// \brief Determines whether it is already known whether the
1245 /// initializer is an integral constant expression or not.
1246 bool isInitKnownICE() const;
1247
1248 /// \brief Determines whether the initializer is an integral constant
1249 /// expression, or in C++11, whether the initializer is a constant
1250 /// expression.
1251 ///
1252 /// \pre isInitKnownICE()
1253 bool isInitICE() const;
1254
1255 /// \brief Determine whether the value of the initializer attached to this
1256 /// declaration is an integral constant expression.
1257 bool checkInitIsICE() const;
1258
1259 void setInitStyle(InitializationStyle Style) {
1260 VarDeclBits.InitStyle = Style;
1261 }
1262
1263 /// \brief The style of initialization for this declaration.
1264 ///
1265 /// C-style initialization is "int x = 1;". Call-style initialization is
1266 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1267 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1268 /// expression for class types. List-style initialization is C++11 syntax,
1269 /// e.g. "int x{1};". Clients can distinguish between different forms of
1270 /// initialization by checking this value. In particular, "int x = {1};" is
1271 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1272 /// Init expression in all three cases is an InitListExpr.
1273 InitializationStyle getInitStyle() const {
1274 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1275 }
1276
1277 /// \brief Whether the initializer is a direct-initializer (list or call).
1278 bool isDirectInit() const {
1279 return getInitStyle() != CInit;
1280 }
1281
1282 /// \brief If this definition should pretend to be a declaration.
1283 bool isThisDeclarationADemotedDefinition() const {
1284 return isa<ParmVarDecl>(this) ? false :
1285 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1286 }
1287
1288 /// \brief This is a definition which should be demoted to a declaration.
1289 ///
1290 /// In some cases (mostly module merging) we can end up with two visible
1291 /// definitions one of which needs to be demoted to a declaration to keep
1292 /// the AST invariants.
1293 void demoteThisDefinitionToDeclaration() {
1294 assert(isThisDeclarationADefinition() && "Not a definition!")(static_cast <bool> (isThisDeclarationADefinition() &&
"Not a definition!") ? void (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1294, __extension__ __PRETTY_FUNCTION__))
;
1295 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")(static_cast <bool> (!isa<ParmVarDecl>(this) &&
"Cannot demote ParmVarDecls!") ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1295, __extension__ __PRETTY_FUNCTION__))
;
1296 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1297 }
1298
1299 /// \brief Determine whether this variable is the exception variable in a
1300 /// C++ catch statememt or an Objective-C \@catch statement.
1301 bool isExceptionVariable() const {
1302 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1303 }
1304 void setExceptionVariable(bool EV) {
1305 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1305, __extension__ __PRETTY_FUNCTION__))
;
1306 NonParmVarDeclBits.ExceptionVar = EV;
1307 }
1308
1309 /// \brief Determine whether this local variable can be used with the named
1310 /// return value optimization (NRVO).
1311 ///
1312 /// The named return value optimization (NRVO) works by marking certain
1313 /// non-volatile local variables of class type as NRVO objects. These
1314 /// locals can be allocated within the return slot of their containing
1315 /// function, in which case there is no need to copy the object to the
1316 /// return slot when returning from the function. Within the function body,
1317 /// each return that returns the NRVO object will have this variable as its
1318 /// NRVO candidate.