Bug Summary

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

Annotated Source Code

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