blob: a8d4ed12808e79255c371591855e132b46ee0c98 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Guy Benyei11169dd2012-12-18 14:30:41 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This coordinates the debug information generation while generating code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGDebugInfo.h"
14#include "CGBlocks.h"
David Blaikie38079fd2013-05-10 21:53:14 +000015#include "CGCXXABI.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000016#include "CGObjCRuntime.h"
Bob Haarmandff36732016-10-25 22:19:32 +000017#include "CGRecordLayout.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000018#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000020#include "ConstantEmitter.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000021#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"
Richard Trieu63688182018-12-11 03:18:39 +000027#include "clang/Basic/CodeGenOptions.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/Basic/FileManager.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/Version.h"
Taewook Oh0fb5b782017-08-16 19:36:24 +000031#include "clang/Frontend/FrontendOptions.h"
Adrian Prantlc4bb47e2015-06-30 17:39:51 +000032#include "clang/Lex/HeaderSearchOptions.h"
Adrian Prantl9402cef2015-09-20 16:51:35 +000033#include "clang/Lex/ModuleMap.h"
Adrian Prantlc4bb47e2015-06-30 17:39:51 +000034#include "clang/Lex/PreprocessorOptions.h"
Bob Haarmandff36732016-10-25 22:19:32 +000035#include "llvm/ADT/DenseSet.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "llvm/ADT/SmallVector.h"
37#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000038#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/DerivedTypes.h"
41#include "llvm/IR/Instructions.h"
42#include "llvm/IR/Intrinsics.h"
Matthew Voss20165362018-10-03 18:45:04 +000043#include "llvm/IR/Metadata.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000044#include "llvm/IR/Module.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "llvm/Support/FileSystem.h"
Amjad Aboude2aab8c2016-12-25 10:12:27 +000046#include "llvm/Support/MD5.h"
Adrian Prantl0630eb72013-12-18 21:48:18 +000047#include "llvm/Support/Path.h"
Luboš Luňák4f2104c2019-11-02 16:39:59 +010048#include "llvm/Support/TimeProfiler.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000049using namespace clang;
50using namespace clang::CodeGen;
51
Victor Leschuka7ece032016-10-20 00:13:19 +000052static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
53 auto TI = Ctx.getTypeInfo(Ty);
54 return TI.AlignIsRequired ? TI.Align : 0;
55}
56
57static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
58 return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
59}
60
61static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
62 return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
63}
64
Guy Benyei11169dd2012-12-18 14:30:41 +000065CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher324bbbd2013-07-14 21:12:44 +000066 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
Adrian Prantl6b21ab22015-08-27 19:46:20 +000067 DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
Eric Christopher324bbbd2013-07-14 21:12:44 +000068 DBuilder(CGM.getModule()) {
Saleem Abdulrasool436256a2015-10-12 20:21:08 +000069 for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
70 DebugPrefixMap[KV.first] = KV.second;
Guy Benyei11169dd2012-12-18 14:30:41 +000071 CreateCompileUnit();
72}
73
74CGDebugInfo::~CGDebugInfo() {
75 assert(LexicalBlockStack.empty() &&
76 "Region stack mismatch, stack not empty!");
77}
78
David Blaikie66e41972015-01-14 07:38:27 +000079ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
Calixte Denizetfcd661d2018-09-24 18:24:18 +000080 SourceLocation TemporaryLocation)
David Blaikied7057d92015-08-12 23:49:57 +000081 : CGF(&CGF) {
Calixte Denizetfcd661d2018-09-24 18:24:18 +000082 init(TemporaryLocation);
David Blaikie9b479662015-01-25 01:19:10 +000083}
84
Adrian Prantl39428e72015-02-03 18:40:42 +000085ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
Adrian Prantl95b24e92015-02-03 20:00:54 +000086 bool DefaultToEmpty,
Calixte Denizetfcd661d2018-09-24 18:24:18 +000087 SourceLocation TemporaryLocation)
David Blaikied7057d92015-08-12 23:49:57 +000088 : CGF(&CGF) {
Calixte Denizetfcd661d2018-09-24 18:24:18 +000089 init(TemporaryLocation, DefaultToEmpty);
Adrian Prantl39428e72015-02-03 18:40:42 +000090}
91
92void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
Calixte Denizetfcd661d2018-09-24 18:24:18 +000093 bool DefaultToEmpty) {
David Blaikied7057d92015-08-12 23:49:57 +000094 auto *DI = CGF->getDebugInfo();
95 if (!DI) {
96 CGF = nullptr;
97 return;
David Blaikie66e41972015-01-14 07:38:27 +000098 }
David Blaikied7057d92015-08-12 23:49:57 +000099
100 OriginalLocation = CGF->Builder.getCurrentDebugLocation();
Bob Haarmanc6c9b8f2017-09-11 22:11:57 +0000101
102 if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())
103 return;
104
David Blaikied7057d92015-08-12 23:49:57 +0000105 if (TemporaryLocation.isValid()) {
Calixte Denizetfcd661d2018-09-24 18:24:18 +0000106 DI->EmitLocation(CGF->Builder, TemporaryLocation);
David Blaikied7057d92015-08-12 23:49:57 +0000107 return;
108 }
109
110 if (DefaultToEmpty) {
111 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
112 return;
113 }
114
115 // Construct a location that has a valid scope, but no line info.
116 assert(!DI->LexicalBlockStack.empty());
Adrian Prantlb7acfc02017-02-27 21:30:05 +0000117 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
118 0, 0, DI->LexicalBlockStack.back(), DI->getInlinedAt()));
Adrian Prantl2e0637f2013-07-18 00:28:02 +0000119}
120
David Blaikie9b479662015-01-25 01:19:10 +0000121ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
David Blaikied7057d92015-08-12 23:49:57 +0000122 : CGF(&CGF) {
David Blaikie9b479662015-01-25 01:19:10 +0000123 init(E->getExprLoc());
124}
125
David Blaikie66e41972015-01-14 07:38:27 +0000126ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
David Blaikied7057d92015-08-12 23:49:57 +0000127 : CGF(&CGF) {
128 if (!CGF.getDebugInfo()) {
129 this->CGF = nullptr;
130 return;
David Blaikie66e41972015-01-14 07:38:27 +0000131 }
David Blaikied7057d92015-08-12 23:49:57 +0000132 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
133 if (Loc)
134 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
David Blaikie66e41972015-01-14 07:38:27 +0000135}
136
137ApplyDebugLocation::~ApplyDebugLocation() {
138 // Query CGF so the location isn't overwritten when location updates are
139 // temporarily disabled (for C++ default function arguments)
David Blaikied7057d92015-08-12 23:49:57 +0000140 if (CGF)
141 CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
David Blaikie66e41972015-01-14 07:38:27 +0000142}
143
Adrian Prantlb7acfc02017-02-27 21:30:05 +0000144ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,
145 GlobalDecl InlinedFn)
146 : CGF(&CGF) {
147 if (!CGF.getDebugInfo()) {
148 this->CGF = nullptr;
149 return;
150 }
151 auto &DI = *CGF.getDebugInfo();
152 SavedLocation = DI.getLocation();
153 assert((DI.getInlinedAt() ==
154 CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
155 "CGDebugInfo and IRBuilder are out of sync");
156
157 DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
158}
159
160ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
161 if (!CGF)
162 return;
163 auto &DI = *CGF->getDebugInfo();
164 DI.EmitInlineFunctionEnd(CGF->Builder);
165 DI.EmitLocation(CGF->Builder, SavedLocation);
166}
167
Guy Benyei11169dd2012-12-18 14:30:41 +0000168void CGDebugInfo::setLocation(SourceLocation Loc) {
169 // If the new location isn't valid return.
Eric Christophere7b87e52014-10-26 23:40:33 +0000170 if (Loc.isInvalid())
171 return;
Guy Benyei11169dd2012-12-18 14:30:41 +0000172
173 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
174
175 // If we've changed files in the middle of a lexical scope go ahead
176 // and create a new lexical scope with file node if it's different
177 // from the one in the scope.
Eric Christophere7b87e52014-10-26 23:40:33 +0000178 if (LexicalBlockStack.empty())
179 return;
Guy Benyei11169dd2012-12-18 14:30:41 +0000180
181 SourceManager &SM = CGM.getContext().getSourceManager();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000182 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
Guy Benyei11169dd2012-12-18 14:30:41 +0000183 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
Adrian Prantl212c1042018-12-06 18:44:50 +0000184 if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
Guy Benyei11169dd2012-12-18 14:30:41 +0000185 return;
186
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000187 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000188 LexicalBlockStack.pop_back();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +0000189 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
190 LBF->getScope(), getOrCreateFile(CurLoc)));
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000191 } else if (isa<llvm::DILexicalBlock>(Scope) ||
192 isa<llvm::DISubprogram>(Scope)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000193 LexicalBlockStack.pop_back();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +0000194 LexicalBlockStack.emplace_back(
195 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000196 }
197}
198
Adrian Prantl6ec370a2015-09-10 18:39:45 +0000199llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
Adrian Prantl5c8bd882015-09-11 17:23:08 +0000200 llvm::DIScope *Mod = getParentModuleOrNull(D);
201 return getContextDescriptor(cast<Decl>(D->getDeclContext()),
202 Mod ? Mod : TheCU);
Adrian Prantl6ec370a2015-09-10 18:39:45 +0000203}
204
205llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
206 llvm::DIScope *Default) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000207 if (!Context)
Adrian Prantl6ec370a2015-09-10 18:39:45 +0000208 return Default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000209
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000210 auto I = RegionMap.find(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +0000211 if (I != RegionMap.end()) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000212 llvm::Metadata *V = I->second;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000213 return dyn_cast_or_null<llvm::DIScope>(V);
Guy Benyei11169dd2012-12-18 14:30:41 +0000214 }
215
216 // Check namespace.
Adrian Prantlddb8e062017-05-12 16:23:53 +0000217 if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
218 return getOrCreateNamespace(NSDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +0000219
David Majnemer58ed0f32016-07-17 00:39:12 +0000220 if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
David Blaikiebfa52742013-04-19 06:56:38 +0000221 if (!RDecl->isDependentType())
222 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000223 TheCU->getFile());
Adrian Prantl6ec370a2015-09-10 18:39:45 +0000224 return Default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000225}
226
Reid Kleckner59d12202017-08-08 01:33:53 +0000227PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
228 PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
229
230 // If we're emitting codeview, it's important to try to match MSVC's naming so
231 // that visualizers written for MSVC will trigger for our class names. In
232 // particular, we can't have spaces between arguments of standard templates
233 // like basic_string and vector.
234 if (CGM.getCodeGenOpts().EmitCodeView)
235 PP.MSVCFormatting = true;
236
Adrian Prantl56acd5a2018-12-05 18:37:44 +0000237 // Apply -fdebug-prefix-map.
Richard Smithdbcb6902019-10-15 17:51:08 -0700238 PP.Callbacks = &PrintCB;
Reid Kleckner59d12202017-08-08 01:33:53 +0000239 return PP;
240}
241
Guy Benyei11169dd2012-12-18 14:30:41 +0000242StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
Eric Christophere7b87e52014-10-26 23:40:33 +0000243 assert(FD && "Invalid FunctionDecl!");
Guy Benyei11169dd2012-12-18 14:30:41 +0000244 IdentifierInfo *FII = FD->getIdentifier();
Eric Christophere7b87e52014-10-26 23:40:33 +0000245 FunctionTemplateSpecializationInfo *Info =
246 FD->getTemplateSpecializationInfo();
Reid Kleckner60103382015-12-16 02:04:40 +0000247
Reid Kleckner31abd802016-06-30 17:41:31 +0000248 // Emit the unqualified name in normal operation. LLVM and the debugger can
249 // compute the fully qualified name from the scope chain. If we're only
250 // emitting line table info, there won't be any scope chains, so emit the
251 // fully qualified name here so that stack traces are more accurate.
252 // FIXME: Do this when emitting DWARF as well as when emitting CodeView after
253 // evaluating the size impact.
254 bool UseQualifiedName = DebugKind == codegenoptions::DebugLineTablesOnly &&
255 CGM.getCodeGenOpts().EmitCodeView;
256
257 if (!Info && FII && !UseQualifiedName)
Guy Benyei11169dd2012-12-18 14:30:41 +0000258 return FII->getName();
259
Benjamin Kramer9170e912013-02-22 15:46:01 +0000260 SmallString<128> NS;
261 llvm::raw_svector_ostream OS(NS);
Reid Kleckner31abd802016-06-30 17:41:31 +0000262 if (!UseQualifiedName)
263 FD->printName(OS);
264 else
Reid Kleckner59d12202017-08-08 01:33:53 +0000265 FD->printQualifiedName(OS, getPrintingPolicy());
Guy Benyei11169dd2012-12-18 14:30:41 +0000266
Reid Kleckner829398e2016-06-17 16:11:20 +0000267 // Add any template specialization args.
268 if (Info) {
269 const TemplateArgumentList *TArgs = Info->TemplateArguments;
Serge Pavlov03e672c2017-11-28 16:14:14 +0000270 printTemplateArgumentList(OS, TArgs->asArray(), getPrintingPolicy());
Guy Benyei11169dd2012-12-18 14:30:41 +0000271 }
272
273 // Copy this name on the side and use its reference.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000274 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000275}
276
277StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
278 SmallString<256> MethodName;
279 llvm::raw_svector_ostream OS(MethodName);
280 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
281 const DeclContext *DC = OMD->getDeclContext();
David Majnemer58ed0f32016-07-17 00:39:12 +0000282 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
Eric Christophere7b87e52014-10-26 23:40:33 +0000283 OS << OID->getName();
David Majnemer58ed0f32016-07-17 00:39:12 +0000284 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
Eric Christophere7b87e52014-10-26 23:40:33 +0000285 OS << OID->getName();
David Majnemer58ed0f32016-07-17 00:39:12 +0000286 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
Douglas Gregoracf4fd32015-11-03 01:15:46 +0000287 if (OC->IsClassExtension()) {
288 OS << OC->getClassInterface()->getName();
289 } else {
David Majnemer58ed0f32016-07-17 00:39:12 +0000290 OS << OC->getIdentifier()->getNameStart() << '('
Douglas Gregoracf4fd32015-11-03 01:15:46 +0000291 << OC->getIdentifier()->getNameStart() << ')';
292 }
David Majnemer58ed0f32016-07-17 00:39:12 +0000293 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000294 OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
Adrian Prantlb39fc142013-05-17 23:58:45 +0000295 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl6e785ec2013-05-17 23:49:10 +0000296 // We can extract the type of the class from the self pointer.
Eric Christophere7b87e52014-10-26 23:40:33 +0000297 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
Adrian Prantl6e785ec2013-05-17 23:49:10 +0000298 QualType ClassTy =
Eric Christophere7b87e52014-10-26 23:40:33 +0000299 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
Adrian Prantl6e785ec2013-05-17 23:49:10 +0000300 ClassTy.print(OS, PrintingPolicy(LangOptions()));
301 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000302 }
303 OS << ' ' << OMD->getSelector().getAsString() << ']';
304
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000305 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000306}
307
Guy Benyei11169dd2012-12-18 14:30:41 +0000308StringRef CGDebugInfo::getSelectorName(Selector S) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000309 return internString(S.getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +0000310}
311
Eric Christophere7b87e52014-10-26 23:40:33 +0000312StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
David Majnemerbc5976a2016-07-01 23:12:54 +0000313 if (isa<ClassTemplateSpecializationDecl>(RD)) {
314 SmallString<128> Name;
David Blaikie65813a32014-04-02 18:21:09 +0000315 llvm::raw_svector_ostream OS(Name);
David Blaikie9fdd09a2019-10-18 23:58:34 +0000316 PrintingPolicy PP = getPrintingPolicy();
317 PP.PrintCanonicalTypes = true;
318 RD->getNameForDiagnostic(OS, PP,
David Blaikie65813a32014-04-02 18:21:09 +0000319 /*Qualified*/ false);
David Majnemerbc5976a2016-07-01 23:12:54 +0000320
321 // Copy this name on the side and use its reference.
322 return internString(Name);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000323 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000324
David Majnemerbc5976a2016-07-01 23:12:54 +0000325 // quick optimization to avoid having to intern strings that are already
326 // stored reliably elsewhere
327 if (const IdentifierInfo *II = RD->getIdentifier())
328 return II->getName();
329
330 // The CodeView printer in LLVM wants to see the names of unnamed types: it is
331 // used to reconstruct the fully qualified type names.
332 if (CGM.getCodeGenOpts().EmitCodeView) {
333 if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
334 assert(RD->getDeclContext() == D->getDeclContext() &&
335 "Typedef should not be in another decl context!");
336 assert(D->getDeclName().getAsIdentifierInfo() &&
337 "Typedef was not named!");
338 return D->getDeclName().getAsIdentifierInfo()->getName();
339 }
340
341 if (CGM.getLangOpts().CPlusPlus) {
342 StringRef Name;
343
344 ASTContext &Context = CGM.getContext();
345 if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
346 // Anonymous types without a name for linkage purposes have their
347 // declarator mangled in if they have one.
348 Name = DD->getName();
349 else if (const TypedefNameDecl *TND =
350 Context.getTypedefNameForUnnamedTagDecl(RD))
351 // Anonymous types without a name for linkage purposes have their
352 // associate typedef mangled in if they have one.
353 Name = TND->getName();
354
355 if (!Name.empty()) {
356 SmallString<256> UnnamedType("<unnamed-type-");
357 UnnamedType += Name;
358 UnnamedType += '>';
359 return internString(UnnamedType);
360 }
361 }
362 }
363
364 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +0000365}
366
Scott Linder94834f12018-02-12 19:47:05 +0000367Optional<llvm::DIFile::ChecksumKind>
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000368CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
369 Checksum.clear();
370
Paul Robinson76178632018-05-25 22:35:59 +0000371 if (!CGM.getCodeGenOpts().EmitCodeView &&
372 CGM.getCodeGenOpts().DwarfVersion < 5)
Scott Linder94834f12018-02-12 19:47:05 +0000373 return None;
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000374
375 SourceManager &SM = CGM.getContext().getSourceManager();
376 bool Invalid;
Nico Weber04347d82019-04-04 21:06:41 +0000377 const llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid);
Paul Robinson76178632018-05-25 22:35:59 +0000378 if (Invalid)
Scott Linder94834f12018-02-12 19:47:05 +0000379 return None;
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000380
381 llvm::MD5 Hash;
382 llvm::MD5::MD5Result Result;
383
384 Hash.update(MemBuffer->getBuffer());
385 Hash.final(Result);
386
387 Hash.stringifyResult(Result, Checksum);
388 return llvm::DIFile::CSK_MD5;
389}
390
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000391Optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
392 FileID FID) {
Scott Lindera2fbcef2018-02-26 17:32:31 +0000393 if (!CGM.getCodeGenOpts().EmbedSource)
394 return None;
395
396 bool SourceInvalid = false;
397 StringRef Source = SM.getBufferData(FID, &SourceInvalid);
398
399 if (SourceInvalid)
400 return None;
401
402 return Source;
403}
404
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000405llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000406 if (!Loc.isValid())
407 // If Location is not valid then use main input file.
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000408 return TheCU->getFile();
Guy Benyei11169dd2012-12-18 14:30:41 +0000409
410 SourceManager &SM = CGM.getContext().getSourceManager();
411 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
412
Adrian Prantl212c1042018-12-06 18:44:50 +0000413 StringRef FileName = PLoc.getFilename();
414 if (PLoc.isInvalid() || FileName.empty())
Guy Benyei11169dd2012-12-18 14:30:41 +0000415 // If the location is not valid then use main input file.
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000416 return TheCU->getFile();
Guy Benyei11169dd2012-12-18 14:30:41 +0000417
418 // Cache the results.
Adrian Prantl212c1042018-12-06 18:44:50 +0000419 auto It = DIFileCache.find(FileName.data());
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000420 if (It != DIFileCache.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000421 // Verify that the information still exists.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000422 if (llvm::Metadata *V = It->second)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000423 return cast<llvm::DIFile>(V);
Guy Benyei11169dd2012-12-18 14:30:41 +0000424 }
425
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000426 SmallString<32> Checksum;
Alexandre Ganea047e65d2019-05-21 19:40:28 +0000427
428 // Compute the checksum if possible. If the location is affected by a #line
429 // directive that refers to a file, PLoc will have an invalid FileID, and we
430 // will correctly get no checksum.
Scott Linder94834f12018-02-12 19:47:05 +0000431 Optional<llvm::DIFile::ChecksumKind> CSKind =
Alexandre Ganea047e65d2019-05-21 19:40:28 +0000432 computeChecksum(PLoc.getFileID(), Checksum);
Scott Linder94834f12018-02-12 19:47:05 +0000433 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
434 if (CSKind)
435 CSInfo.emplace(*CSKind, Checksum);
Adrian Prantlaa5bad42018-12-11 16:58:43 +0000436 return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));
437}
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000438
Adrian Prantlaa5bad42018-12-11 16:58:43 +0000439llvm::DIFile *
440CGDebugInfo::createFile(StringRef FileName,
441 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
442 Optional<StringRef> Source) {
Adrian Prantl212c1042018-12-06 18:44:50 +0000443 StringRef Dir;
444 StringRef File;
445 std::string RemappedFile = remapDIPath(FileName);
446 std::string CurDir = remapDIPath(getCurrentDirname());
447 SmallString<128> DirBuf;
448 SmallString<128> FileBuf;
449 if (llvm::sys::path::is_absolute(RemappedFile)) {
450 // Strip the common prefix (if it is more than just "/") from current
451 // directory and FileName for a more space-efficient encoding.
452 auto FileIt = llvm::sys::path::begin(RemappedFile);
453 auto FileE = llvm::sys::path::end(RemappedFile);
454 auto CurDirIt = llvm::sys::path::begin(CurDir);
455 auto CurDirE = llvm::sys::path::end(CurDir);
456 for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
457 llvm::sys::path::append(DirBuf, *CurDirIt);
458 if (std::distance(llvm::sys::path::begin(CurDir), CurDirIt) == 1) {
Adrian Prantl0feb7b72019-02-05 21:21:01 +0000459 // Don't strip the common prefix if it is only the root "/"
460 // since that would make LLVM diagnostic locations confusing.
Adrian Prantl212c1042018-12-06 18:44:50 +0000461 Dir = {};
462 File = RemappedFile;
463 } else {
464 for (; FileIt != FileE; ++FileIt)
465 llvm::sys::path::append(FileBuf, *FileIt);
466 Dir = DirBuf;
467 File = FileBuf;
468 }
469 } else {
470 Dir = CurDir;
471 File = RemappedFile;
472 }
Adrian Prantlaa5bad42018-12-11 16:58:43 +0000473 llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
Adrian Prantl212c1042018-12-06 18:44:50 +0000474 DIFileCache[FileName.data()].reset(F);
Guy Benyei11169dd2012-12-18 14:30:41 +0000475 return F;
476}
477
Saleem Abdulrasool436256a2015-10-12 20:21:08 +0000478std::string CGDebugInfo::remapDIPath(StringRef Path) const {
479 for (const auto &Entry : DebugPrefixMap)
480 if (Path.startswith(Entry.first))
481 return (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
482 return Path.str();
Guy Benyei11169dd2012-12-18 14:30:41 +0000483}
484
Guy Benyei11169dd2012-12-18 14:30:41 +0000485unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
486 if (Loc.isInvalid() && CurLoc.isInvalid())
487 return 0;
488 SourceManager &SM = CGM.getContext().getSourceManager();
489 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
Eric Christophere7b87e52014-10-26 23:40:33 +0000490 return PLoc.isValid() ? PLoc.getLine() : 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000491}
492
Adrian Prantlc7822422013-03-12 20:43:25 +0000493unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000494 // We may not want column information at all.
Adrian Prantlc7822422013-03-12 20:43:25 +0000495 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000496 return 0;
497
498 // If the location is invalid then use the current column.
499 if (Loc.isInvalid() && CurLoc.isInvalid())
500 return 0;
501 SourceManager &SM = CGM.getContext().getSourceManager();
502 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
Eric Christophere7b87e52014-10-26 23:40:33 +0000503 return PLoc.isValid() ? PLoc.getColumn() : 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000504}
505
506StringRef CGDebugInfo::getCurrentDirname() {
507 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
508 return CGM.getCodeGenOpts().DebugCompilationDir;
509
510 if (!CWDName.empty())
511 return CWDName;
512 SmallString<256> CWD;
513 llvm::sys::fs::current_path(CWD);
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000514 return CWDName = internString(CWD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000515}
516
Guy Benyei11169dd2012-12-18 14:30:41 +0000517void CGDebugInfo::CreateCompileUnit() {
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000518 SmallString<32> Checksum;
Scott Linder94834f12018-02-12 19:47:05 +0000519 Optional<llvm::DIFile::ChecksumKind> CSKind;
520 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000521
David Blaikieaabde052014-05-14 00:29:00 +0000522 // Should we be asking the SourceManager for the main file name, instead of
523 // accepting it as an argument? This just causes the main file name to
524 // mismatch with source locations and create extra lexical scopes or
525 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
526 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
527 // because that's what the SourceManager says)
528
Guy Benyei11169dd2012-12-18 14:30:41 +0000529 // Get absolute path name.
530 SourceManager &SM = CGM.getContext().getSourceManager();
531 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
532 if (MainFileName.empty())
David Blaikieaabde052014-05-14 00:29:00 +0000533 MainFileName = "<stdin>";
Guy Benyei11169dd2012-12-18 14:30:41 +0000534
535 // The main file name provided via the "-main-file-name" option contains just
536 // the file name itself with no path information. This file name may have had
537 // a relative path, so we look into the actual file entry for the main
538 // file to determine the real absolute path for the file.
539 std::string MainFileDir;
540 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Adrian Prantl122e7af2019-10-21 16:44:37 +0000541 MainFileDir = MainFile->getDir()->getName();
542 if (!llvm::sys::path::is_absolute(MainFileName)) {
Eric Christopher0a1301f2014-02-26 02:49:36 +0000543 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
544 llvm::sys::path::append(MainFileDirSS, MainFileName);
Adrian Prantl122e7af2019-10-21 16:44:37 +0000545 MainFileName = llvm::sys::path::remove_leading_dotslash(MainFileDirSS);
Yaron Keren9fb7e902013-10-21 20:07:37 +0000546 }
Taewook Oh0fb5b782017-08-16 19:36:24 +0000547 // If the main file name provided is identical to the input file name, and
548 // if the input file is a preprocessed source, use the module name for
549 // debug info. The module name comes from the name specified in the first
550 // linemarker if the input is a preprocessed source.
551 if (MainFile->getName() == MainFileName &&
552 FrontendOptions::getInputKindForExtension(
553 MainFile->getName().rsplit('.').second)
554 .isPreprocessed())
555 MainFileName = CGM.getModule().getName().str();
556
Amjad Aboude2aab8c2016-12-25 10:12:27 +0000557 CSKind = computeChecksum(SM.getMainFileID(), Checksum);
Guy Benyei11169dd2012-12-18 14:30:41 +0000558 }
559
Ed Masteda706022014-05-07 12:49:30 +0000560 llvm::dwarf::SourceLanguage LangTag;
Guy Benyei11169dd2012-12-18 14:30:41 +0000561 const LangOptions &LO = CGM.getLangOpts();
562 if (LO.CPlusPlus) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000563 if (LO.ObjC)
Guy Benyei11169dd2012-12-18 14:30:41 +0000564 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
Adrian Prantl350de4f2019-09-24 00:38:49 +0000565 else if (LO.CPlusPlus14)
566 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
567 else if (LO.CPlusPlus11)
568 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
Guy Benyei11169dd2012-12-18 14:30:41 +0000569 else
570 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000571 } else if (LO.ObjC) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000572 LangTag = llvm::dwarf::DW_LANG_ObjC;
Pirama Arumuga Nainara7484c92016-06-21 21:35:11 +0000573 } else if (LO.RenderScript) {
574 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
Guy Benyei11169dd2012-12-18 14:30:41 +0000575 } else if (LO.C99) {
576 LangTag = llvm::dwarf::DW_LANG_C99;
577 } else {
578 LangTag = llvm::dwarf::DW_LANG_C89;
579 }
580
581 std::string Producer = getClangFullVersion();
582
583 // Figure out which version of the ObjC runtime we have.
584 unsigned RuntimeVers = 0;
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000585 if (LO.ObjC)
Guy Benyei11169dd2012-12-18 14:30:41 +0000586 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
587
Adrian Prantl826824e2016-04-08 22:43:06 +0000588 llvm::DICompileUnit::DebugEmissionKind EmissionKind;
589 switch (DebugKind) {
590 case codegenoptions::NoDebugInfo:
591 case codegenoptions::LocTrackingOnly:
592 EmissionKind = llvm::DICompileUnit::NoDebug;
593 break;
594 case codegenoptions::DebugLineTablesOnly:
595 EmissionKind = llvm::DICompileUnit::LineTablesOnly;
596 break;
Alexey Bataev80e1b5e2018-08-31 13:56:14 +0000597 case codegenoptions::DebugDirectivesOnly:
598 EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
599 break;
Adrian Prantl826824e2016-04-08 22:43:06 +0000600 case codegenoptions::LimitedDebugInfo:
601 case codegenoptions::FullDebugInfo:
602 EmissionKind = llvm::DICompileUnit::FullDebug;
603 break;
604 }
605
Adrian Prantl046d1002018-12-13 17:53:29 +0000606 uint64_t DwoId = 0;
607 auto &CGOpts = CGM.getCodeGenOpts();
608 // The DIFile used by the CU is distinct from the main source
609 // file. Its directory part specifies what becomes the
610 // DW_AT_comp_dir (the compilation directory), even if the source
611 // file was specified with an absolute path.
Scott Linder94834f12018-02-12 19:47:05 +0000612 if (CSKind)
613 CSInfo.emplace(*CSKind, Checksum);
Adrian Prantl046d1002018-12-13 17:53:29 +0000614 llvm::DIFile *CUFile = DBuilder.createFile(
615 remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
616 getSource(SM, SM.getMainFileID()));
Scott Linder94834f12018-02-12 19:47:05 +0000617
Guy Benyei11169dd2012-12-18 14:30:41 +0000618 // Create new compile unit.
Eric Christophere4200a22014-02-27 01:25:08 +0000619 TheCU = DBuilder.createCompileUnit(
Adrian Prantl046d1002018-12-13 17:53:29 +0000620 LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000621 LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
Aaron Puchert45611612019-06-26 21:39:19 +0000622 CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
623 DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
David Blaikie9982bb82018-08-16 23:56:32 +0000624 CGM.getTarget().getTriple().isNVPTX()
625 ? llvm::DICompileUnit::DebugNameTableKind::None
David Blaikie65864522018-08-20 20:14:08 +0000626 : static_cast<llvm::DICompileUnit::DebugNameTableKind>(
David Blaikie27692de2018-11-13 20:08:13 +0000627 CGOpts.DebugNameTable),
628 CGOpts.DebugRangesBaseAddress);
Guy Benyei11169dd2012-12-18 14:30:41 +0000629}
630
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000631llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
Ed Masteda706022014-05-07 12:49:30 +0000632 llvm::dwarf::TypeKind Encoding;
Guy Benyei11169dd2012-12-18 14:30:41 +0000633 StringRef BTName;
634 switch (BT->getKind()) {
635#define BUILTIN_TYPE(Id, SingletonId)
Eric Christophere7b87e52014-10-26 23:40:33 +0000636#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
Guy Benyei11169dd2012-12-18 14:30:41 +0000637#include "clang/AST/BuiltinTypes.def"
638 case BuiltinType::Dependent:
639 llvm_unreachable("Unexpected builtin type");
640 case BuiltinType::NullPtr:
Peter Collingbourne5c5e6172013-06-27 22:51:01 +0000641 return DBuilder.createNullPtrType();
Guy Benyei11169dd2012-12-18 14:30:41 +0000642 case BuiltinType::Void:
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000643 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000644 case BuiltinType::ObjCClass:
David Blaikief427b002014-05-06 03:42:01 +0000645 if (!ClassTy)
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000646 ClassTy =
647 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
648 "objc_class", TheCU, TheCU->getFile(), 0);
Guy Benyei11169dd2012-12-18 14:30:41 +0000649 return ClassTy;
650 case BuiltinType::ObjCId: {
651 // typedef struct objc_class *Class;
652 // typedef struct objc_object {
653 // Class isa;
654 // } *id;
655
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000656 if (ObjTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000657 return ObjTy;
658
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000659 if (!ClassTy)
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000660 ClassTy =
661 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
662 "objc_class", TheCU, TheCU->getFile(), 0);
Guy Benyei11169dd2012-12-18 14:30:41 +0000663
664 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000665
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000666 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
Guy Benyei11169dd2012-12-18 14:30:41 +0000667
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000668 ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
669 0, 0, llvm::DINode::FlagZero, nullptr,
670 llvm::DINodeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000671
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +0000672 DBuilder.replaceArrays(
Leny Kholodovdf050fd2016-09-06 17:06:14 +0000673 ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000674 ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
Leny Kholodovdf050fd2016-09-06 17:06:14 +0000675 llvm::DINode::FlagZero, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000676 return ObjTy;
677 }
678 case BuiltinType::ObjCSel: {
David Blaikief427b002014-05-06 03:42:01 +0000679 if (!SelTy)
680 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
681 "objc_selector", TheCU,
Adrian Prantlc2a44ec2018-12-11 16:58:46 +0000682 TheCU->getFile(), 0);
Guy Benyei11169dd2012-12-18 14:30:41 +0000683 return SelTy;
684 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000685
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000686#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
687 case BuiltinType::Id: \
688 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
Alexey Bader954ba212016-04-08 13:40:33 +0000689 SingletonId);
Alexey Baderb62f1442016-04-13 08:33:41 +0000690#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei61054192013-02-07 10:55:47 +0000691 case BuiltinType::OCLSampler:
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000692 return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000693 case BuiltinType::OCLEvent:
Eric Christophere7b87e52014-10-26 23:40:33 +0000694 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
Alexey Bader9c8453f2015-09-15 11:18:52 +0000695 case BuiltinType::OCLClkEvent:
696 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
697 case BuiltinType::OCLQueue:
698 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
Alexey Bader9c8453f2015-09-15 11:18:52 +0000699 case BuiltinType::OCLReserveID:
700 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
Andrew Savonichev3fee3512018-11-08 11:25:41 +0000701#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
702 case BuiltinType::Id: \
703 return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
704#include "clang/Basic/OpenCLExtensionTypes.def"
Richard Sandifordeb485fb2019-08-09 08:52:54 +0000705 // TODO: real support for SVE types requires more infrastructure
706 // to be added first. The types have a variable length and are
707 // represented in debug info as types whose length depends on a
708 // target-specific pseudo register.
709#define SVE_TYPE(Name, Id, SingletonId) \
710 case BuiltinType::Id:
711#include "clang/Basic/AArch64SVEACLETypes.def"
712 {
713 unsigned DiagID = CGM.getDiags().getCustomDiagID(
714 DiagnosticsEngine::Error,
715 "cannot yet generate debug info for SVE type '%0'");
716 auto Name = BT->getName(CGM.getContext().getPrintingPolicy());
717 CGM.getDiags().Report(DiagID) << Name;
718 // Return something safe.
719 return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
720 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000721
Guy Benyei11169dd2012-12-18 14:30:41 +0000722 case BuiltinType::UChar:
Eric Christophere7b87e52014-10-26 23:40:33 +0000723 case BuiltinType::Char_U:
724 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
725 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000726 case BuiltinType::Char_S:
Eric Christophere7b87e52014-10-26 23:40:33 +0000727 case BuiltinType::SChar:
728 Encoding = llvm::dwarf::DW_ATE_signed_char;
729 break;
Richard Smith3a8244d2018-05-01 05:02:45 +0000730 case BuiltinType::Char8:
Guy Benyei11169dd2012-12-18 14:30:41 +0000731 case BuiltinType::Char16:
Eric Christophere7b87e52014-10-26 23:40:33 +0000732 case BuiltinType::Char32:
733 Encoding = llvm::dwarf::DW_ATE_UTF;
734 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000735 case BuiltinType::UShort:
736 case BuiltinType::UInt:
737 case BuiltinType::UInt128:
738 case BuiltinType::ULong:
739 case BuiltinType::WChar_U:
Eric Christophere7b87e52014-10-26 23:40:33 +0000740 case BuiltinType::ULongLong:
741 Encoding = llvm::dwarf::DW_ATE_unsigned;
742 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000743 case BuiltinType::Short:
744 case BuiltinType::Int:
745 case BuiltinType::Int128:
746 case BuiltinType::Long:
747 case BuiltinType::WChar_S:
Eric Christophere7b87e52014-10-26 23:40:33 +0000748 case BuiltinType::LongLong:
749 Encoding = llvm::dwarf::DW_ATE_signed;
750 break;
751 case BuiltinType::Bool:
752 Encoding = llvm::dwarf::DW_ATE_boolean;
753 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000754 case BuiltinType::Half:
755 case BuiltinType::Float:
756 case BuiltinType::LongDouble:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +0000757 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000758 case BuiltinType::Float128:
Eric Christophere7b87e52014-10-26 23:40:33 +0000759 case BuiltinType::Double:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000760 // FIXME: For targets where long double and __float128 have the same size,
761 // they are currently indistinguishable in the debugger without some
762 // special treatment. However, there is currently no consensus on encoding
763 // and this should be updated once a DWARF encoding exists for distinct
764 // floating point types of the same size.
Eric Christophere7b87e52014-10-26 23:40:33 +0000765 Encoding = llvm::dwarf::DW_ATE_float;
766 break;
Leonard Chanf921d852018-06-04 16:07:52 +0000767 case BuiltinType::ShortAccum:
768 case BuiltinType::Accum:
769 case BuiltinType::LongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +0000770 case BuiltinType::ShortFract:
771 case BuiltinType::Fract:
772 case BuiltinType::LongFract:
773 case BuiltinType::SatShortFract:
774 case BuiltinType::SatFract:
775 case BuiltinType::SatLongFract:
776 case BuiltinType::SatShortAccum:
777 case BuiltinType::SatAccum:
778 case BuiltinType::SatLongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +0000779 Encoding = llvm::dwarf::DW_ATE_signed_fixed;
780 break;
781 case BuiltinType::UShortAccum:
782 case BuiltinType::UAccum:
783 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +0000784 case BuiltinType::UShortFract:
785 case BuiltinType::UFract:
786 case BuiltinType::ULongFract:
787 case BuiltinType::SatUShortAccum:
788 case BuiltinType::SatUAccum:
789 case BuiltinType::SatULongAccum:
790 case BuiltinType::SatUShortFract:
791 case BuiltinType::SatUFract:
792 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +0000793 Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
794 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000795 }
796
797 switch (BT->getKind()) {
Eric Christophere7b87e52014-10-26 23:40:33 +0000798 case BuiltinType::Long:
799 BTName = "long int";
800 break;
801 case BuiltinType::LongLong:
802 BTName = "long long int";
803 break;
804 case BuiltinType::ULong:
805 BTName = "long unsigned int";
806 break;
807 case BuiltinType::ULongLong:
808 BTName = "long long unsigned int";
809 break;
Guy Benyei11169dd2012-12-18 14:30:41 +0000810 default:
811 BTName = BT->getName(CGM.getLangOpts());
812 break;
813 }
Victor Leschuka7ece032016-10-20 00:13:19 +0000814 // Bit size and offset of the type.
Guy Benyei11169dd2012-12-18 14:30:41 +0000815 uint64_t Size = CGM.getContext().getTypeSize(BT);
Victor Leschuka7ece032016-10-20 00:13:19 +0000816 return DBuilder.createBasicType(BTName, Size, Encoding);
Guy Benyei11169dd2012-12-18 14:30:41 +0000817}
818
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000819llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
Victor Leschuka7ece032016-10-20 00:13:19 +0000820 // Bit size and offset of the type.
Ed Masteda706022014-05-07 12:49:30 +0000821 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
Guy Benyei11169dd2012-12-18 14:30:41 +0000822 if (Ty->isComplexIntegerType())
823 Encoding = llvm::dwarf::DW_ATE_lo_user;
824
825 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +0000826 return DBuilder.createBasicType("complex", Size, Encoding);
Guy Benyei11169dd2012-12-18 14:30:41 +0000827}
828
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000829llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
830 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000831 QualifierCollector Qc;
832 const Type *T = Qc.strip(Ty);
833
834 // Ignore these qualifiers for now.
835 Qc.removeObjCGCAttr();
836 Qc.removeAddressSpace();
837 Qc.removeObjCLifetime();
838
839 // We will create one Derived type for one qualifier and recurse to handle any
840 // additional ones.
Ed Masteda706022014-05-07 12:49:30 +0000841 llvm::dwarf::Tag Tag;
Guy Benyei11169dd2012-12-18 14:30:41 +0000842 if (Qc.hasConst()) {
843 Tag = llvm::dwarf::DW_TAG_const_type;
844 Qc.removeConst();
845 } else if (Qc.hasVolatile()) {
846 Tag = llvm::dwarf::DW_TAG_volatile_type;
847 Qc.removeVolatile();
848 } else if (Qc.hasRestrict()) {
849 Tag = llvm::dwarf::DW_TAG_restrict_type;
850 Qc.removeRestrict();
851 } else {
852 assert(Qc.empty() && "Unknown type qualifier for debug info");
853 return getOrCreateType(QualType(T, 0), Unit);
854 }
855
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000856 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000857
858 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
859 // CVR derived types.
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000860 return DBuilder.createQualifiedType(Tag, FromTy);
Guy Benyei11169dd2012-12-18 14:30:41 +0000861}
862
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000863llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
864 llvm::DIFile *Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000865
866 // The frontend treats 'id' as a typedef to an ObjCObjectType,
867 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
868 // debug info, we want to emit 'id' in both cases.
869 if (Ty->isObjCQualifiedIdType())
Eric Christophere7b87e52014-10-26 23:40:33 +0000870 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000871
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +0000872 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
873 Ty->getPointeeType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000874}
875
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000876llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
877 llvm::DIFile *Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000878 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000879 Ty->getPointeeType(), Unit);
880}
881
Adrian Prantlc6f91a22015-06-15 23:18:16 +0000882/// \return whether a C++ mangling exists for the type defined by TD.
883static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
884 switch (TheCU->getSourceLanguage()) {
885 case llvm::dwarf::DW_LANG_C_plus_plus:
Adrian Prantl350de4f2019-09-24 00:38:49 +0000886 case llvm::dwarf::DW_LANG_C_plus_plus_11:
887 case llvm::dwarf::DW_LANG_C_plus_plus_14:
Adrian Prantlc6f91a22015-06-15 23:18:16 +0000888 return true;
889 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
890 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
891 default:
892 return false;
893 }
894}
895
Reid Kleckner59320fc2018-08-17 20:59:52 +0000896// Determines if the debug info for this tag declaration needs a type
897// identifier. The purpose of the unique identifier is to deduplicate type
898// information for identical types across TUs. Because of the C++ one definition
899// rule (ODR), it is valid to assume that the type is defined the same way in
900// every TU and its debug info is equivalent.
901//
902// C does not have the ODR, and it is common for codebases to contain multiple
903// different definitions of a struct with the same name in different TUs.
904// Therefore, if the type doesn't have a C++ mangling, don't give it an
905// identifer. Type information in C is smaller and simpler than C++ type
906// information, so the increase in debug info size is negligible.
907//
908// If the type is not externally visible, it should be unique to the current TU,
909// and should not need an identifier to participate in type deduplication.
910// However, when emitting CodeView, the format internally uses these
911// unique type name identifers for references between debug info. For example,
912// the method of a class in an anonymous namespace uses the identifer to refer
913// to its parent class. The Microsoft C++ ABI attempts to provide unique names
914// for such types, so when emitting CodeView, always use identifiers for C++
915// types. This may create problems when attempting to emit CodeView when the MS
916// C++ ABI is not in use.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000917static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
Brock Wyma8557ec52018-05-22 12:41:19 +0000918 llvm::DICompileUnit *TheCU) {
919 // We only add a type identifier for types with C++ name mangling.
920 if (!hasCXXMangling(TD, TheCU))
921 return false;
922
Brock Wyma8557ec52018-05-22 12:41:19 +0000923 // Externally visible types with C++ mangling need a type identifier.
924 if (TD->isExternallyVisible())
925 return true;
926
Reid Kleckner59320fc2018-08-17 20:59:52 +0000927 // CodeView types with C++ mangling need a type identifier.
928 if (CGM.getCodeGenOpts().EmitCodeView)
929 return true;
930
Brock Wyma8557ec52018-05-22 12:41:19 +0000931 return false;
932}
933
Reid Kleckner59320fc2018-08-17 20:59:52 +0000934// Returns a unique type identifier string if one exists, or an empty string.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000935static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
Brock Wyma8557ec52018-05-22 12:41:19 +0000936 llvm::DICompileUnit *TheCU) {
937 SmallString<256> Identifier;
Manman Rene0064d82013-08-29 23:19:58 +0000938 const TagDecl *TD = Ty->getDecl();
Adrian Prantlc6f91a22015-06-15 23:18:16 +0000939
Brock Wyma8557ec52018-05-22 12:41:19 +0000940 if (!needsTypeIdentifier(TD, CGM, TheCU))
941 return Identifier;
David Blaikief0d66552019-04-25 20:05:47 +0000942 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
943 if (RD->getDefinition())
944 if (RD->isDynamicClass() &&
945 CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
946 return Identifier;
Adrian Prantlc6f91a22015-06-15 23:18:16 +0000947
Manman Rene0064d82013-08-29 23:19:58 +0000948 // TODO: This is using the RTTI name. Is there a better way to get
949 // a unique string for a type?
Brock Wyma8557ec52018-05-22 12:41:19 +0000950 llvm::raw_svector_ostream Out(Identifier);
Manman Rene0064d82013-08-29 23:19:58 +0000951 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
Brock Wyma8557ec52018-05-22 12:41:19 +0000952 return Identifier;
Manman Rene0064d82013-08-29 23:19:58 +0000953}
954
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000955/// \return the appropriate DWARF tag for a composite type.
Adrian Prantl5f66bae2015-02-11 17:45:15 +0000956static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +0000957 llvm::dwarf::Tag Tag;
Adrian Prantl5f66bae2015-02-11 17:45:15 +0000958 if (RD->isStruct() || RD->isInterface())
959 Tag = llvm::dwarf::DW_TAG_structure_type;
960 else if (RD->isUnion())
961 Tag = llvm::dwarf::DW_TAG_union_type;
962 else {
963 // FIXME: This could be a struct type giving a default visibility different
964 // than C++ class type, but needs llvm metadata changes first.
965 assert(RD->isClass());
966 Tag = llvm::dwarf::DW_TAG_class_type;
967 }
968 return Tag;
969}
970
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000971llvm::DICompositeType *
Manman Ren1b457022013-08-28 21:20:28 +0000972CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000973 llvm::DIScope *Ctx) {
Manman Ren1b457022013-08-28 21:20:28 +0000974 const RecordDecl *RD = Ty->getDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000975 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
976 return cast<llvm::DICompositeType>(T);
977 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 unsigned Line = getLineNumber(RD->getLocation());
979 StringRef RDName = getClassName(RD);
980
Peter Collingbourned251b0a2015-03-01 22:07:04 +0000981 uint64_t Size = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +0000982 uint32_t Align = 0;
Peter Collingbourned251b0a2015-03-01 22:07:04 +0000983
Guy Benyei11169dd2012-12-18 14:30:41 +0000984 // Create the type.
Brock Wyma8557ec52018-05-22 12:41:19 +0000985 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000986 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
Peter Collingbourned251b0a2015-03-01 22:07:04 +0000987 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
Brock Wyma8557ec52018-05-22 12:41:19 +0000988 llvm::DINode::FlagFwdDecl, Identifier);
Paul Robinson1787f812017-09-28 18:37:02 +0000989 if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
990 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
991 DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
992 CollectCXXTemplateParams(TSpecial, DefUnit));
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +0000993 ReplaceMap.emplace_back(
994 std::piecewise_construct, std::make_tuple(Ty),
995 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
David Blaikief427b002014-05-06 03:42:01 +0000996 return RetTy;
Guy Benyei11169dd2012-12-18 14:30:41 +0000997}
998
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +0000999llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00001000 const Type *Ty,
1001 QualType PointeeTy,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001002 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001003 // Bit size, align and offset of the type.
1004 // Size is always the size of a pointer. We can't use getTypeSize here
1005 // because that does not return the correct value for references.
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001006 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
1007 uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
Victor Leschuka7ece032016-10-20 00:13:19 +00001008 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001009 Optional<unsigned> DWARFAddressSpace =
1010 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
Guy Benyei11169dd2012-12-18 14:30:41 +00001011
Keno Fischer87842f32015-11-16 09:04:13 +00001012 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1013 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
1014 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001015 Size, Align, DWARFAddressSpace);
Keno Fischer87842f32015-11-16 09:04:13 +00001016 else
1017 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001018 Align, DWARFAddressSpace);
Guy Benyei11169dd2012-12-18 14:30:41 +00001019}
1020
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001021llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1022 llvm::DIType *&Cache) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +00001023 if (Cache)
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001024 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +00001025 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
Adrian Prantlc2a44ec2018-12-11 16:58:46 +00001026 TheCU, TheCU->getFile(), 0);
David Blaikiefefc7f72013-05-21 17:58:54 +00001027 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1028 Cache = DBuilder.createPointerType(Cache, Size);
1029 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001030}
1031
Scott Linder58df0e42018-08-08 15:56:12 +00001032uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1033 const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1034 unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001035 QualType FType;
Guy Benyei11169dd2012-12-18 14:30:41 +00001036
Scott Linder58df0e42018-08-08 15:56:12 +00001037 // Advanced by calls to CreateMemberType in increments of FType, then
1038 // returned as the overall size of the default elements.
1039 uint64_t FieldOffset = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001040
Scott Linder58df0e42018-08-08 15:56:12 +00001041 // Blocks in OpenCL have unique constraints which make the standard fields
1042 // redundant while requiring size and align fields for enqueue_kernel. See
1043 // initializeForBlockHeader in CGBlocks.cpp
Scott Linder2b5cf042018-07-30 20:31:11 +00001044 if (CGM.getLangOpts().OpenCL) {
1045 FType = CGM.getContext().IntTy;
1046 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1047 EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1048 } else {
1049 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1050 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1051 FType = CGM.getContext().IntTy;
1052 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1053 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1054 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1055 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1056 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Scott Linder58df0e42018-08-08 15:56:12 +00001057 uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1058 uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
Scott Linder2b5cf042018-07-30 20:31:11 +00001059 EltTys.push_back(DBuilder.createMemberType(
Scott Linder58df0e42018-08-08 15:56:12 +00001060 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1061 FieldOffset, llvm::DINode::FlagZero, DescTy));
Scott Lindera7c45682018-07-30 22:52:07 +00001062 FieldOffset += FieldSize;
Scott Linder2b5cf042018-07-30 20:31:11 +00001063 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001064
Scott Linder58df0e42018-08-08 15:56:12 +00001065 return FieldOffset;
1066}
1067
1068llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1069 llvm::DIFile *Unit) {
1070 SmallVector<llvm::Metadata *, 8> EltTys;
1071 QualType FType;
1072 uint64_t FieldOffset;
1073 llvm::DINodeArray Elements;
1074
1075 FieldOffset = 0;
1076 FType = CGM.getContext().UnsignedLongTy;
1077 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1078 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1079
1080 Elements = DBuilder.getOrCreateArray(EltTys);
1081 EltTys.clear();
1082
1083 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1084
1085 auto *EltTy =
1086 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1087 FieldOffset, 0, Flags, nullptr, Elements);
1088
1089 // Bit size, align and offset of the type.
1090 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1091
1092 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1093
1094 FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1095 0, EltTys);
1096
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 Elements = DBuilder.getOrCreateArray(EltTys);
1098
Adrian Prantl3d2c0512015-07-07 00:49:35 +00001099 // The __block_literal_generic structs are marked with a special
1100 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1101 // the debugger needs to know about. To allow type uniquing, emit
1102 // them without a name or a location.
Scott Linder58df0e42018-08-08 15:56:12 +00001103 EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001104 Flags, nullptr, Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001105
Adrian Prantl3d2c0512015-07-07 00:49:35 +00001106 return DBuilder.createPointerType(EltTy, Size);
Guy Benyei11169dd2012-12-18 14:30:41 +00001107}
1108
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001109llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1110 llvm::DIFile *Unit) {
David Blaikief1b382e2014-04-06 17:14:06 +00001111 assert(Ty->isTypeAlias());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001112 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
David Blaikief1b382e2014-04-06 17:14:06 +00001113
David Blaikie8472fa62019-06-08 00:01:21 +00001114 auto *AliasDecl =
1115 cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
1116 ->getTemplatedDecl();
1117
1118 if (AliasDecl->hasAttr<NoDebugAttr>())
1119 return Src;
1120
David Blaikief1b382e2014-04-06 17:14:06 +00001121 SmallString<128> NS;
1122 llvm::raw_svector_ostream OS(NS);
Serge Pavlov03e672c2017-11-28 16:14:14 +00001123 Ty->getTemplateName().print(OS, getPrintingPolicy(), /*qualified*/ false);
1124 printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy());
David Blaikief1b382e2014-04-06 17:14:06 +00001125
David Blaikief1b382e2014-04-06 17:14:06 +00001126 SourceLocation Loc = AliasDecl->getLocation();
Adrian Prantlb67dbce2015-09-11 18:45:02 +00001127 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1128 getLineNumber(Loc),
Sam McCalld27a16e2019-11-18 15:53:22 +01001129 getDeclContextDescriptor(AliasDecl));
David Blaikief1b382e2014-04-06 17:14:06 +00001130}
1131
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001132llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1133 llvm::DIFile *Unit) {
David Blaikie8472fa62019-06-08 00:01:21 +00001134 llvm::DIType *Underlying =
1135 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1136
1137 if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1138 return Underlying;
1139
Guy Benyei11169dd2012-12-18 14:30:41 +00001140 // We don't set size information, but do specify where the typedef was
1141 // declared.
Amjad Abouddc4531e2016-04-30 01:44:38 +00001142 SourceLocation Loc = Ty->getDecl()->getLocation();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001143
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00001144 // Typedefs are derived from some other type.
Sam McCalld27a16e2019-11-18 15:53:22 +01001145 return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1146 getOrCreateFile(Loc), getLineNumber(Loc),
1147 getDeclContextDescriptor(Ty->getDecl()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001148}
1149
Reid Klecknerf00f8032016-06-08 20:41:54 +00001150static unsigned getDwarfCC(CallingConv CC) {
1151 switch (CC) {
1152 case CC_C:
1153 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1154 return 0;
1155
1156 case CC_X86StdCall:
1157 return llvm::dwarf::DW_CC_BORLAND_stdcall;
1158 case CC_X86FastCall:
1159 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1160 case CC_X86ThisCall:
1161 return llvm::dwarf::DW_CC_BORLAND_thiscall;
1162 case CC_X86VectorCall:
1163 return llvm::dwarf::DW_CC_LLVM_vectorcall;
1164 case CC_X86Pascal:
1165 return llvm::dwarf::DW_CC_BORLAND_pascal;
Martin Storsjo022e7822017-07-17 20:49:45 +00001166 case CC_Win64:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001167 return llvm::dwarf::DW_CC_LLVM_Win64;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001168 case CC_X86_64SysV:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001169 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001170 case CC_AAPCS:
Sander de Smalen44a22532018-11-26 16:38:37 +00001171 case CC_AArch64VectorCall:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001172 return llvm::dwarf::DW_CC_LLVM_AAPCS;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001173 case CC_AAPCS_VFP:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001174 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001175 case CC_IntelOclBicc:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001176 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001177 case CC_SpirFunction:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001178 return llvm::dwarf::DW_CC_LLVM_SpirFunction;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00001179 case CC_OpenCLKernel:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001180 return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001181 case CC_Swift:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001182 return llvm::dwarf::DW_CC_LLVM_Swift;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001183 case CC_PreserveMost:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001184 return llvm::dwarf::DW_CC_LLVM_PreserveMost;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001185 case CC_PreserveAll:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001186 return llvm::dwarf::DW_CC_LLVM_PreserveAll;
Erich Keane757d3172016-11-02 18:29:35 +00001187 case CC_X86RegCall:
Jonas Devliegheref0702682018-03-22 13:53:30 +00001188 return llvm::dwarf::DW_CC_LLVM_X86RegCall;
Reid Klecknerf00f8032016-06-08 20:41:54 +00001189 }
1190 return 0;
1191}
1192
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001193llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1194 llvm::DIFile *Unit) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001195 SmallVector<llvm::Metadata *, 16> EltTys;
Guy Benyei11169dd2012-12-18 14:30:41 +00001196
1197 // Add the result type at least.
Alp Toker314cc812014-01-25 16:55:45 +00001198 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001199
1200 // Set up remainder of arguments if there is a prototype.
Adrian Prantl800faef2014-02-25 23:42:18 +00001201 // otherwise emit it as a variadic function.
Guy Benyei11169dd2012-12-18 14:30:41 +00001202 if (isa<FunctionNoProtoType>(Ty))
1203 EltTys.push_back(DBuilder.createUnspecifiedParameter());
David Majnemer58ed0f32016-07-17 00:39:12 +00001204 else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
1205 for (const QualType &ParamType : FPT->param_types())
1206 EltTys.push_back(getOrCreateType(ParamType, Unit));
Adrian Prantld45ba252014-02-25 19:38:11 +00001207 if (FPT->isVariadic())
1208 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +00001209 }
1210
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001211 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
Leny Kholodov80c047d2016-09-06 10:48:04 +00001212 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
Reid Klecknerf00f8032016-06-08 20:41:54 +00001213 getDwarfCC(Ty->getCallConv()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001214}
1215
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001216/// Convert an AccessSpecifier into the corresponding DINode flag.
Adrian Prantl21361fb2014-08-29 22:44:27 +00001217/// As an optimization, return 0 if the access specifier equals the
1218/// default for the containing type.
Leny Kholodovdf050fd2016-09-06 17:06:14 +00001219static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1220 const RecordDecl *RD) {
Adrian Prantl21361fb2014-08-29 22:44:27 +00001221 AccessSpecifier Default = clang::AS_none;
1222 if (RD && RD->isClass())
1223 Default = clang::AS_private;
1224 else if (RD && (RD->isStruct() || RD->isUnion()))
1225 Default = clang::AS_public;
1226
1227 if (Access == Default)
Leny Kholodov80c047d2016-09-06 10:48:04 +00001228 return llvm::DINode::FlagZero;
Adrian Prantl21361fb2014-08-29 22:44:27 +00001229
Eric Christophere7b87e52014-10-26 23:40:33 +00001230 switch (Access) {
1231 case clang::AS_private:
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001232 return llvm::DINode::FlagPrivate;
Eric Christophere7b87e52014-10-26 23:40:33 +00001233 case clang::AS_protected:
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001234 return llvm::DINode::FlagProtected;
Eric Christophere7b87e52014-10-26 23:40:33 +00001235 case clang::AS_public:
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001236 return llvm::DINode::FlagPublic;
Eric Christophere7b87e52014-10-26 23:40:33 +00001237 case clang::AS_none:
Leny Kholodov80c047d2016-09-06 10:48:04 +00001238 return llvm::DINode::FlagZero;
Adrian Prantl21361fb2014-08-29 22:44:27 +00001239 }
1240 llvm_unreachable("unexpected access enumerator");
1241}
Guy Benyei11169dd2012-12-18 14:30:41 +00001242
David Majnemerb4b671e2016-06-30 03:01:59 +00001243llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1244 llvm::DIScope *RecordTy,
1245 const RecordDecl *RD) {
1246 StringRef Name = BitFieldDecl->getName();
1247 QualType Ty = BitFieldDecl->getType();
1248 SourceLocation Loc = BitFieldDecl->getLocation();
1249 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1250 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1251
1252 // Get the location for the field.
1253 llvm::DIFile *File = getOrCreateFile(Loc);
1254 unsigned Line = getLineNumber(Loc);
1255
1256 const CGBitFieldInfo &BitFieldInfo =
1257 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1258 uint64_t SizeInBits = BitFieldInfo.Size;
1259 assert(SizeInBits > 0 && "found named 0-width bitfield");
David Majnemerb4b671e2016-06-30 03:01:59 +00001260 uint64_t StorageOffsetInBits =
1261 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
Reid Kleckner06a4b2a2017-06-12 19:57:56 +00001262 uint64_t Offset = BitFieldInfo.Offset;
1263 // The bit offsets for big endian machines are reversed for big
1264 // endian target, compensate for that as the DIDerivedType requires
1265 // un-reversed offsets.
1266 if (CGM.getDataLayout().isBigEndian())
1267 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1268 uint64_t OffsetInBits = StorageOffsetInBits + Offset;
Leny Kholodov80c047d2016-09-06 10:48:04 +00001269 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
David Majnemerb4b671e2016-06-30 03:01:59 +00001270 return DBuilder.createBitFieldMemberType(
Victor Leschuka7ece032016-10-20 00:13:19 +00001271 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1272 Flags, DebugType);
David Majnemerb4b671e2016-06-30 03:01:59 +00001273}
1274
1275llvm::DIType *
1276CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
1277 AccessSpecifier AS, uint64_t offsetInBits,
Victor Leschuka7ece032016-10-20 00:13:19 +00001278 uint32_t AlignInBits, llvm::DIFile *tunit,
1279 llvm::DIScope *scope, const RecordDecl *RD) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001280 llvm::DIType *debugType = getOrCreateType(type, tunit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001281
1282 // Get the location for the field.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001283 llvm::DIFile *file = getOrCreateFile(loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001284 unsigned line = getLineNumber(loc);
1285
David Majnemer34b57492014-07-30 01:30:47 +00001286 uint64_t SizeInBits = 0;
Victor Leschuka7ece032016-10-20 00:13:19 +00001287 auto Align = AlignInBits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001288 if (!type->isIncompleteArrayType()) {
David Majnemer34b57492014-07-30 01:30:47 +00001289 TypeInfo TI = CGM.getContext().getTypeInfo(type);
1290 SizeInBits = TI.Width;
Victor Leschuka7ece032016-10-20 00:13:19 +00001291 if (!Align)
1292 Align = getTypeAlignIfRequired(type, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001293 }
1294
Leny Kholodov80c047d2016-09-06 10:48:04 +00001295 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001296 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1297 offsetInBits, flags, debugType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001298}
1299
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001300void CGDebugInfo::CollectRecordLambdaFields(
1301 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001302 llvm::DIType *RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +00001303 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1304 // has the name and the location of the variable so we should iterate over
1305 // both concurrently.
1306 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1307 RecordDecl::field_iterator Field = CXXDecl->field_begin();
1308 unsigned fieldno = 0;
1309 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
Eric Christophere7b87e52014-10-26 23:40:33 +00001310 E = CXXDecl->captures_end();
1311 I != E; ++I, ++Field, ++fieldno) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00001312 const LambdaCapture &C = *I;
Eric Christopher91a31902013-01-16 01:22:32 +00001313 if (C.capturesVariable()) {
David Majnemerb4b671e2016-06-30 03:01:59 +00001314 SourceLocation Loc = C.getLocation();
1315 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
Eric Christopher91a31902013-01-16 01:22:32 +00001316 VarDecl *V = C.getCapturedVar();
Eric Christopher91a31902013-01-16 01:22:32 +00001317 StringRef VName = V->getName();
David Majnemerb4b671e2016-06-30 03:01:59 +00001318 llvm::DIFile *VUnit = getOrCreateFile(Loc);
Victor Leschuka7ece032016-10-20 00:13:19 +00001319 auto Align = getDeclAlignIfRequired(V, CGM.getContext());
David Majnemerb4b671e2016-06-30 03:01:59 +00001320 llvm::DIType *FieldType = createFieldType(
1321 VName, Field->getType(), Loc, Field->getAccess(),
Victor Leschuka7ece032016-10-20 00:13:19 +00001322 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
David Majnemerb4b671e2016-06-30 03:01:59 +00001323 elements.push_back(FieldType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001324 } else if (C.capturesThis()) {
Eric Christopher91a31902013-01-16 01:22:32 +00001325 // TODO: Need to handle 'this' in some way by probably renaming the
1326 // this of the lambda class and having a field member of 'this' or
1327 // by using AT_object_pointer for the function and having that be
1328 // used as 'this' for semantic references.
Eric Christopher91a31902013-01-16 01:22:32 +00001329 FieldDecl *f = *Field;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001330 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
Eric Christopher91a31902013-01-16 01:22:32 +00001331 QualType type = f->getType();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001332 llvm::DIType *fieldType = createFieldType(
David Majnemerb4b671e2016-06-30 03:01:59 +00001333 "this", type, f->getLocation(), f->getAccess(),
Eric Christophere7b87e52014-10-26 23:40:33 +00001334 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
Eric Christopher91a31902013-01-16 01:22:32 +00001335
1336 elements.push_back(fieldType);
1337 }
1338 }
1339}
1340
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001341llvm::DIDerivedType *
1342CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
Duncan P. N. Exon Smithc09c5482015-04-20 21:17:26 +00001343 const RecordDecl *RD) {
Eric Christopher91a31902013-01-16 01:22:32 +00001344 // Create the descriptor for the static variable, with or without
1345 // constant initializers.
David Blaikie8e707bb2014-10-14 22:22:17 +00001346 Var = Var->getCanonicalDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001347 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1348 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
Eric Christopher91a31902013-01-16 01:22:32 +00001349
Eric Christopher91a31902013-01-16 01:22:32 +00001350 unsigned LineNumber = getLineNumber(Var->getLocation());
1351 StringRef VName = Var->getName();
Craig Topper8a13c412014-05-21 05:09:00 +00001352 llvm::Constant *C = nullptr;
Eric Christopher91a31902013-01-16 01:22:32 +00001353 if (Var->getInit()) {
1354 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +00001355 if (Value) {
1356 if (Value->isInt())
1357 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1358 if (Value->isFloat())
1359 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1360 }
Eric Christopher91a31902013-01-16 01:22:32 +00001361 }
1362
Leny Kholodov80c047d2016-09-06 10:48:04 +00001363 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
Victor Leschuka7ece032016-10-20 00:13:19 +00001364 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001365 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
Victor Leschuka7ece032016-10-20 00:13:19 +00001366 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001367 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
David Blaikieae019462013-08-15 22:50:29 +00001368 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +00001369}
1370
Eric Christophere7b87e52014-10-26 23:40:33 +00001371void CGDebugInfo::CollectRecordNormalField(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001372 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1373 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
Eric Christophere7b87e52014-10-26 23:40:33 +00001374 const RecordDecl *RD) {
Eric Christopher91a31902013-01-16 01:22:32 +00001375 StringRef name = field->getName();
1376 QualType type = field->getType();
1377
1378 // Ignore unnamed fields unless they're anonymous structs/unions.
1379 if (name.empty() && !type->isRecordType())
1380 return;
1381
David Majnemerb4b671e2016-06-30 03:01:59 +00001382 llvm::DIType *FieldType;
Eric Christopher91a31902013-01-16 01:22:32 +00001383 if (field->isBitField()) {
David Majnemerb4b671e2016-06-30 03:01:59 +00001384 FieldType = createBitFieldType(field, RecordTy, RD);
1385 } else {
Victor Leschuka7ece032016-10-20 00:13:19 +00001386 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
David Majnemerb4b671e2016-06-30 03:01:59 +00001387 FieldType =
1388 createFieldType(name, type, field->getLocation(), field->getAccess(),
Victor Leschuka7ece032016-10-20 00:13:19 +00001389 OffsetInBits, Align, tunit, RecordTy, RD);
Eric Christopher91a31902013-01-16 01:22:32 +00001390 }
1391
David Majnemerb4b671e2016-06-30 03:01:59 +00001392 elements.push_back(FieldType);
Eric Christopher91a31902013-01-16 01:22:32 +00001393}
1394
Reid Klecknere2e82062017-08-08 20:30:14 +00001395void CGDebugInfo::CollectRecordNestedType(
1396 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1397 QualType Ty = CGM.getContext().getTypeDeclType(TD);
Reid Kleckner755220b2016-08-01 18:56:13 +00001398 // Injected class names are not considered nested records.
1399 if (isa<InjectedClassNameType>(Ty))
1400 return;
Reid Klecknere2e82062017-08-08 20:30:14 +00001401 SourceLocation Loc = TD->getLocation();
Adrian McCarthyab1e7862016-07-21 18:43:20 +00001402 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1403 elements.push_back(nestedType);
1404}
1405
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001406void CGDebugInfo::CollectRecordFields(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001407 const RecordDecl *record, llvm::DIFile *tunit,
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001408 SmallVectorImpl<llvm::Metadata *> &elements,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001409 llvm::DICompositeType *RecordTy) {
David Majnemer58ed0f32016-07-17 00:39:12 +00001410 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001411
Eric Christopher91a31902013-01-16 01:22:32 +00001412 if (CXXDecl && CXXDecl->isLambda())
1413 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1414 else {
1415 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001416
Eric Christopher91a31902013-01-16 01:22:32 +00001417 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +00001418 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +00001419
Eric Christopher91a31902013-01-16 01:22:32 +00001420 // Static and non-static members should appear in the same order as
1421 // the corresponding declarations in the source program.
Aaron Ballman629afae2014-03-07 19:56:05 +00001422 for (const auto *I : record->decls())
1423 if (const auto *V = dyn_cast<VarDecl>(I)) {
Paul Robinsonb17327d2016-04-27 17:37:12 +00001424 if (V->hasAttr<NoDebugAttr>())
1425 continue;
Reid Kleckner891b2712018-07-20 20:55:00 +00001426
1427 // Skip variable template specializations when emitting CodeView. MSVC
1428 // doesn't emit them.
1429 if (CGM.getCodeGenOpts().EmitCodeView &&
1430 isa<VarTemplateSpecializationDecl>(V))
1431 continue;
1432
David Blaikie4f3b7362019-06-17 19:40:52 +00001433 if (isa<VarTemplatePartialSpecializationDecl>(V))
1434 continue;
1435
David Blaikiece763042013-08-20 21:49:21 +00001436 // Reuse the existing static member declaration if one exists
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001437 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
David Blaikiece763042013-08-20 21:49:21 +00001438 if (MI != StaticDataMemberCache.end()) {
1439 assert(MI->second &&
1440 "Static data member declaration should still exist");
Duncan P. N. Exon Smithac346ba2015-07-24 18:05:58 +00001441 elements.push_back(MI->second);
Adrian Prantl21361fb2014-08-29 22:44:27 +00001442 } else {
1443 auto Field = CreateRecordStaticField(V, RecordTy, record);
1444 elements.push_back(Field);
1445 }
Aaron Ballman629afae2014-03-07 19:56:05 +00001446 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
Eric Christophere7b87e52014-10-26 23:40:33 +00001447 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1448 elements, RecordTy, record);
Eric Christopher91a31902013-01-16 01:22:32 +00001449
1450 // Bump field number for next field.
1451 ++fieldNo;
Reid Kleckner891b2712018-07-20 20:55:00 +00001452 } else if (CGM.getCodeGenOpts().EmitCodeView) {
1453 // Debug info for nested types is included in the member list only for
1454 // CodeView.
Reid Klecknere2e82062017-08-08 20:30:14 +00001455 if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1456 if (!nestedType->isImplicit() &&
1457 nestedType->getDeclContext() == record)
1458 CollectRecordNestedType(nestedType, elements);
1459 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001460 }
1461}
1462
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001463llvm::DISubroutineType *
Guy Benyei11169dd2012-12-18 14:30:41 +00001464CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001465 llvm::DIFile *Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +00001466 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +00001467 if (Method->isStatic())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001468 return cast_or_null<llvm::DISubroutineType>(
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00001469 getOrCreateType(QualType(Func, 0), Unit));
Brian Gesiak5488ab42019-01-11 01:54:53 +00001470 return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit);
David Blaikie7eb06852013-01-07 23:06:35 +00001471}
David Blaikie2aaf0652013-01-07 22:24:59 +00001472
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001473llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1474 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001475 // Add "this" pointer.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001476 llvm::DITypeRefArray Args(
1477 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00001478 ->getTypeArray());
Duncan P. N. Exon Smitha98fac62015-04-07 04:14:45 +00001479 assert(Args.size() && "Invalid number of arguments!");
Guy Benyei11169dd2012-12-18 14:30:41 +00001480
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001481 SmallVector<llvm::Metadata *, 16> Elts;
Guy Benyei11169dd2012-12-18 14:30:41 +00001482
1483 // First element is always return type. For 'void' functions it is NULL.
Duncan P. N. Exon Smith37328582015-04-07 18:41:26 +00001484 Elts.push_back(Args[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001485
David Blaikie2aaf0652013-01-07 22:24:59 +00001486 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +00001487 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +00001488 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1489 // Create pointer type directly in this case.
1490 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1491 QualType PointeeTy = ThisPtrTy->getPointeeType();
1492 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +00001493 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Victor Leschuka7ece032016-10-20 00:13:19 +00001494 auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001495 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1496 llvm::DIType *ThisPtrType =
Eric Christophere7b87e52014-10-26 23:40:33 +00001497 DBuilder.createPointerType(PointeeType, Size, Align);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001498 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
David Blaikie2aaf0652013-01-07 22:24:59 +00001499 // TODO: This and the artificial type below are misleading, the
1500 // types aren't artificial the argument is, but the current
1501 // metadata doesn't represent that.
1502 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1503 Elts.push_back(ThisPtrType);
1504 } else {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001505 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001506 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
David Blaikie2aaf0652013-01-07 22:24:59 +00001507 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1508 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001509 }
1510
1511 // Copy rest of the arguments.
Duncan P. N. Exon Smitha98fac62015-04-07 04:14:45 +00001512 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1513 Elts.push_back(Args[i]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001514
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001515 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
Guy Benyei11169dd2012-12-18 14:30:41 +00001516
Leny Kholodov80c047d2016-09-06 10:48:04 +00001517 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001518 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001519 Flags |= llvm::DINode::FlagLValueReference;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001520 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001521 Flags |= llvm::DINode::FlagRValueReference;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001522
Reid Klecknerf00f8032016-06-08 20:41:54 +00001523 return DBuilder.createSubroutineType(EltTypeArray, Flags,
1524 getDwarfCC(Func->getCallConv()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001525}
1526
Eric Christopherb2a008c2013-05-16 00:45:12 +00001527/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001528/// inside a function.
1529static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
David Majnemer58ed0f32016-07-17 00:39:12 +00001530 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 return isFunctionLocalClass(NRD);
1532 if (isa<FunctionDecl>(RD->getDeclContext()))
1533 return true;
1534 return false;
1535}
1536
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001537llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1538 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001539 bool IsCtorOrDtor =
Eric Christophere7b87e52014-10-26 23:40:33 +00001540 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001541
Guy Benyei11169dd2012-12-18 14:30:41 +00001542 StringRef MethodName = getFunctionName(Method);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001543 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001544
1545 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1546 // make sense to give a single ctor/dtor a linkage name.
1547 StringRef MethodLinkageName;
David Blaikie71647672016-04-12 21:22:48 +00001548 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1549 // property to use here. It may've been intended to model "is non-external
1550 // type" but misses cases of non-function-local but non-external classes such
1551 // as those in anonymous namespaces as well as the reverse - external types
1552 // that are function local, such as those in (non-local) inline functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00001553 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1554 MethodLinkageName = CGM.getMangledName(Method);
1555
1556 // Get the location for the method.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001557 llvm::DIFile *MethodDefUnit = nullptr;
David Blaikie7fceebf2013-08-19 03:37:48 +00001558 unsigned MethodLine = 0;
1559 if (!Method->isImplicit()) {
1560 MethodDefUnit = getOrCreateFile(Method->getLocation());
1561 MethodLine = getLineNumber(Method->getLocation());
1562 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001563
1564 // Collect virtual method info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001565 llvm::DIType *ContainingType = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001566 unsigned VIndex = 0;
Leny Kholodov80c047d2016-09-06 10:48:04 +00001567 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Paul Robinsoncda54212018-11-19 18:29:28 +00001568 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
Reid Kleckner0358cbf2016-07-01 02:41:25 +00001569 int ThisAdjustment = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001570
Guy Benyei11169dd2012-12-18 14:30:41 +00001571 if (Method->isVirtual()) {
1572 if (Method->isPure())
Paul Robinsoncda54212018-11-19 18:29:28 +00001573 SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
Guy Benyei11169dd2012-12-18 14:30:41 +00001574 else
Paul Robinsoncda54212018-11-19 18:29:28 +00001575 SPFlags |= llvm::DISubprogram::SPFlagVirtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001576
Reid Kleckner216d0a12016-06-16 20:08:51 +00001577 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1578 // It doesn't make sense to give a virtual destructor a vtable index,
1579 // since a single destructor has two entries in the vtable.
1580 if (!isa<CXXDestructorDecl>(Method))
1581 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1582 } else {
1583 // Emit MS ABI vftable information. There is only one entry for the
1584 // deleting dtor.
1585 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1586 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
Reid Klecknercbec0262018-04-02 20:00:39 +00001587 MethodVFTableLocation ML =
Reid Kleckner216d0a12016-06-16 20:08:51 +00001588 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1589 VIndex = ML.Index;
Reid Klecknerc4871ed2016-06-22 18:34:45 +00001590
1591 // CodeView only records the vftable offset in the class that introduces
1592 // the virtual method. This is possible because, unlike Itanium, the MS
1593 // C++ ABI does not include all virtual methods from non-primary bases in
1594 // the vtable for the most derived class. For example, if C inherits from
1595 // A and B, C's primary vftable will not include B's virtual methods.
Benjamin Krameracfa3392017-12-17 23:52:45 +00001596 if (Method->size_overridden_methods() == 0)
Reid Klecknerc4871ed2016-06-22 18:34:45 +00001597 Flags |= llvm::DINode::FlagIntroducedVirtual;
1598
Reid Kleckner0358cbf2016-07-01 02:41:25 +00001599 // The 'this' adjustment accounts for both the virtual and non-virtual
1600 // portions of the adjustment. Presumably the debugger only uses it when
1601 // it knows the dynamic type of an object.
1602 ThisAdjustment = CGM.getCXXABI()
1603 .getVirtualFunctionPrologueThisAdjustment(GD)
1604 .getQuantity();
Reid Kleckner216d0a12016-06-16 20:08:51 +00001605 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001606 ContainingType = RecordTy;
1607 }
1608
Adrian Prantlf919be32019-10-29 09:20:14 -07001609 // We're checking for deleted C++ special member functions
1610 // [Ctors,Dtors, Copy/Move]
Sourabh Singh Tomar52ea3082019-11-02 01:28:40 +05301611 auto checkAttrDeleted = [&](const auto *Method) {
Adrian Prantlf919be32019-10-29 09:20:14 -07001612 if (Method->getCanonicalDecl()->isDeleted())
1613 SPFlags |= llvm::DISubprogram::SPFlagDeleted;
1614 };
1615
1616 switch (Method->getKind()) {
1617
1618 case Decl::CXXConstructor:
1619 case Decl::CXXDestructor:
1620 checkAttrDeleted(Method);
1621 break;
1622 case Decl::CXXMethod:
1623 if (Method->isCopyAssignmentOperator() ||
1624 Method->isMoveAssignmentOperator())
1625 checkAttrDeleted(Method);
1626 break;
1627 default:
1628 break;
1629 }
1630
Adrian Prantla9cfde12019-10-16 16:30:38 +00001631 if (Method->isNoReturn())
1632 Flags |= llvm::DINode::FlagNoReturn;
Adrian Prantlf919be32019-10-29 09:20:14 -07001633
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001634 if (Method->isStatic())
1635 Flags |= llvm::DINode::FlagStaticMember;
Guy Benyei11169dd2012-12-18 14:30:41 +00001636 if (Method->isImplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001637 Flags |= llvm::DINode::FlagArtificial;
Adrian Prantl21361fb2014-08-29 22:44:27 +00001638 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
David Majnemer58ed0f32016-07-17 00:39:12 +00001639 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001640 if (CXXC->isExplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001641 Flags |= llvm::DINode::FlagExplicit;
David Majnemer58ed0f32016-07-17 00:39:12 +00001642 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001643 if (CXXC->isExplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001644 Flags |= llvm::DINode::FlagExplicit;
Guy Benyei11169dd2012-12-18 14:30:41 +00001645 }
1646 if (Method->hasPrototype())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001647 Flags |= llvm::DINode::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001648 if (Method->getRefQualifier() == RQ_LValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001649 Flags |= llvm::DINode::FlagLValueReference;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001650 if (Method->getRefQualifier() == RQ_RValue)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001651 Flags |= llvm::DINode::FlagRValueReference;
Paul Robinsoncda54212018-11-19 18:29:28 +00001652 if (CGM.getLangOpts().Optimize)
1653 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
Guy Benyei11169dd2012-12-18 14:30:41 +00001654
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001655 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1656 llvm::DISubprogram *SP = DBuilder.createMethod(
Eric Christophere7b87e52014-10-26 23:40:33 +00001657 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
Paul Robinsoncda54212018-11-19 18:29:28 +00001658 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
Reid Kleckner0358cbf2016-07-01 02:41:25 +00001659 TParamsArray.get());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001660
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001661 SPCache[Method->getCanonicalDecl()].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00001662
1663 return SP;
1664}
1665
Eric Christophere7b87e52014-10-26 23:40:33 +00001666void CGDebugInfo::CollectCXXMemberFunctions(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001667 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1668 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001669
1670 // Since we want more than just the individual member decls if we
1671 // have templated functions iterate over every declaration to gather
1672 // the functions.
Eric Christophere7b87e52014-10-26 23:40:33 +00001673 for (const auto *I : RD->decls()) {
David Blaikiefd580722014-10-06 05:18:55 +00001674 const auto *Method = dyn_cast<CXXMethodDecl>(I);
1675 // If the member is implicit, don't add it to the member list. This avoids
1676 // the member being added to type units by LLVM, while still allowing it
1677 // to be emitted into the type declaration/reference inside the compile
1678 // unit.
Paul Robinson6a7511b2015-06-25 17:50:43 +00001679 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
David Blaikie6dddfe32014-10-06 05:52:27 +00001680 // FIXME: Handle Using(Shadow?)Decls here to create
1681 // DW_TAG_imported_declarations inside the class for base decls brought into
1682 // derived classes. GDB doesn't seem to notice/leverage these when I tried
1683 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1684 // referenced)
Paul Robinson6a7511b2015-06-25 17:50:43 +00001685 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
David Blaikiefd580722014-10-06 05:18:55 +00001686 continue;
David Blaikie42edade2014-11-11 20:44:45 +00001687
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00001688 if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
David Blaikie42edade2014-11-11 20:44:45 +00001689 continue;
1690
David Blaikiefd580722014-10-06 05:18:55 +00001691 // Reuse the existing member function declaration if it exists.
1692 // It may be associated with the declaration of the type & should be
1693 // reused as we're building the definition.
1694 //
1695 // This situation can arise in the vtable-based debug info reduction where
1696 // implicit members are emitted in a non-vtable TU.
1697 auto MI = SPCache.find(Method->getCanonicalDecl());
1698 EltTys.push_back(MI == SPCache.end()
1699 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001700 : static_cast<llvm::Metadata *>(MI->second));
Guy Benyei11169dd2012-12-18 14:30:41 +00001701 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001702}
Guy Benyei11169dd2012-12-18 14:30:41 +00001703
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001704void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001705 SmallVectorImpl<llvm::Metadata *> &EltTys,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001706 llvm::DIType *RecordTy) {
Bob Haarmandff36732016-10-25 22:19:32 +00001707 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1708 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1709 llvm::DINode::FlagZero);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001710
Bob Haarmandff36732016-10-25 22:19:32 +00001711 // If we are generating CodeView debug info, we also need to emit records for
1712 // indirect virtual base classes.
1713 if (CGM.getCodeGenOpts().EmitCodeView) {
1714 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1715 llvm::DINode::FlagIndirectVirtualBase);
1716 }
1717}
1718
1719void CGDebugInfo::CollectCXXBasesAux(
1720 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1721 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1722 const CXXRecordDecl::base_class_const_range &Bases,
1723 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
1724 llvm::DINode::DIFlags StartingFlags) {
1725 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1726 for (const auto &BI : Bases) {
David Majnemer58ed0f32016-07-17 00:39:12 +00001727 const auto *Base =
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00001728 cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
Bob Haarmandff36732016-10-25 22:19:32 +00001729 if (!SeenTypes.insert(Base).second)
1730 continue;
1731 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1732 llvm::DINode::DIFlags BFlags = StartingFlags;
1733 uint64_t BaseOffset;
Brock Wyma3db2b102018-05-14 21:21:22 +00001734 uint32_t VBPtrOffset = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001735
Aaron Ballman574705e2014-03-13 15:41:46 +00001736 if (BI.isVirtual()) {
Reid Klecknerd3b23d62014-08-07 21:29:25 +00001737 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1738 // virtual base offset offset is -ve. The code generator emits dwarf
1739 // expression where it expects +ve number.
Eric Christophere7b87e52014-10-26 23:40:33 +00001740 BaseOffset = 0 - CGM.getItaniumVTableContext()
1741 .getVirtualBaseOffsetOffset(RD, Base)
1742 .getQuantity();
Reid Klecknerd3b23d62014-08-07 21:29:25 +00001743 } else {
1744 // In the MS ABI, store the vbtable offset, which is analogous to the
1745 // vbase offset offset in Itanium.
1746 BaseOffset =
1747 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001748 VBPtrOffset = CGM.getContext()
1749 .getASTRecordLayout(RD)
1750 .getVBPtrOffset()
1751 .getQuantity();
Reid Klecknerd3b23d62014-08-07 21:29:25 +00001752 }
Bob Haarmandff36732016-10-25 22:19:32 +00001753 BFlags |= llvm::DINode::FlagVirtual;
Guy Benyei11169dd2012-12-18 14:30:41 +00001754 } else
1755 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1756 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1757 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001758
Adrian Prantl21361fb2014-08-29 22:44:27 +00001759 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001760 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
1761 VBPtrOffset, BFlags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001762 EltTys.push_back(DTy);
1763 }
1764}
1765
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001766llvm::DINodeArray
Eric Christophere7b87e52014-10-26 23:40:33 +00001767CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1768 ArrayRef<TemplateArgument> TAList,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001769 llvm::DIFile *Unit) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001770 SmallVector<llvm::Metadata *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001771 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1772 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001773 StringRef Name;
1774 if (TPList)
1775 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001776 switch (TA.getKind()) {
1777 case TemplateArgument::Type: {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001778 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001779 TemplateParams.push_back(
1780 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
David Blaikie38079fd2013-05-10 21:53:14 +00001781 } break;
1782 case TemplateArgument::Integral: {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001783 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001784 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1785 TheCU, Name, TTy,
1786 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
David Blaikie38079fd2013-05-10 21:53:14 +00001787 } break;
1788 case TemplateArgument::Declaration: {
1789 const ValueDecl *D = TA.getAsDecl();
David Blaikieb5c7e6a2014-10-18 02:21:26 +00001790 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001791 llvm::DIType *TTy = getOrCreateType(T, Unit);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001792 llvm::Constant *V = nullptr;
Michael Liao982cbb62019-03-06 21:16:27 +00001793 // Skip retrieve the value if that template parameter has cuda device
1794 // attribute, i.e. that value is not available at the host side.
1795 if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
1796 !D->hasAttr<CUDADeviceAttr>()) {
1797 const CXXMethodDecl *MD;
1798 // Variable pointer template parameters have a value that is the address
1799 // of the variable.
1800 if (const auto *VD = dyn_cast<VarDecl>(D))
1801 V = CGM.GetAddrOfGlobalVar(VD);
1802 // Member function pointers have special support for building them,
1803 // though this is currently unsupported in LLVM CodeGen.
1804 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1805 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1806 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1807 V = CGM.GetAddrOfFunction(FD);
1808 // Member data pointers have special handling too to compute the fixed
1809 // offset within the object.
1810 else if (const auto *MPT =
1811 dyn_cast<MemberPointerType>(T.getTypePtr())) {
1812 // These five lines (& possibly the above member function pointer
1813 // handling) might be able to be refactored to use similar code in
1814 // CodeGenModule::getMemberPointerConstant
1815 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1816 CharUnits chars =
1817 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1818 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1819 }
Simon Pilgrimcfee2ef2019-10-16 10:38:49 +00001820 assert(V && "Failed to find template parameter pointer");
Michael Liao982cbb62019-03-06 21:16:27 +00001821 V = V->stripPointerCasts();
David Blaikie38079fd2013-05-10 21:53:14 +00001822 }
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001823 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
Michael Liao982cbb62019-03-06 21:16:27 +00001824 TheCU, Name, TTy, cast_or_null<llvm::Constant>(V)));
David Blaikie38079fd2013-05-10 21:53:14 +00001825 } break;
1826 case TemplateArgument::NullPtr: {
1827 QualType T = TA.getNullPtrType();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001828 llvm::DIType *TTy = getOrCreateType(T, Unit);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001829 llvm::Constant *V = nullptr;
David Blaikie38079fd2013-05-10 21:53:14 +00001830 // Special case member data pointer null values since they're actually -1
1831 // instead of zero.
David Majnemer58ed0f32016-07-17 00:39:12 +00001832 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
David Blaikie38079fd2013-05-10 21:53:14 +00001833 // But treat member function pointers as simple zero integers because
1834 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1835 // CodeGen grows handling for values of non-null member function
1836 // pointers then perhaps we could remove this special case and rely on
1837 // EmitNullMemberPointer for member function pointers.
1838 if (MPT->isMemberDataPointer())
1839 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1840 if (!V)
1841 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001842 TemplateParams.push_back(
1843 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V));
David Blaikie38079fd2013-05-10 21:53:14 +00001844 } break;
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001845 case TemplateArgument::Template:
1846 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00001847 TheCU, Name, nullptr,
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001848 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1849 break;
1850 case TemplateArgument::Pack:
1851 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1852 TheCU, Name, nullptr,
1853 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1854 break;
David Majnemer5559d472013-08-24 08:21:10 +00001855 case TemplateArgument::Expression: {
1856 const Expr *E = TA.getAsExpr();
1857 QualType T = E->getType();
David Majnemer922ad9f2014-10-24 19:49:04 +00001858 if (E->isGLValue())
1859 T = CGM.getContext().getLValueReferenceType(T);
John McCallde0fe072017-08-15 21:42:52 +00001860 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
David Majnemer5559d472013-08-24 08:21:10 +00001861 assert(V && "Expression in template argument isn't constant");
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001862 llvm::DIType *TTy = getOrCreateType(T, Unit);
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00001863 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
David Majnemer58ed0f32016-07-17 00:39:12 +00001864 TheCU, Name, TTy, V->stripPointerCasts()));
David Majnemer5559d472013-08-24 08:21:10 +00001865 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001866 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001867 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001868 case TemplateArgument::Null:
1869 llvm_unreachable(
1870 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001871 }
1872 }
1873 return DBuilder.getOrCreateArray(TemplateParams);
1874}
1875
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001876llvm::DINodeArray
Duncan P. N. Exon Smith8e47da42015-04-21 20:07:29 +00001877CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001878 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001879 if (FD->getTemplatedKind() ==
1880 FunctionDecl::TK_FunctionTemplateSpecialization) {
Eric Christophere7b87e52014-10-26 23:40:33 +00001881 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1882 ->getTemplate()
1883 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001884 return CollectTemplateParams(
1885 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001886 }
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001887 return llvm::DINodeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +00001888}
1889
Matthew Voss20165362018-10-03 18:45:04 +00001890llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
Reid Kleckner2dbd5d82019-05-02 17:45:54 +00001891 llvm::DIFile *Unit) {
1892 // Always get the full list of parameters, not just the ones from the
1893 // specialization. A partial specialization may have fewer parameters than
1894 // there are arguments.
1895 auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VL);
1896 if (!TS)
1897 return llvm::DINodeArray();
1898 VarTemplateDecl *T = TS->getSpecializedTemplate();
1899 const TemplateParameterList *TList = T->getTemplateParameters();
1900 auto TA = TS->getTemplateArgs().asArray();
1901 return CollectTemplateParams(TList, TA, Unit);
Matthew Voss20165362018-10-03 18:45:04 +00001902}
1903
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001904llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1905 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
Reid Kleckner2dbd5d82019-05-02 17:45:54 +00001906 // Always get the full list of parameters, not just the ones from the
1907 // specialization. A partial specialization may have fewer parameters than
1908 // there are arguments.
Adrian Prantl649f0302014-04-17 01:04:01 +00001909 TemplateParameterList *TPList =
Eric Christophere7b87e52014-10-26 23:40:33 +00001910 TSpecial->getSpecializedTemplate()->getTemplateParameters();
Adrian Prantl2c92e9c2014-04-17 00:30:48 +00001911 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001912 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001913}
1914
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001915llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
Duncan P. N. Exon Smithb7470232015-04-15 23:48:50 +00001916 if (VTablePtrType)
Guy Benyei11169dd2012-12-18 14:30:41 +00001917 return VTablePtrType;
1918
1919 ASTContext &Context = CGM.getContext();
1920
1921 /* Function type */
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001922 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001923 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
Eric Christopher28a6db52015-10-15 06:56:08 +00001924 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001925 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00001926 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1927 Optional<unsigned> DWARFAddressSpace =
1928 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
1929
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00001930 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
1931 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
Guy Benyei11169dd2012-12-18 14:30:41 +00001932 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1933 return VTablePtrType;
1934}
1935
Guy Benyei11169dd2012-12-18 14:30:41 +00001936StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00001937 // Copy the gdb compatible name on the side and use its reference.
1938 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00001939}
1940
Reid Kleckner105c5652019-04-24 22:45:44 +00001941StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
1942 DynamicInitKind StubKind,
1943 llvm::Function *InitFn) {
1944 // If we're not emitting codeview, use the mangled name. For Itanium, this is
1945 // arbitrary.
Alexandre Ganeacaf31662019-11-15 16:21:17 -05001946 if (!CGM.getCodeGenOpts().EmitCodeView)
Reid Kleckner105c5652019-04-24 22:45:44 +00001947 return InitFn->getName();
1948
1949 // Print the normal qualified name for the variable, then break off the last
1950 // NNS, and add the appropriate other text. Clang always prints the global
1951 // variable name without template arguments, so we can use rsplit("::") and
1952 // then recombine the pieces.
1953 SmallString<128> QualifiedGV;
1954 StringRef Quals;
1955 StringRef GVName;
1956 {
1957 llvm::raw_svector_ostream OS(QualifiedGV);
1958 VD->printQualifiedName(OS, getPrintingPolicy());
1959 std::tie(Quals, GVName) = OS.str().rsplit("::");
1960 if (GVName.empty())
1961 std::swap(Quals, GVName);
1962 }
1963
1964 SmallString<128> InitName;
1965 llvm::raw_svector_ostream OS(InitName);
1966 if (!Quals.empty())
1967 OS << Quals << "::";
1968
1969 switch (StubKind) {
1970 case DynamicInitKind::NoStub:
1971 llvm_unreachable("not an initializer");
1972 case DynamicInitKind::Initializer:
1973 OS << "`dynamic initializer for '";
1974 break;
1975 case DynamicInitKind::AtExit:
1976 OS << "`dynamic atexit destructor for '";
1977 break;
1978 }
1979
1980 OS << GVName;
1981
1982 // Add any template specialization args.
1983 if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
1984 printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
1985 getPrintingPolicy());
1986 }
1987
1988 OS << '\'';
1989
1990 return internString(OS.str());
1991}
1992
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00001993void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
Reid Klecknerdc124992016-08-31 16:11:43 +00001994 SmallVectorImpl<llvm::Metadata *> &EltTys,
1995 llvm::DICompositeType *RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001996 // If this class is not dynamic then there is not any vtable info to collect.
1997 if (!RD->isDynamicClass())
1998 return;
1999
Reid Kleckner59812422016-08-31 20:35:01 +00002000 // Don't emit any vtable shape or vptr info if this class doesn't have an
2001 // extendable vfptr. This can happen if the class doesn't have virtual
2002 // methods, or in the MS ABI if those virtual methods only come from virtually
2003 // inherited bases.
2004 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2005 if (!RL.hasExtendableVFPtr())
2006 return;
2007
Reid Klecknerdc124992016-08-31 16:11:43 +00002008 // CodeView needs to know how large the vtable of every dynamic class is, so
2009 // emit a special named pointer type into the element list. The vptr type
2010 // points to this type as well.
2011 llvm::DIType *VPtrTy = nullptr;
2012 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2013 CGM.getTarget().getCXXABI().isMicrosoft();
2014 if (NeedVTableShape) {
2015 uint64_t PtrWidth =
2016 CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2017 const VTableLayout &VFTLayout =
2018 CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
2019 unsigned VSlotCount =
Peter Collingbournee53683f2016-09-08 01:14:39 +00002020 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
Reid Klecknerdc124992016-08-31 16:11:43 +00002021 unsigned VTableWidth = PtrWidth * VSlotCount;
Konstantin Zhuravlyovd1ba16e2017-03-08 23:56:48 +00002022 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2023 Optional<unsigned> DWARFAddressSpace =
2024 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
Reid Klecknerdc124992016-08-31 16:11:43 +00002025
2026 // Create a very wide void* type and insert it directly in the element list.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002027 llvm::DIType *VTableType = DBuilder.createPointerType(
2028 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
Reid Klecknerdc124992016-08-31 16:11:43 +00002029 EltTys.push_back(VTableType);
2030
2031 // The vptr is a pointer to this special vtable type.
2032 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2033 }
2034
2035 // If there is a primary base then the artificial vptr member lives there.
Reid Klecknerdc124992016-08-31 16:11:43 +00002036 if (RL.getPrimaryBase())
2037 return;
2038
2039 if (!VPtrTy)
2040 VPtrTy = getOrCreateVTablePtrType(Unit);
2041
Guy Benyei11169dd2012-12-18 14:30:41 +00002042 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002043 llvm::DIType *VPtrMember =
2044 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2045 llvm::DINode::FlagArtificial, VPtrTy);
Reid Klecknerdc124992016-08-31 16:11:43 +00002046 EltTys.push_back(VPtrMember);
Guy Benyei11169dd2012-12-18 14:30:41 +00002047}
2048
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002049llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002050 SourceLocation Loc) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002051 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002052 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
Guy Benyei11169dd2012-12-18 14:30:41 +00002053 return T;
2054}
2055
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002056llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002057 SourceLocation Loc) {
Adrian Prantlad9a195e2015-08-27 21:21:19 +00002058 return getOrCreateStandaloneType(D, Loc);
2059}
2060
2061llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
2062 SourceLocation Loc) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002063 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Adrian Prantlad9a195e2015-08-27 21:21:19 +00002064 assert(!D.isNull() && "null type");
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002065 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlad9a195e2015-08-27 21:21:19 +00002066 assert(T && "could not create debug info for type");
Adrian Prantl3a884fa2015-08-27 22:56:46 +00002067
Adrian Prantl73409ce2013-03-11 18:33:46 +00002068 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00002069 return T;
2070}
2071
Amy Huang0d0334f2019-04-12 20:25:30 +00002072void CGDebugInfo::addHeapAllocSiteMetadata(llvm::Instruction *CI,
2073 QualType D,
2074 SourceLocation Loc) {
2075 llvm::MDNode *node;
2076 if (D.getTypePtr()->isVoidPointerType()) {
2077 node = llvm::MDNode::get(CGM.getLLVMContext(), None);
2078 } else {
2079 QualType PointeeTy = D.getTypePtr()->getPointeeType();
2080 node = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
2081 }
Amy Huangfc79ab92019-04-23 21:12:58 +00002082
Amy Huang0d0334f2019-04-12 20:25:30 +00002083 CI->setMetadata("heapallocsite", node);
2084}
2085
David Blaikie483a9da2014-05-06 18:35:21 +00002086void CGDebugInfo::completeType(const EnumDecl *ED) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002087 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie483a9da2014-05-06 18:35:21 +00002088 return;
2089 QualType Ty = CGM.getContext().getEnumType(ED);
Eric Christophere7b87e52014-10-26 23:40:33 +00002090 void *TyPtr = Ty.getAsOpaquePtr();
David Blaikie483a9da2014-05-06 18:35:21 +00002091 auto I = TypeCache.find(TyPtr);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002092 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
David Blaikie483a9da2014-05-06 18:35:21 +00002093 return;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002094 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00002095 assert(!Res->isForwardDecl());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002096 TypeCache[TyPtr].reset(Res);
David Blaikie483a9da2014-05-06 18:35:21 +00002097}
2098
David Blaikieb2e86eb2013-08-15 20:49:17 +00002099void CGDebugInfo::completeType(const RecordDecl *RD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002100 if (DebugKind > codegenoptions::LimitedDebugInfo ||
David Blaikieb2e86eb2013-08-15 20:49:17 +00002101 !CGM.getLangOpts().CPlusPlus)
2102 completeRequiredType(RD);
2103}
2104
David Blaikieb11c8732017-01-30 06:36:08 +00002105/// Return true if the class or any of its methods are marked dllimport.
2106static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
2107 if (RD->hasAttr<DLLImportAttr>())
2108 return true;
2109 for (const CXXMethodDecl *MD : RD->methods())
2110 if (MD->hasAttr<DLLImportAttr>())
2111 return true;
2112 return false;
2113}
2114
Adrian Prantla43acdc2017-07-24 23:48:51 +00002115/// Does a type definition exist in an imported clang module?
2116static bool isDefinedInClangModule(const RecordDecl *RD) {
2117 // Only definitions that where imported from an AST file come from a module.
2118 if (!RD || !RD->isFromASTFile())
2119 return false;
2120 // Anonymous entities cannot be addressed. Treat them as not from module.
2121 if (!RD->isExternallyVisible() && RD->getName().empty())
2122 return false;
2123 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2124 if (!CXXDecl->isCompleteDefinition())
2125 return false;
Adrian Prantlba6fdc52018-10-24 00:06:02 +00002126 // Check wether RD is a template.
Adrian Prantla43acdc2017-07-24 23:48:51 +00002127 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2128 if (TemplateKind != TSK_Undeclared) {
Adrian Prantlba6fdc52018-10-24 00:06:02 +00002129 // Unfortunately getOwningModule() isn't accurate enough to find the
2130 // owning module of a ClassTemplateSpecializationDecl that is inside a
2131 // namespace spanning multiple modules.
2132 bool Explicit = false;
2133 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2134 Explicit = TD->isExplicitInstantiationOrSpecialization();
2135 if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
2136 return false;
Adrian Prantla43acdc2017-07-24 23:48:51 +00002137 // This is a template, check the origin of the first member.
2138 if (CXXDecl->field_begin() == CXXDecl->field_end())
2139 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2140 if (!CXXDecl->field_begin()->isFromASTFile())
2141 return false;
2142 }
2143 }
2144 return true;
2145}
2146
David Blaikie6943dea2013-08-20 01:28:15 +00002147void CGDebugInfo::completeClassData(const RecordDecl *RD) {
David Blaikieb11c8732017-01-30 06:36:08 +00002148 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2149 if (CXXRD->isDynamicClass() &&
2150 CGM.getVTableLinkage(CXXRD) ==
2151 llvm::GlobalValue::AvailableExternallyLinkage &&
2152 !isClassOrMethodDLLImport(CXXRD))
2153 return;
Adrian Prantla43acdc2017-07-24 23:48:51 +00002154
2155 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2156 return;
2157
David Blaikieb11c8732017-01-30 06:36:08 +00002158 completeClass(RD);
2159}
2160
2161void CGDebugInfo::completeClass(const RecordDecl *RD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002162 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00002163 return;
David Blaikie6943dea2013-08-20 01:28:15 +00002164 QualType Ty = CGM.getContext().getRecordType(RD);
Eric Christophere7b87e52014-10-26 23:40:33 +00002165 void *TyPtr = Ty.getAsOpaquePtr();
David Blaikieef8a9512014-05-05 23:23:53 +00002166 auto I = TypeCache.find(TyPtr);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002167 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
David Blaikieb2e86eb2013-08-15 20:49:17 +00002168 return;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002169 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00002170 assert(!Res->isForwardDecl());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002171 TypeCache[TyPtr].reset(Res);
David Blaikieb2e86eb2013-08-15 20:49:17 +00002172}
2173
David Blaikie0e716b42014-03-03 23:48:23 +00002174static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
2175 CXXRecordDecl::method_iterator End) {
David Majnemer58ed0f32016-07-17 00:39:12 +00002176 for (CXXMethodDecl *MD : llvm::make_range(I, End))
2177 if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
David Blaikief7f21852014-03-04 03:08:14 +00002178 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
David Majnemer58ed0f32016-07-17 00:39:12 +00002179 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
David Blaikie0e716b42014-03-03 23:48:23 +00002180 return true;
2181 return false;
2182}
2183
Benjamin Kramer8c305922016-02-02 11:06:51 +00002184static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
2185 bool DebugTypeExtRefs, const RecordDecl *RD,
David Blaikie0e716b42014-03-03 23:48:23 +00002186 const LangOptions &LangOpts) {
Adrian Prantl88d79172016-04-26 21:58:18 +00002187 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
Adrian Prantl43e00812016-01-19 23:42:53 +00002188 return true;
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002189
David Blaikie1ac9c982017-04-11 21:13:37 +00002190 if (auto *ES = RD->getASTContext().getExternalSource())
2191 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2192 return true;
2193
Benjamin Kramer8c305922016-02-02 11:06:51 +00002194 if (DebugKind > codegenoptions::LimitedDebugInfo)
David Blaikie0e716b42014-03-03 23:48:23 +00002195 return false;
2196
2197 if (!LangOpts.CPlusPlus)
2198 return false;
2199
2200 if (!RD->isCompleteDefinitionRequired())
2201 return true;
2202
David Majnemer58ed0f32016-07-17 00:39:12 +00002203 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie0e716b42014-03-03 23:48:23 +00002204
2205 if (!CXXDecl)
2206 return false;
2207
Adrian McCarthy99242982016-08-16 22:11:18 +00002208 // Only emit complete debug info for a dynamic class when its vtable is
2209 // emitted. However, Microsoft debuggers don't resolve type information
Reid Klecknerc9404e12016-09-09 16:27:04 +00002210 // across DLL boundaries, so skip this optimization if the class or any of its
2211 // methods are marked dllimport. This isn't a complete solution, since objects
2212 // without any dllimport methods can be used in one DLL and constructed in
2213 // another, but it is the current behavior of LimitedDebugInfo.
Adrian McCarthy99242982016-08-16 22:11:18 +00002214 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
Reid Klecknerc9404e12016-09-09 16:27:04 +00002215 !isClassOrMethodDLLImport(CXXDecl))
David Blaikie0e716b42014-03-03 23:48:23 +00002216 return true;
2217
2218 TemplateSpecializationKind Spec = TSK_Undeclared;
David Majnemer58ed0f32016-07-17 00:39:12 +00002219 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
David Blaikie0e716b42014-03-03 23:48:23 +00002220 Spec = SD->getSpecializationKind();
2221
2222 if (Spec == TSK_ExplicitInstantiationDeclaration &&
2223 hasExplicitMemberDefinition(CXXDecl->method_begin(),
2224 CXXDecl->method_end()))
2225 return true;
2226
2227 return false;
2228}
2229
Reid Kleckner6c7b1c62016-09-13 00:01:23 +00002230void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
2231 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2232 return;
2233
2234 QualType Ty = CGM.getContext().getRecordType(RD);
2235 llvm::DIType *T = getTypeOrNull(Ty);
2236 if (T && T->isForwardDecl())
2237 completeClassData(RD);
2238}
2239
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002240llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002241 RecordDecl *RD = Ty->getDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002242 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002243 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2244 CGM.getLangOpts())) {
David Blaikie3b1cc9b2013-09-06 06:45:04 +00002245 if (!T)
Adrian Prantl6ec370a2015-09-10 18:39:45 +00002246 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00002247 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00002248 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002249
David Blaikieb2e86eb2013-08-15 20:49:17 +00002250 return CreateTypeDefinition(Ty);
2251}
2252
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002253llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
David Blaikieb2e86eb2013-08-15 20:49:17 +00002254 RecordDecl *RD = Ty->getDecl();
2255
Guy Benyei11169dd2012-12-18 14:30:41 +00002256 // Get overall information about the record type for the debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002257 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002258
2259 // Records and classes and unions can all be recursive. To handle them, we
2260 // first generate a debug descriptor for the struct as a forward declaration.
2261 // Then (if it is a definition) we go through and get debug info for all of
2262 // its members. Finally, we create a descriptor for the complete type (which
2263 // may refer to the forward decl if the struct is recursive) and replace all
2264 // uses of the forward declaration with the final definition.
Duncan P. N. Exon Smithbd210e62015-07-24 20:34:41 +00002265 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002266
Adrian Prantl5f66bae2015-02-11 17:45:15 +00002267 const RecordDecl *D = RD->getDefinition();
2268 if (!D || !D->isCompleteDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002269 return FwdDecl;
2270
David Majnemer58ed0f32016-07-17 00:39:12 +00002271 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
David Blaikieadfbf992013-08-18 16:55:33 +00002272 CollectContainingType(CXXDecl, FwdDecl);
2273
Guy Benyei11169dd2012-12-18 14:30:41 +00002274 // Push the struct on region stack.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002275 LexicalBlockStack.emplace_back(&*FwdDecl);
2276 RegionMap[Ty->getDecl()].reset(FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002277
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 // Convert all the elements.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002279 SmallVector<llvm::Metadata *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00002280 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00002281
2282 // Note: The split of CXXDecl information here is intentional, the
2283 // gdb tests will depend on a certain ordering at printout. The debug
2284 // information offsets are still correct if we merge them all together
2285 // though.
David Majnemer58ed0f32016-07-17 00:39:12 +00002286 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
Guy Benyei11169dd2012-12-18 14:30:41 +00002287 if (CXXDecl) {
2288 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
Reid Klecknerdc124992016-08-31 16:11:43 +00002289 CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002290 }
2291
Eric Christopher91a31902013-01-16 01:22:32 +00002292 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00002294 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00002295 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002296
2297 LexicalBlockStack.pop_back();
2298 RegionMap.erase(Ty->getDecl());
2299
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002300 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00002301 DBuilder.replaceArrays(FwdDecl, Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002302
Adrian Prantl5f66bae2015-02-11 17:45:15 +00002303 if (FwdDecl->isTemporary())
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00002304 FwdDecl =
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002305 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
Adrian Prantl5f66bae2015-02-11 17:45:15 +00002306
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002307 RegionMap[Ty->getDecl()].reset(FwdDecl);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00002308 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002309}
2310
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002311llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2312 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002313 // Ignore protocols.
2314 return getOrCreateType(Ty->getBaseType(), Unit);
2315}
2316
Manman Rene6be26c2016-09-13 17:25:08 +00002317llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2318 llvm::DIFile *Unit) {
2319 // Ignore protocols.
2320 SourceLocation Loc = Ty->getDecl()->getLocation();
2321
2322 // Use Typedefs to represent ObjCTypeParamType.
2323 return DBuilder.createTypedef(
2324 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2325 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
Sam McCalld27a16e2019-11-18 15:53:22 +01002326 getDeclContextDescriptor(Ty->getDecl()));
Manman Rene6be26c2016-09-13 17:25:08 +00002327}
2328
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00002329/// \return true if Getter has the default name for the property PD.
2330static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2331 const ObjCMethodDecl *Getter) {
2332 assert(PD);
2333 if (!Getter)
2334 return true;
2335
2336 assert(Getter->getDeclName().isObjCZeroArgSelector());
2337 return PD->getName() ==
Eric Christophere7b87e52014-10-26 23:40:33 +00002338 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00002339}
2340
2341/// \return true if Setter has the default name for the property PD.
2342static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2343 const ObjCMethodDecl *Setter) {
2344 assert(PD);
2345 if (!Setter)
2346 return true;
2347
2348 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00002349 return SelectorTable::constructSetterName(PD->getName()) ==
Eric Christophere7b87e52014-10-26 23:40:33 +00002350 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00002351}
2352
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002353llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2354 llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002355 ObjCInterfaceDecl *ID = Ty->getDecl();
2356 if (!ID)
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002357 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002358
Adrian Prantl50fd1a82016-04-20 23:59:32 +00002359 // Return a forward declaration if this type was imported from a clang module,
2360 // and this is not the compile unit with the implementation of the type (which
2361 // may contain hidden ivars).
2362 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2363 !ID->getImplementation())
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002364 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2365 ID->getName(),
2366 getDeclContextDescriptor(ID), Unit, 0);
2367
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 // Get overall information about the record type for the debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002369 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002370 unsigned Line = getLineNumber(ID->getLocation());
Duncan P. N. Exon Smith798d5652015-04-15 23:19:15 +00002371 auto RuntimeLang =
2372 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
Guy Benyei11169dd2012-12-18 14:30:41 +00002373
2374 // If this is just a forward declaration return a special forward-declaration
2375 // debug type since we won't be able to lay out the entire type.
2376 ObjCInterfaceDecl *Def = ID->getDefinition();
David Blaikieef8a9512014-05-05 23:23:53 +00002377 if (!Def || !Def->getImplementation()) {
Adrian Prantl42ce2d32015-10-01 16:57:02 +00002378 llvm::DIScope *Mod = getParentModuleOrNull(ID);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002379 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
Adrian Prantl42ce2d32015-10-01 16:57:02 +00002380 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2381 DefUnit, Line, RuntimeLang);
David Blaikieef8a9512014-05-05 23:23:53 +00002382 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002383 return FwdDecl;
2384 }
2385
David Blaikieef8a9512014-05-05 23:23:53 +00002386 return CreateTypeDefinition(Ty, Unit);
2387}
2388
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002389llvm::DIModule *
Adrian Prantl66689202015-09-18 23:01:45 +00002390CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
2391 bool CreateSkeletonCU) {
Adrian Prantleb66a262015-09-24 16:10:04 +00002392 // Use the Module pointer as the key into the cache. This is a
2393 // nullptr if the "Module" is a PCH, which is safe because we don't
2394 // support chained PCH debug info, so there can only be a single PCH.
2395 const Module *M = Mod.getModuleOrNull();
Adrian Prantl9e8ea352015-09-29 20:44:46 +00002396 auto ModRef = ModuleCache.find(M);
2397 if (ModRef != ModuleCache.end())
2398 return cast<llvm::DIModule>(ModRef->second);
Adrian Prantl2388ead2015-06-30 18:01:05 +00002399
2400 // Macro definitions that were defined with "-D" on the command line.
2401 SmallString<128> ConfigMacros;
2402 {
2403 llvm::raw_svector_ostream OS(ConfigMacros);
2404 const auto &PPOpts = CGM.getPreprocessorOpts();
2405 unsigned I = 0;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002406 // Translate the macro definitions back into a command line.
Adrian Prantl2388ead2015-06-30 18:01:05 +00002407 for (auto &M : PPOpts.Macros) {
2408 if (++I > 1)
2409 OS << " ";
2410 const std::string &Macro = M.first;
2411 bool Undef = M.second;
2412 OS << "\"-" << (Undef ? 'U' : 'D');
2413 for (char c : Macro)
2414 switch (c) {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002415 case '\\':
2416 OS << "\\\\";
2417 break;
2418 case '"':
2419 OS << "\\\"";
2420 break;
2421 default:
2422 OS << c;
Adrian Prantl2388ead2015-06-30 18:01:05 +00002423 }
2424 OS << '\"';
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002425 }
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002426 }
Adrian Prantl66689202015-09-18 23:01:45 +00002427
Adrian Prantl835e6632015-09-24 16:10:10 +00002428 bool IsRootModule = M ? !M->Parent : true;
Adrian Prantl7b6b9a12019-02-08 23:15:42 +00002429 // When a module name is specified as -fmodule-name, that module gets a
2430 // clang::Module object, but it won't actually be built or imported; it will
2431 // be textual.
Adrian Prantle308e422019-02-15 20:24:26 +00002432 if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
2433 assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) &&
Adrian Prantl7b6b9a12019-02-08 23:15:42 +00002434 "clang module without ASTFile must be specified by -fmodule-name");
2435
2436 if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
Adrian Prantlc96da8f2016-01-22 17:43:43 +00002437 // PCH files don't have a signature field in the control block,
2438 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002439 // We use the lower 64 bits for debug info.
2440 uint64_t Signature =
2441 Mod.getSignature()
2442 ? (uint64_t)Mod.getSignature()[1] << 32 | Mod.getSignature()[0]
2443 : ~1ULL;
Adrian Prantl66689202015-09-18 23:01:45 +00002444 llvm::DIBuilder DIB(CGM.getModule());
Amjad Aboudfa9a17e2016-12-14 20:24:40 +00002445 DIB.createCompileUnit(TheCU->getSourceLanguage(),
Scott Lindera2fbcef2018-02-26 17:32:31 +00002446 // TODO: Support "Source" from external AST providers?
Amjad Aboudfa9a17e2016-12-14 20:24:40 +00002447 DIB.createFile(Mod.getModuleName(), Mod.getPath()),
2448 TheCU->getProducer(), true, StringRef(), 0,
2449 Mod.getASTFile(), llvm::DICompileUnit::FullDebug,
2450 Signature);
Adrian Prantl66689202015-09-18 23:01:45 +00002451 DIB.finalize();
Adrian Prantl2f957ac2015-09-19 00:59:22 +00002452 }
Adrian Prantl7b6b9a12019-02-08 23:15:42 +00002453
Adrian Prantl835e6632015-09-24 16:10:10 +00002454 llvm::DIModule *Parent =
2455 IsRootModule ? nullptr
2456 : getOrCreateModuleRef(
2457 ExternalASTSource::ASTSourceDescriptor(*M->Parent),
2458 CreateSkeletonCU);
Adrian Prantleb66a262015-09-24 16:10:04 +00002459 llvm::DIModule *DIMod =
Adrian Prantl835e6632015-09-24 16:10:10 +00002460 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2461 Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot);
Adrian Prantl9e8ea352015-09-29 20:44:46 +00002462 ModuleCache[M].reset(DIMod);
Adrian Prantleb66a262015-09-24 16:10:04 +00002463 return DIMod;
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00002464}
2465
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002466llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2467 llvm::DIFile *Unit) {
David Blaikieef8a9512014-05-05 23:23:53 +00002468 ObjCInterfaceDecl *ID = Ty->getDecl();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002469 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
David Blaikieef8a9512014-05-05 23:23:53 +00002470 unsigned Line = getLineNumber(ID->getLocation());
Duncan P. N. Exon Smith798d5652015-04-15 23:19:15 +00002471 unsigned RuntimeLang = TheCU->getSourceLanguage();
Guy Benyei11169dd2012-12-18 14:30:41 +00002472
2473 // Bit size, align and offset of the type.
2474 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00002475 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002476
Leny Kholodov80c047d2016-09-06 10:48:04 +00002477 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Guy Benyei11169dd2012-12-18 14:30:41 +00002478 if (ID->getImplementation())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002479 Flags |= llvm::DINode::FlagObjcClassComplete;
Guy Benyei11169dd2012-12-18 14:30:41 +00002480
Adrian Prantlfd696112015-10-01 00:48:51 +00002481 llvm::DIScope *Mod = getParentModuleOrNull(ID);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002482 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
Adrian Prantlfd696112015-10-01 00:48:51 +00002483 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2484 nullptr, llvm::DINodeArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00002485
David Blaikieef8a9512014-05-05 23:23:53 +00002486 QualType QTy(Ty, 0);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002487 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002488
Eric Christopher35f1f9f2013-07-14 21:00:07 +00002489 // Push the struct on region stack.
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00002490 LexicalBlockStack.emplace_back(RealDecl);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002491 RegionMap[Ty->getDecl()].reset(RealDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00002492
2493 // Convert all the elements.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002494 SmallVector<llvm::Metadata *, 16> EltTys;
Guy Benyei11169dd2012-12-18 14:30:41 +00002495
2496 ObjCInterfaceDecl *SClass = ID->getSuperClass();
2497 if (SClass) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002498 llvm::DIType *SClassTy =
Eric Christophere7b87e52014-10-26 23:40:33 +00002499 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
Duncan P. N. Exon Smithb7470232015-04-15 23:48:50 +00002500 if (!SClassTy)
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002501 return nullptr;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002502
Brock Wyma3db2b102018-05-14 21:21:22 +00002503 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
Leny Kholodovdf050fd2016-09-06 17:06:14 +00002504 llvm::DINode::FlagZero);
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 EltTys.push_back(InhTag);
2506 }
2507
Eric Christopher35f1f9f2013-07-14 21:00:07 +00002508 // Create entries for all of the properties.
Nico Weber7123bca2015-12-04 19:14:14 +00002509 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002510 SourceLocation Loc = PD->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002511 llvm::DIFile *PUnit = getOrCreateFile(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 unsigned PLine = getLineNumber(Loc);
2513 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2514 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
Eric Christophere7b87e52014-10-26 23:40:33 +00002515 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2516 PD->getName(), PUnit, PLine,
2517 hasDefaultGetterName(PD, Getter) ? ""
2518 : getSelectorName(PD->getGetterName()),
2519 hasDefaultSetterName(PD, Setter) ? ""
2520 : getSelectorName(PD->getSetterName()),
2521 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 EltTys.push_back(PropertyNode);
Nico Weber7123bca2015-12-04 19:14:14 +00002523 };
2524 {
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002525 llvm::SmallPtrSet<const IdentifierInfo *, 16> PropertySet;
Nico Weberde059e12015-12-04 19:35:45 +00002526 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
Manman Renefe1bac2016-01-27 20:00:32 +00002527 for (auto *PD : ClassExt->properties()) {
Nico Weberde059e12015-12-04 19:35:45 +00002528 PropertySet.insert(PD->getIdentifier());
2529 AddProperty(PD);
2530 }
Manman Renefe1bac2016-01-27 20:00:32 +00002531 for (const auto *PD : ID->properties()) {
Nico Weber7123bca2015-12-04 19:14:14 +00002532 // Don't emit duplicate metadata for properties that were already in a
2533 // class extension.
2534 if (!PropertySet.insert(PD->getIdentifier()).second)
2535 continue;
2536 AddProperty(PD);
2537 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 }
2539
2540 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2541 unsigned FieldNo = 0;
2542 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2543 Field = Field->getNextIvar(), ++FieldNo) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002544 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
Duncan P. N. Exon Smithb7470232015-04-15 23:48:50 +00002545 if (!FieldTy)
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002546 return nullptr;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002547
Guy Benyei11169dd2012-12-18 14:30:41 +00002548 StringRef FieldName = Field->getName();
2549
2550 // Ignore unnamed fields.
2551 if (FieldName.empty())
2552 continue;
2553
2554 // Get the location for the field.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002555 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002556 unsigned FieldLine = getLineNumber(Field->getLocation());
2557 QualType FType = Field->getType();
2558 uint64_t FieldSize = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002559 uint32_t FieldAlign = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002560
2561 if (!FType->isIncompleteArrayType()) {
2562
2563 // Bit size, align and offset of the type.
2564 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00002565 ? Field->getBitWidthValue(CGM.getContext())
2566 : CGM.getContext().getTypeSize(FType);
Victor Leschuka7ece032016-10-20 00:13:19 +00002567 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 }
2569
2570 uint64_t FieldOffset;
2571 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2572 // We don't know the runtime offset of an ivar if we're using the
2573 // non-fragile ABI. For bitfields, use the bit offset into the first
2574 // byte of storage of the bitfield. For other fields, use zero.
2575 if (Field->isBitField()) {
Eric Christophere7b87e52014-10-26 23:40:33 +00002576 FieldOffset =
2577 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 FieldOffset %= CGM.getContext().getCharWidth();
2579 } else {
2580 FieldOffset = 0;
2581 }
2582 } else {
2583 FieldOffset = RL.getFieldOffset(FieldNo);
2584 }
2585
Leny Kholodov80c047d2016-09-06 10:48:04 +00002586 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002588 Flags = llvm::DINode::FlagProtected;
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002590 Flags = llvm::DINode::FlagPrivate;
Adrian Prantl21361fb2014-08-29 22:44:27 +00002591 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002592 Flags = llvm::DINode::FlagPublic;
Guy Benyei11169dd2012-12-18 14:30:41 +00002593
Craig Topper8a13c412014-05-21 05:09:00 +00002594 llvm::MDNode *PropertyNode = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002596 if (ObjCPropertyImplDecl *PImpD =
Eric Christophere7b87e52014-10-26 23:40:33 +00002597 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002598 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00002599 SourceLocation Loc = PD->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002600 llvm::DIFile *PUnit = getOrCreateFile(Loc);
Eric Christopherc0c5d462013-02-21 22:35:08 +00002601 unsigned PLine = getLineNumber(Loc);
Adrian Prantl901cc4a2019-11-08 09:24:31 -08002602 ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
2603 ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
Eric Christophere7b87e52014-10-26 23:40:33 +00002604 PropertyNode = DBuilder.createObjCProperty(
2605 PD->getName(), PUnit, PLine,
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002606 hasDefaultGetterName(PD, Getter)
2607 ? ""
2608 : getSelectorName(PD->getGetterName()),
2609 hasDefaultSetterName(PD, Setter)
2610 ? ""
2611 : getSelectorName(PD->getSetterName()),
Eric Christophere7b87e52014-10-26 23:40:33 +00002612 PD->getPropertyAttributes(),
2613 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 }
2615 }
2616 }
Eric Christophere7b87e52014-10-26 23:40:33 +00002617 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2618 FieldSize, FieldAlign, FieldOffset, Flags,
2619 FieldTy, PropertyNode);
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 EltTys.push_back(FieldTy);
2621 }
2622
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002623 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00002624 DBuilder.replaceArrays(RealDecl, Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00002625
Guy Benyei11169dd2012-12-18 14:30:41 +00002626 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00002627 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002628}
2629
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002630llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2631 llvm::DIFile *Unit) {
2632 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 int64_t Count = Ty->getNumElements();
Guy Benyei11169dd2012-12-18 14:30:41 +00002634
Sander de Smalen891af03a2018-02-03 13:55:59 +00002635 llvm::Metadata *Subscript;
2636 QualType QTy(Ty, 0);
2637 auto SizeExpr = SizeExprCache.find(QTy);
2638 if (SizeExpr != SizeExprCache.end())
2639 Subscript = DBuilder.getOrCreateSubrange(0, SizeExpr->getSecond());
2640 else
2641 Subscript = DBuilder.getOrCreateSubrange(0, Count ? Count : -1);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002642 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
Guy Benyei11169dd2012-12-18 14:30:41 +00002643
2644 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00002645 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002646
2647 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2648}
2649
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002650llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002651 uint64_t Size;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002652 uint32_t Align;
Guy Benyei11169dd2012-12-18 14:30:41 +00002653
2654 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
David Majnemer58ed0f32016-07-17 00:39:12 +00002655 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002656 Size = 0;
Victor Leschuka7ece032016-10-20 00:13:19 +00002657 Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2658 CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002659 } else if (Ty->isIncompleteArrayType()) {
2660 Size = 0;
2661 if (Ty->getElementType()->isIncompleteType())
2662 Align = 0;
2663 else
Victor Leschuka7ece032016-10-20 00:13:19 +00002664 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
David Blaikief03b2e82013-05-09 20:48:12 +00002665 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002666 Size = 0;
2667 Align = 0;
2668 } else {
2669 // Size and align of the whole array, not the element type.
2670 Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00002671 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 }
2673
2674 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
2675 // interior arrays, do we care? Why aren't nested arrays represented the
2676 // obvious/recursive way?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002677 SmallVector<llvm::Metadata *, 8> Subscripts;
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 QualType EltTy(Ty, 0);
2679 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2680 // If the number of elements is known, then count is that number. Otherwise,
2681 // it's -1. This allows us to represent a subrange with an array of 0
2682 // elements, like this:
2683 //
2684 // struct foo {
2685 // int x[0];
2686 // };
Eric Christophere7b87e52014-10-26 23:40:33 +00002687 int64_t Count = -1; // Count == -1 is an unbounded array.
David Majnemer58ed0f32016-07-17 00:39:12 +00002688 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 Count = CAT->getSize().getZExtValue();
David Blaikie87173f12016-08-22 17:49:56 +00002690 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
Eli Friedman01d6b962016-10-19 22:16:32 +00002691 if (Expr *Size = VAT->getSizeExpr()) {
Fangrui Song407659a2018-11-30 23:41:18 +00002692 Expr::EvalResult Result;
2693 if (Size->EvaluateAsInt(Result, CGM.getContext()))
2694 Count = Result.Val.getInt().getExtValue();
Eli Friedman01d6b962016-10-19 22:16:32 +00002695 }
David Blaikie87173f12016-08-22 17:49:56 +00002696 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002697
Sander de Smalen891af03a2018-02-03 13:55:59 +00002698 auto SizeNode = SizeExprCache.find(EltTy);
2699 if (SizeNode != SizeExprCache.end())
2700 Subscripts.push_back(
2701 DBuilder.getOrCreateSubrange(0, SizeNode->getSecond()));
2702 else
2703 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 EltTy = Ty->getElementType();
2705 }
2706
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002707 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
Guy Benyei11169dd2012-12-18 14:30:41 +00002708
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002709 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2710 SubscriptArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00002711}
2712
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002713llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2714 llvm::DIFile *Unit) {
Eric Christophere7b87e52014-10-26 23:40:33 +00002715 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2716 Ty->getPointeeType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002717}
2718
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002719llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2720 llvm::DIFile *Unit) {
Eric Christophere7b87e52014-10-26 23:40:33 +00002721 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2722 Ty->getPointeeType(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002723}
2724
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002725llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2726 llvm::DIFile *U) {
Leny Kholodov80c047d2016-09-06 10:48:04 +00002727 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Reid Klecknerfb727182016-06-17 22:27:59 +00002728 uint64_t Size = 0;
2729
2730 if (!Ty->isIncompleteType()) {
2731 Size = CGM.getContext().getTypeSize(Ty);
2732
2733 // Set the MS inheritance model. There is no flag for the unspecified model.
2734 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2735 switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
2736 case MSInheritanceAttr::Keyword_single_inheritance:
2737 Flags |= llvm::DINode::FlagSingleInheritance;
2738 break;
2739 case MSInheritanceAttr::Keyword_multiple_inheritance:
2740 Flags |= llvm::DINode::FlagMultipleInheritance;
2741 break;
2742 case MSInheritanceAttr::Keyword_virtual_inheritance:
2743 Flags |= llvm::DINode::FlagVirtualInheritance;
2744 break;
2745 case MSInheritanceAttr::Keyword_unspecified_inheritance:
2746 break;
Erich Keane68b09772019-09-17 14:11:51 +00002747 case MSInheritanceAttr::SpellingNotCalculated:
2748 llvm_unreachable("Spelling not yet calculated");
Reid Klecknerfb727182016-06-17 22:27:59 +00002749 }
2750 }
2751 }
2752
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002753 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
David Majnemer5fd33e02015-04-24 01:25:08 +00002754 if (Ty->isMemberDataPointerType())
David Blaikie2c705ca2013-01-19 19:20:56 +00002755 return DBuilder.createMemberPointerType(
Reid Klecknerfb727182016-06-17 22:27:59 +00002756 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2757 Flags);
Adrian Prantl0866acd2013-12-19 01:38:47 +00002758
2759 const FunctionProtoType *FPT =
Eric Christophere7b87e52014-10-26 23:40:33 +00002760 Ty->getPointeeType()->getAs<FunctionProtoType>();
2761 return DBuilder.createMemberPointerType(
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002762 getOrCreateInstanceMethodType(
2763 CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
2764 FPT, U),
Reid Klecknerfb727182016-06-17 22:27:59 +00002765 ClassType, Size, /*Align=*/0, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00002766}
2767
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002768llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
Victor Leschuk0df190372016-10-31 19:09:47 +00002769 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
2770 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002771}
2772
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002773llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00002774 return getOrCreateType(Ty->getElementType(), U);
2775}
2776
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002777llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00002778 const EnumDecl *ED = Ty->getDecl();
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002779
Guy Benyei11169dd2012-12-18 14:30:41 +00002780 uint64_t Size = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002781 uint32_t Align = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 if (!ED->getTypeForDecl()->isIncompleteType()) {
2783 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
Victor Leschuka7ece032016-10-20 00:13:19 +00002784 Align = getDeclAlignIfRequired(ED, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002785 }
2786
Brock Wyma8557ec52018-05-22 12:41:19 +00002787 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
Manman Rene0064d82013-08-29 23:19:58 +00002788
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002789 bool isImportedFromModule =
2790 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2791
Guy Benyei11169dd2012-12-18 14:30:41 +00002792 // If this is just a forward declaration, construct an appropriately
2793 // marked node and just return it.
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002794 if (isImportedFromModule || !ED->getDefinition()) {
Adrian Prantl45946062016-02-23 19:30:08 +00002795 // Note that it is possible for enums to be created as part of
2796 // their own declcontext. In this case a FwdDecl will be created
2797 // twice. This doesn't cause a problem because both FwdDecls are
2798 // entered into the ReplaceMap: finalize() will replace the first
2799 // FwdDecl with the second and then replace the second with
2800 // complete type.
Amjad Abouddc4531e2016-04-30 01:44:38 +00002801 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002802 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
Adrian Prantlff9d83c2016-02-08 17:03:28 +00002803 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2804 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
Adrian Prantla40030f2016-02-06 01:59:09 +00002805
Guy Benyei11169dd2012-12-18 14:30:41 +00002806 unsigned Line = getLineNumber(ED->getLocation());
2807 StringRef EDName = ED->getName();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002808 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
Adrian Prantl45946062016-02-23 19:30:08 +00002809 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
Brock Wyma8557ec52018-05-22 12:41:19 +00002810 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
Adrian Prantla40030f2016-02-06 01:59:09 +00002811
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002812 ReplaceMap.emplace_back(
2813 std::piecewise_construct, std::make_tuple(Ty),
2814 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
David Blaikief427b002014-05-06 03:42:01 +00002815 return RetTy;
Guy Benyei11169dd2012-12-18 14:30:41 +00002816 }
2817
David Blaikie483a9da2014-05-06 18:35:21 +00002818 return CreateTypeDefinition(Ty);
2819}
2820
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002821llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
David Blaikie483a9da2014-05-06 18:35:21 +00002822 const EnumDecl *ED = Ty->getDecl();
2823 uint64_t Size = 0;
Victor Leschuk802e4a52016-10-19 22:11:07 +00002824 uint32_t Align = 0;
David Blaikie483a9da2014-05-06 18:35:21 +00002825 if (!ED->getTypeForDecl()->isIncompleteType()) {
2826 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
Victor Leschuka7ece032016-10-20 00:13:19 +00002827 Align = getDeclAlignIfRequired(ED, CGM.getContext());
David Blaikie483a9da2014-05-06 18:35:21 +00002828 }
2829
Brock Wyma8557ec52018-05-22 12:41:19 +00002830 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
David Blaikie483a9da2014-05-06 18:35:21 +00002831
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00002832 // Create elements for each enumerator.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002833 SmallVector<llvm::Metadata *, 16> Enumerators;
Guy Benyei11169dd2012-12-18 14:30:41 +00002834 ED = ED->getDefinition();
Momchil Velikov25f6be52018-02-12 16:12:52 +00002835 bool IsSigned = ED->getIntegerType()->isSignedIntegerType();
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00002836 for (const auto *Enum : ED->enumerators()) {
Momchil Velikov25f6be52018-02-12 16:12:52 +00002837 const auto &InitVal = Enum->getInitVal();
2838 auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue();
2839 Enumerators.push_back(
2840 DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned));
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 }
2842
2843 // Return a CompositeType for the enum itself.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002844 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
Guy Benyei11169dd2012-12-18 14:30:41 +00002845
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002846 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 unsigned Line = getLineNumber(ED->getLocation());
Amjad Abouddc4531e2016-04-30 01:44:38 +00002848 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
Momchil Velikov25f6be52018-02-12 16:12:52 +00002849 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002850 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
2851 Line, Size, Align, EltArray, ClassTy,
Paul Robinsonb1ce7c82019-01-08 16:28:11 +00002852 Identifier, ED->isScoped());
Guy Benyei11169dd2012-12-18 14:30:41 +00002853}
2854
Amjad Aboud546bc112017-02-09 22:07:24 +00002855llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
2856 unsigned MType, SourceLocation LineLoc,
2857 StringRef Name, StringRef Value) {
2858 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2859 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
2860}
2861
2862llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
2863 SourceLocation LineLoc,
2864 SourceLocation FileLoc) {
2865 llvm::DIFile *FName = getOrCreateFile(FileLoc);
2866 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2867 return DBuilder.createTempMacroFile(Parent, Line, FName);
2868}
2869
David Blaikie05491062013-01-21 04:37:12 +00002870static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
2871 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00002872 do {
Adrian Prantl179af902013-09-26 21:35:50 +00002873 Qualifiers InnerQuals = T.getLocalQualifiers();
2874 // Qualifiers::operator+() doesn't like it if you add a Qualifier
2875 // that is already there.
2876 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
2877 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00002878 QualType LastT = T;
2879 switch (T->getTypeClass()) {
2880 default:
David Blaikie05491062013-01-21 04:37:12 +00002881 return C.getQualifiedType(T.getTypePtr(), Quals);
David Blaikief1b382e2014-04-06 17:14:06 +00002882 case Type::TemplateSpecialization: {
2883 const auto *Spec = cast<TemplateSpecializationType>(T);
2884 if (Spec->isTypeAlias())
2885 return C.getQualifiedType(T.getTypePtr(), Quals);
2886 T = Spec->desugar();
Eric Christophere7b87e52014-10-26 23:40:33 +00002887 break;
2888 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002889 case Type::TypeOfExpr:
2890 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2891 break;
2892 case Type::TypeOf:
2893 T = cast<TypeOfType>(T)->getUnderlyingType();
2894 break;
2895 case Type::Decltype:
2896 T = cast<DecltypeType>(T)->getUnderlyingType();
2897 break;
2898 case Type::UnaryTransform:
2899 T = cast<UnaryTransformType>(T)->getUnderlyingType();
2900 break;
2901 case Type::Attributed:
2902 T = cast<AttributedType>(T)->getEquivalentType();
2903 break;
2904 case Type::Elaborated:
2905 T = cast<ElaboratedType>(T)->getNamedType();
2906 break;
2907 case Type::Paren:
2908 T = cast<ParenType>(T)->getInnerType();
2909 break;
Leonard Chanc72aaf62019-05-07 03:20:17 +00002910 case Type::MacroQualified:
2911 T = cast<MacroQualifiedType>(T)->getUnderlyingType();
2912 break;
David Blaikie05491062013-01-21 04:37:12 +00002913 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00002914 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002915 break;
Richard Smitha0abc422017-02-22 00:13:14 +00002916 case Type::Auto:
2917 case Type::DeducedTemplateSpecialization: {
2918 QualType DT = cast<DeducedType>(T)->getDeducedType();
David Blaikie42edade2014-11-11 20:44:45 +00002919 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
David Blaikie22c460a02013-05-24 21:24:35 +00002920 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00002921 break;
2922 }
Jordan Rose303e2f12016-11-10 23:28:17 +00002923 case Type::Adjusted:
2924 case Type::Decayed:
2925 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2926 T = cast<AdjustedType>(T)->getAdjustedType();
2927 break;
2928 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002929
Guy Benyei11169dd2012-12-18 14:30:41 +00002930 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00002931 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 } while (true);
2933}
2934
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002935llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002936
2937 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002938 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002939
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002940 auto It = TypeCache.find(Ty.getAsOpaquePtr());
2941 if (It != TypeCache.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002942 // Verify that the debug info still exists.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002943 if (llvm::Metadata *V = It->second)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002944 return cast<llvm::DIType>(V);
Guy Benyei11169dd2012-12-18 14:30:41 +00002945 }
2946
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00002947 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002948}
2949
David Blaikie0e716b42014-03-03 23:48:23 +00002950void CGDebugInfo::completeTemplateDefinition(
2951 const ClassTemplateSpecializationDecl &SD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002952 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie0856f662014-03-04 22:01:08 +00002953 return;
David Blaikie1ac9c982017-04-11 21:13:37 +00002954 completeUnusedClass(SD);
2955}
David Blaikie0856f662014-03-04 22:01:08 +00002956
David Blaikie1ac9c982017-04-11 21:13:37 +00002957void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
2958 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2959 return;
2960
2961 completeClassData(&D);
David Blaikie0e716b42014-03-03 23:48:23 +00002962 // In case this type has no member function definitions being emitted, ensure
2963 // it is retained
David Blaikie1ac9c982017-04-11 21:13:37 +00002964 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
David Blaikie0e716b42014-03-03 23:48:23 +00002965}
2966
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00002967llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002968 if (Ty.isNull())
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002969 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002970
Luboš Luňák4f2104c2019-11-02 16:39:59 +01002971 llvm::TimeTraceScope TimeScope("DebugType", [&]() {
2972 std::string Name;
2973 llvm::raw_string_ostream OS(Name);
2974 Ty.print(OS, getPrintingPolicy());
2975 return Name;
2976 });
2977
Guy Benyei11169dd2012-12-18 14:30:41 +00002978 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002979 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002980
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00002981 if (auto *T = getTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002982 return T;
2983
Adrian Prantlca844182015-09-11 17:23:03 +00002984 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00002985 void *TyPtr = Ty.getAsOpaquePtr();
Adrian Prantl73409ce2013-03-11 18:33:46 +00002986
2987 // And update the type cache.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002988 TypeCache[TyPtr].reset(Res);
Guy Benyei11169dd2012-12-18 14:30:41 +00002989
Guy Benyei11169dd2012-12-18 14:30:41 +00002990 return Res;
2991}
2992
Adrian Prantl5c8bd882015-09-11 17:23:08 +00002993llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
Adrian Prantl335f5c72015-10-02 17:36:14 +00002994 // A forward declaration inside a module header does not belong to the module.
2995 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
2996 return nullptr;
Adrian Prantl85d938a2015-09-21 17:48:37 +00002997 if (DebugTypeExtRefs && D->isFromASTFile()) {
2998 // Record a reference to an imported clang module or precompiled header.
2999 auto *Reader = CGM.getContext().getExternalSource();
3000 auto Idx = D->getOwningModuleID();
3001 auto Info = Reader->getSourceDescriptor(Idx);
3002 if (Info)
3003 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3004 } else if (ClangModuleMap) {
Adrian Prantl9402cef2015-09-20 16:51:35 +00003005 // We are building a clang module or a precompiled header.
3006 //
3007 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3008 // and it wouldn't be necessary to specify the parent scope
3009 // because the type is already unique by definition (it would look
3010 // like the output of -fno-standalone-debug). On the other hand,
3011 // the parent scope helps a consumer to quickly locate the object
3012 // file where the type's definition is located, so it might be
3013 // best to make this behavior a command line or debugger tuning
3014 // option.
Richard Smith54f04402017-05-18 02:29:20 +00003015 if (Module *M = D->getOwningModule()) {
Adrian Prantlaa5d08d2016-01-22 21:14:41 +00003016 // This is a (sub-)module.
Adrian Prantl9402cef2015-09-20 16:51:35 +00003017 auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
3018 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
Adrian Prantlaa5d08d2016-01-22 21:14:41 +00003019 } else {
3020 // This the precompiled header being built.
3021 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
Adrian Prantl9402cef2015-09-20 16:51:35 +00003022 }
3023 }
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003024
Adrian Prantl9402cef2015-09-20 16:51:35 +00003025 return nullptr;
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003026}
3027
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003028llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003029 // Handle qualifiers, which recursively handles what they refer to.
3030 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00003031 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003032
Guy Benyei11169dd2012-12-18 14:30:41 +00003033 // Work out details of type.
3034 switch (Ty->getTypeClass()) {
3035#define TYPE(Class, Base)
3036#define ABSTRACT_TYPE(Class, Base)
3037#define NON_CANONICAL_TYPE(Class, Base)
3038#define DEPENDENT_TYPE(Class, Base) case Type::Class:
John McCall36b12a82019-10-02 06:35:23 +00003039#include "clang/AST/TypeNodes.inc"
Guy Benyei11169dd2012-12-18 14:30:41 +00003040 llvm_unreachable("Dependent types cannot show up in debug information");
3041
3042 case Type::ExtVector:
3043 case Type::Vector:
3044 return CreateType(cast<VectorType>(Ty), Unit);
3045 case Type::ObjCObjectPointer:
3046 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3047 case Type::ObjCObject:
3048 return CreateType(cast<ObjCObjectType>(Ty), Unit);
Manman Rene6be26c2016-09-13 17:25:08 +00003049 case Type::ObjCTypeParam:
3050 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003051 case Type::ObjCInterface:
3052 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3053 case Type::Builtin:
3054 return CreateType(cast<BuiltinType>(Ty));
3055 case Type::Complex:
3056 return CreateType(cast<ComplexType>(Ty));
3057 case Type::Pointer:
3058 return CreateType(cast<PointerType>(Ty), Unit);
3059 case Type::BlockPointer:
3060 return CreateType(cast<BlockPointerType>(Ty), Unit);
3061 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00003062 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003063 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00003064 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00003065 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00003066 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00003067 case Type::FunctionProto:
3068 case Type::FunctionNoProto:
3069 return CreateType(cast<FunctionType>(Ty), Unit);
3070 case Type::ConstantArray:
3071 case Type::VariableArray:
3072 case Type::IncompleteArray:
3073 return CreateType(cast<ArrayType>(Ty), Unit);
3074
3075 case Type::LValueReference:
3076 return CreateType(cast<LValueReferenceType>(Ty), Unit);
3077 case Type::RValueReference:
3078 return CreateType(cast<RValueReferenceType>(Ty), Unit);
3079
3080 case Type::MemberPointer:
3081 return CreateType(cast<MemberPointerType>(Ty), Unit);
3082
3083 case Type::Atomic:
3084 return CreateType(cast<AtomicType>(Ty), Unit);
3085
Xiuli Pan9c14e282016-01-09 12:53:17 +00003086 case Type::Pipe:
3087 return CreateType(cast<PipeType>(Ty), Unit);
3088
Guy Benyei11169dd2012-12-18 14:30:41 +00003089 case Type::TemplateSpecialization:
David Blaikief1b382e2014-04-06 17:14:06 +00003090 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3091
David Blaikie42edade2014-11-11 20:44:45 +00003092 case Type::Auto:
David Blaikief1b382e2014-04-06 17:14:06 +00003093 case Type::Attributed:
Jordan Rose303e2f12016-11-10 23:28:17 +00003094 case Type::Adjusted:
3095 case Type::Decayed:
Richard Smith600b5262017-01-26 20:40:47 +00003096 case Type::DeducedTemplateSpecialization:
Guy Benyei11169dd2012-12-18 14:30:41 +00003097 case Type::Elaborated:
3098 case Type::Paren:
Leonard Chanc72aaf62019-05-07 03:20:17 +00003099 case Type::MacroQualified:
Guy Benyei11169dd2012-12-18 14:30:41 +00003100 case Type::SubstTemplateTypeParm:
3101 case Type::TypeOfExpr:
3102 case Type::TypeOf:
3103 case Type::Decltype:
3104 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00003105 case Type::PackExpansion:
David Blaikie22c460a02013-05-24 21:24:35 +00003106 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00003108
David Blaikie42edade2014-11-11 20:44:45 +00003109 llvm_unreachable("type should have been unwrapped!");
Guy Benyei11169dd2012-12-18 14:30:41 +00003110}
3111
Duncan P. N. Exon Smithbd210e62015-07-24 20:34:41 +00003112llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
3113 llvm::DIFile *Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00003114 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003115
Duncan P. N. Exon Smithbd210e62015-07-24 20:34:41 +00003116 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00003117
3118 // We may have cached a forward decl when we could have created
3119 // a non-forward decl. Go ahead and create a non-forward decl
3120 // now.
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00003121 if (T && !T->isForwardDecl())
Eric Christophere7b87e52014-10-26 23:40:33 +00003122 return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00003123
3124 // Otherwise create the type.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003125 llvm::DICompositeType *Res = CreateLimitedType(Ty);
David Blaikie8d5e1282013-08-20 21:03:29 +00003126
3127 // Propagate members from the declaration to the definition
3128 // CreateType(const RecordType*) will overwrite this with the members in the
3129 // correct order if the full type is needed.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003130 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00003131
Guy Benyei11169dd2012-12-18 14:30:41 +00003132 // And update the type cache.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003133 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
Guy Benyei11169dd2012-12-18 14:30:41 +00003134 return Res;
3135}
3136
3137// TODO: Currently used for context chains when limiting debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003138llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003140
Guy Benyei11169dd2012-12-18 14:30:41 +00003141 // Get overall information about the record type for the debug info.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003142 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 unsigned Line = getLineNumber(RD->getLocation());
3144 StringRef RDName = getClassName(RD);
3145
Amjad Abouddc4531e2016-04-30 01:44:38 +00003146 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
Guy Benyei11169dd2012-12-18 14:30:41 +00003147
David Blaikied2785892013-08-18 17:36:19 +00003148 // If we ended up creating the type during the context chain construction,
3149 // just return that.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003150 auto *T = cast_or_null<llvm::DICompositeType>(
Duncan P. N. Exon Smithc7551282015-04-06 23:21:33 +00003151 getTypeOrNull(CGM.getContext().getRecordType(RD)));
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00003152 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
Eric Christophere7b87e52014-10-26 23:40:33 +00003153 return T;
David Blaikied2785892013-08-18 17:36:19 +00003154
Adrian Prantl381e7552014-02-04 21:29:50 +00003155 // If this is just a forward or incomplete declaration, construct an
3156 // appropriately marked node and just return it.
3157 const RecordDecl *D = RD->getDefinition();
3158 if (!D || !D->isCompleteDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00003159 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00003160
3161 uint64_t Size = CGM.getContext().getTypeSize(Ty);
Victor Leschuka7ece032016-10-20 00:13:19 +00003162 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003163
Brock Wyma8557ec52018-05-22 12:41:19 +00003164 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
Manman Rene0064d82013-08-29 23:19:58 +00003165
Shafik Yaghmour528f5da2019-08-27 20:17:35 +00003166 // Explicitly record the calling convention and export symbols for C++
3167 // records.
Adrian Prantl6c5f03a2018-01-05 01:13:52 +00003168 auto Flags = llvm::DINode::FlagZero;
3169 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3170 if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3171 Flags |= llvm::DINode::FlagTypePassByReference;
3172 else
3173 Flags |= llvm::DINode::FlagTypePassByValue;
Aaron Smith044326c2018-07-23 20:49:07 +00003174
Aaron Smithfa7745b2019-04-11 20:24:54 +00003175 // Record if a C++ record is non-trivial type.
3176 if (!CXXRD->isTrivial())
Aaron Smithf0d27332019-02-26 03:49:05 +00003177 Flags |= llvm::DINode::FlagNonTrivial;
Shafik Yaghmour528f5da2019-08-27 20:17:35 +00003178
3179 // Record exports it symbols to the containing structure.
3180 if (CXXRD->isAnonymousStructOrUnion())
3181 Flags |= llvm::DINode::FlagExportSymbols;
Adrian Prantl6c5f03a2018-01-05 01:13:52 +00003182 }
3183
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003184 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
Leny Kholodov80c047d2016-09-06 10:48:04 +00003185 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
Brock Wyma8557ec52018-05-22 12:41:19 +00003186 Flags, Identifier);
Guy Benyei11169dd2012-12-18 14:30:41 +00003187
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003188 // Elements of composite types usually have back to the type, creating
3189 // uniquing cycles. Distinct nodes are more efficient.
3190 switch (RealDecl->getTag()) {
3191 default:
3192 llvm_unreachable("invalid composite type tag");
3193
3194 case llvm::dwarf::DW_TAG_array_type:
3195 case llvm::dwarf::DW_TAG_enumeration_type:
3196 // Array elements and most enumeration elements don't have back references,
3197 // so they don't tend to be involved in uniquing cycles and there is some
3198 // chance of merging them when linking together two modules. Only make
3199 // them distinct if they are ODR-uniqued.
Brock Wyma8557ec52018-05-22 12:41:19 +00003200 if (Identifier.empty())
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003201 break;
Galina Kistanova0872d6c2017-06-03 06:30:46 +00003202 LLVM_FALLTHROUGH;
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003203
3204 case llvm::dwarf::DW_TAG_structure_type:
3205 case llvm::dwarf::DW_TAG_union_type:
3206 case llvm::dwarf::DW_TAG_class_type:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003207 // Immediately resolve to a distinct node.
Duncan P. N. Exon Smithf9521b02016-04-17 07:45:08 +00003208 RealDecl =
3209 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3210 break;
3211 }
3212
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003213 RegionMap[Ty->getDecl()].reset(RealDecl);
3214 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00003215
David Majnemer58ed0f32016-07-17 00:39:12 +00003216 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003217 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00003218 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00003219 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00003220}
3221
David Blaikieadfbf992013-08-18 16:55:33 +00003222void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003223 llvm::DICompositeType *RealDecl) {
David Blaikieadfbf992013-08-18 16:55:33 +00003224 // A class's primary base or the class itself contains the vtable.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003225 llvm::DICompositeType *ContainingType = nullptr;
David Blaikieadfbf992013-08-18 16:55:33 +00003226 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3227 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00003228 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00003229 while (1) {
3230 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3231 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3232 if (PBT && !BRL.isPrimaryBaseVirtual())
3233 PBase = PBT;
3234 else
3235 break;
3236 }
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003237 ContainingType = cast<llvm::DICompositeType>(
David Blaikieadfbf992013-08-18 16:55:33 +00003238 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3239 getOrCreateFile(RD->getLocation())));
3240 } else if (RD->isDynamicClass())
3241 ContainingType = RealDecl;
3242
Duncan P. N. Exon Smithc8ee63e2014-12-18 00:48:56 +00003243 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
David Blaikieadfbf992013-08-18 16:55:33 +00003244}
3245
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003246llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003247 StringRef Name, uint64_t *Offset) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003248 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003249 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
Victor Leschuka7ece032016-10-20 00:13:19 +00003250 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
Leny Kholodovdf050fd2016-09-06 17:06:14 +00003251 llvm::DIType *Ty =
3252 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3253 *Offset, llvm::DINode::FlagZero, FieldTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003254 *Offset += FieldSize;
3255 return Ty;
3256}
3257
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003258void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
Duncan P. N. Exon Smith8e47da42015-04-21 20:07:29 +00003259 StringRef &Name,
3260 StringRef &LinkageName,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003261 llvm::DIScope *&FDContext,
3262 llvm::DINodeArray &TParamsArray,
Leny Kholodov80c047d2016-09-06 10:48:04 +00003263 llvm::DINode::DIFlags &Flags) {
David Majnemer58ed0f32016-07-17 00:39:12 +00003264 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Frederic Riss9db79f12014-11-18 03:40:46 +00003265 Name = getFunctionName(FD);
3266 // Use mangled name as linkage name for C/C++ functions.
3267 if (FD->hasPrototype()) {
3268 LinkageName = CGM.getMangledName(GD);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003269 Flags |= llvm::DINode::FlagPrototyped;
Frederic Riss9db79f12014-11-18 03:40:46 +00003270 }
3271 // No need to replicate the linkage name if it isn't different from the
3272 // subprogram name, no need to have it at all unless coverage is enabled or
Dehao Chenb3a70de2017-01-19 00:44:21 +00003273 // debug is set to more than just line tables or extra debug info is needed.
Benjamin Kramer8c305922016-02-02 11:06:51 +00003274 if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
3275 !CGM.getCodeGenOpts().EmitGcovNotes &&
Dehao Chenb3a70de2017-01-19 00:44:21 +00003276 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
Benjamin Kramer8c305922016-02-02 11:06:51 +00003277 DebugKind <= codegenoptions::DebugLineTablesOnly))
Frederic Riss9db79f12014-11-18 03:40:46 +00003278 LinkageName = StringRef();
3279
Benjamin Kramer8c305922016-02-02 11:06:51 +00003280 if (DebugKind >= codegenoptions::LimitedDebugInfo) {
Frederic Riss9db79f12014-11-18 03:40:46 +00003281 if (const NamespaceDecl *NSDecl =
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003282 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
Adrian Prantlddb8e062017-05-12 16:23:53 +00003283 FDContext = getOrCreateNamespace(NSDecl);
Frederic Riss9db79f12014-11-18 03:40:46 +00003284 else if (const RecordDecl *RDecl =
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003285 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003286 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3287 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3288 }
Adrian Prantlfd5ac8a2016-08-17 16:20:32 +00003289 // Check if it is a noreturn-marked function
3290 if (FD->isNoReturn())
3291 Flags |= llvm::DINode::FlagNoReturn;
Frederic Riss9db79f12014-11-18 03:40:46 +00003292 // Collect template parameters.
3293 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3294 }
3295}
3296
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003297void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
Frederic Riss9db79f12014-11-18 03:40:46 +00003298 unsigned &LineNo, QualType &T,
3299 StringRef &Name, StringRef &LinkageName,
Matthew Voss20165362018-10-03 18:45:04 +00003300 llvm::MDTuple *&TemplateParameters,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003301 llvm::DIScope *&VDContext) {
Frederic Riss9db79f12014-11-18 03:40:46 +00003302 Unit = getOrCreateFile(VD->getLocation());
3303 LineNo = getLineNumber(VD->getLocation());
3304
3305 setLocation(VD->getLocation());
3306
3307 T = VD->getType();
3308 if (T->isIncompleteArrayType()) {
3309 // CodeGen turns int[] into int[1] so we'll do the same here.
3310 llvm::APInt ConstVal(32, 1);
3311 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3312
Richard Smith772e2662019-10-04 01:25:59 +00003313 T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
3314 ArrayType::Normal, 0);
Frederic Riss9db79f12014-11-18 03:40:46 +00003315 }
3316
3317 Name = VD->getName();
3318 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3319 !isa<ObjCMethodDecl>(VD->getDeclContext()))
3320 LinkageName = CGM.getMangledName(VD);
3321 if (LinkageName == Name)
3322 LinkageName = StringRef();
3323
Matthew Voss20165362018-10-03 18:45:04 +00003324 if (isa<VarTemplateSpecializationDecl>(VD)) {
3325 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3326 TemplateParameters = parameterNodes.get();
3327 } else {
3328 TemplateParameters = nullptr;
3329 }
3330
Frederic Riss9db79f12014-11-18 03:40:46 +00003331 // Since we emit declarations (DW_AT_members) for static members, place the
3332 // definition of those static members in the namespace they were declared in
3333 // in the source code (the lexical decl context).
3334 // FIXME: Generalize this for even non-member global variables where the
3335 // declaration and definition may have different lexical decl contexts, once
3336 // we have support for emitting declarations of (non-member) global variables.
Saleem Abdulrasoolcd187f02015-02-28 00:13:13 +00003337 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
3338 : VD->getDeclContext();
3339 // When a record type contains an in-line initialization of a static data
3340 // member, and the record type is marked as __declspec(dllexport), an implicit
3341 // definition of the member will be created in the record context. DWARF
3342 // doesn't seem to have a nice way to describe this in a form that consumers
3343 // are likely to understand, so fake the "normal" situation of a definition
3344 // outside the class by putting it in the global scope.
3345 if (DC->isRecord())
3346 DC = CGM.getContext().getTranslationUnitDecl();
Adrian Prantl5c8bd882015-09-11 17:23:08 +00003347
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003348 llvm::DIScope *Mod = getParentModuleOrNull(VD);
3349 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
Frederic Riss9db79f12014-11-18 03:40:46 +00003350}
3351
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003352llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3353 bool Stub) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003354 llvm::DINodeArray TParamsArray;
Frederic Rissd253ed62014-11-18 03:40:51 +00003355 StringRef Name, LinkageName;
Leny Kholodov80c047d2016-09-06 10:48:04 +00003356 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Paul Robinsoncda54212018-11-19 18:29:28 +00003357 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003358 SourceLocation Loc = GD.getDecl()->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003359 llvm::DIFile *Unit = getOrCreateFile(Loc);
3360 llvm::DIScope *DContext = Unit;
Frederic Rissd253ed62014-11-18 03:40:51 +00003361 unsigned Line = getLineNumber(Loc);
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003362 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3363 Flags);
Simon Pilgrimcfee2ef2019-10-16 10:38:49 +00003364 auto *FD = cast<FunctionDecl>(GD.getDecl());
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003365
Frederic Rissd253ed62014-11-18 03:40:51 +00003366 // Build function type.
3367 SmallVector<QualType, 16> ArgTypes;
Simon Pilgrimcfee2ef2019-10-16 10:38:49 +00003368 for (const ParmVarDecl *Parm : FD->parameters())
3369 ArgTypes.push_back(Parm->getType());
3370
Reid Klecknerf00f8032016-06-08 20:41:54 +00003371 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3372 QualType FnType = CGM.getContext().getFunctionType(
3373 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
Paul Robinsoncda54212018-11-19 18:29:28 +00003374 if (!FD->isExternallyVisible())
3375 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3376 if (CGM.getLangOpts().Optimize)
3377 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3378
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003379 if (Stub) {
Vedant Kumar5931b4e2018-10-05 20:37:17 +00003380 Flags |= getCallSiteRelatedAttrs();
Paul Robinsoncda54212018-11-19 18:29:28 +00003381 SPFlags |= llvm::DISubprogram::SPFlagDefinition;
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003382 return DBuilder.createFunction(
3383 DContext, Name, LinkageName, Unit, Line,
Paul Robinsoncda54212018-11-19 18:29:28 +00003384 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003385 TParamsArray.get(), getFunctionDeclaration(FD));
3386 }
3387
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003388 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
Duncan P. N. Exon Smithebad0aa2015-04-07 16:50:49 +00003389 DContext, Name, LinkageName, Unit, Line,
Paul Robinsoncda54212018-11-19 18:29:28 +00003390 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
Duncan P. N. Exon Smithebad0aa2015-04-07 16:50:49 +00003391 TParamsArray.get(), getFunctionDeclaration(FD));
George Burgess IV00f70bd2018-03-01 05:43:23 +00003392 const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00003393 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3394 std::make_tuple(CanonDecl),
3395 std::make_tuple(SP));
Frederic Rissd253ed62014-11-18 03:40:51 +00003396 return SP;
3397}
3398
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003399llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003400 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3401}
3402
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003403llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003404 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3405}
3406
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003407llvm::DIGlobalVariable *
Frederic Rissd253ed62014-11-18 03:40:51 +00003408CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3409 QualType T;
3410 StringRef Name, LinkageName;
3411 SourceLocation Loc = VD->getLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003412 llvm::DIFile *Unit = getOrCreateFile(Loc);
3413 llvm::DIScope *DContext = Unit;
Frederic Rissd253ed62014-11-18 03:40:51 +00003414 unsigned Line = getLineNumber(Loc);
Matthew Voss20165362018-10-03 18:45:04 +00003415 llvm::MDTuple *TemplateParameters = nullptr;
Frederic Rissd253ed62014-11-18 03:40:51 +00003416
Matthew Voss20165362018-10-03 18:45:04 +00003417 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3418 DContext);
Victor Leschuka7ece032016-10-20 00:13:19 +00003419 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00003420 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3421 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
Matthew Voss20165362018-10-03 18:45:04 +00003422 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003423 FwdDeclReplaceMap.emplace_back(
3424 std::piecewise_construct,
3425 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3426 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
Frederic Rissd253ed62014-11-18 03:40:51 +00003427 return GV;
3428}
3429
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003430llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
David Blaikiebd483762013-05-20 04:58:53 +00003431 // We only need a declaration (not a definition) of the type - so use whatever
3432 // we would otherwise do to get a type for a pointee. (forward declarations in
3433 // limited debug info, full definitions (if the type definition is available)
3434 // in unlimited debug info)
David Majnemer58ed0f32016-07-17 00:39:12 +00003435 if (const auto *TD = dyn_cast<TypeDecl>(D))
David Blaikie6b7d060c2013-08-12 23:14:36 +00003436 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00003437 getOrCreateFile(TD->getLocation()));
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003438 auto I = DeclCache.find(D->getCanonicalDecl());
Frederic Rissd253ed62014-11-18 03:40:51 +00003439
Adrian Prantl5f4740d2016-12-20 02:10:02 +00003440 if (I != DeclCache.end()) {
3441 auto N = I->second;
3442 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3443 return GVE->getVariable();
3444 return dyn_cast_or_null<llvm::DINode>(N);
3445 }
Frederic Rissd253ed62014-11-18 03:40:51 +00003446
3447 // No definition for now. Emit a forward definition that might be
3448 // merged with a potential upcoming definition.
David Majnemer58ed0f32016-07-17 00:39:12 +00003449 if (const auto *FD = dyn_cast<FunctionDecl>(D))
Frederic Rissd253ed62014-11-18 03:40:51 +00003450 return getFunctionForwardDeclaration(FD);
3451 else if (const auto *VD = dyn_cast<VarDecl>(D))
3452 return getGlobalVariableForwardDeclaration(VD);
3453
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00003454 return nullptr;
David Blaikiebd483762013-05-20 04:58:53 +00003455}
3456
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003457llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003458 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003459 return nullptr;
David Blaikie18cfbc52013-06-22 00:09:36 +00003460
David Majnemer58ed0f32016-07-17 00:39:12 +00003461 const auto *FD = dyn_cast<FunctionDecl>(D);
Eric Christophere7b87e52014-10-26 23:40:33 +00003462 if (!FD)
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003463 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003464
3465 // Setup context.
Adrian Prantl6ec370a2015-09-10 18:39:45 +00003466 auto *S = getDeclContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003467
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003468 auto MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00003469 if (MI == SPCache.end()) {
David Majnemer58ed0f32016-07-17 00:39:12 +00003470 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
Duncan P. N. Exon Smithc09c5482015-04-20 21:17:26 +00003471 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003472 cast<llvm::DICompositeType>(S));
David Blaikiefd07c602013-08-09 17:20:05 +00003473 }
3474 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003475 if (MI != SPCache.end()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003476 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
Duncan P. N. Exon Smith87afdeb2015-04-14 03:24:14 +00003477 if (SP && !SP->isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00003478 return SP;
3479 }
3480
Aaron Ballman86c93902014-03-06 23:45:36 +00003481 for (auto NextFD : FD->redecls()) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003482 auto MI = SPCache.find(NextFD->getCanonicalDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00003483 if (MI != SPCache.end()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003484 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
Duncan P. N. Exon Smith87afdeb2015-04-14 03:24:14 +00003485 if (SP && !SP->isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00003486 return SP;
3487 }
3488 }
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003489 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003490}
3491
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003492llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
3493 const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
3494 llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
3495 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3496 return nullptr;
3497
Adrian Prantle0cabe22019-11-21 09:56:01 -08003498 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
3499 if (!OMD)
3500 return nullptr;
3501
3502 if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003503 return nullptr;
3504
3505 // Starting with DWARF V5 method declarations are emitted as children of
3506 // the interface type.
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003507 auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
3508 if (!ID)
3509 ID = OMD->getClassInterface();
3510 if (!ID)
3511 return nullptr;
3512 QualType QTy(ID->getTypeForDecl(), 0);
3513 auto It = TypeCache.find(QTy.getAsOpaquePtr());
3514 if (It == TypeCache.end())
3515 return nullptr;
3516 auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
3517 llvm::DISubprogram *FD = DBuilder.createFunction(
3518 InterfaceType, getObjCMethodName(OMD), StringRef(),
3519 InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
3520 DBuilder.finalizeSubprogram(FD);
Adrian Prantle0cabe22019-11-21 09:56:01 -08003521 ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003522 return FD;
3523}
3524
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003525// getOrCreateFunctionType - Construct type. If it is a c++ method, include
Guy Benyei11169dd2012-12-18 14:30:41 +00003526// implicit parameter "this".
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003527llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
Duncan P. N. Exon Smith4078ad42015-04-16 16:36:45 +00003528 QualType FnType,
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003529 llvm::DIFile *F) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003530 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003531 // Create fake but valid subroutine type. Otherwise -verify would fail, and
3532 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
Eric Christopher28a6db52015-10-15 06:56:08 +00003533 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00003534
David Majnemer58ed0f32016-07-17 00:39:12 +00003535 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00003536 return getOrCreateMethodType(Method, F);
Reid Klecknerf00f8032016-06-08 20:41:54 +00003537
3538 const auto *FTy = FnType->getAs<FunctionType>();
3539 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3540
David Majnemer58ed0f32016-07-17 00:39:12 +00003541 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003542 // Add "self" and "_cmd"
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003543 SmallVector<llvm::Metadata *, 16> Elts;
Guy Benyei11169dd2012-12-18 14:30:41 +00003544
3545 // First element is always return type. For 'void' functions it is NULL.
Alp Toker314cc812014-01-25 16:55:45 +00003546 QualType ResultTy = OMethod->getReturnType();
Adrian Prantl5f360102013-05-22 21:37:49 +00003547
3548 // Replace the instancetype keyword with the actual type.
3549 if (ResultTy == CGM.getContext().getObjCInstanceType())
3550 ResultTy = CGM.getContext().getPointerType(
Eric Christophere7b87e52014-10-26 23:40:33 +00003551 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
Adrian Prantl5f360102013-05-22 21:37:49 +00003552
Adrian Prantl7bec9032013-05-10 21:08:31 +00003553 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00003554 // "self" pointer is always first argument.
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003555 QualType SelfDeclTy;
3556 if (auto *SelfDecl = OMethod->getSelfDecl())
3557 SelfDeclTy = SelfDecl->getType();
3558 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3559 if (FPT->getNumParams() > 1)
3560 SelfDeclTy = FPT->getParamType(0);
3561 if (!SelfDeclTy.isNull())
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003562 Elts.push_back(
3563 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003564 // "_cmd" pointer is always second argument.
Duncan P. N. Exon Smith0b6c3692015-04-20 18:51:48 +00003565 Elts.push_back(DBuilder.createArtificialType(
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003566 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003567 // Get rest of the arguments.
David Majnemer59f77922016-06-24 04:05:48 +00003568 for (const auto *PI : OMethod->parameters())
Aaron Ballman43b68be2014-03-07 17:50:17 +00003569 Elts.push_back(getOrCreateType(PI->getType(), F));
Frederic Riss787d9d62014-08-12 04:42:23 +00003570 // Variadic methods need a special marker at the end of the type list.
3571 if (OMethod->isVariadic())
3572 Elts.push_back(DBuilder.createUnspecifiedParameter());
Guy Benyei11169dd2012-12-18 14:30:41 +00003573
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003574 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
Leny Kholodov80c047d2016-09-06 10:48:04 +00003575 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3576 getDwarfCC(CC));
Guy Benyei11169dd2012-12-18 14:30:41 +00003577 }
Adrian Prantld45ba252014-02-25 19:38:11 +00003578
Adrian Prantl800faef2014-02-25 23:42:18 +00003579 // Handle variadic function types; they need an additional
3580 // unspecified parameter.
David Majnemer58ed0f32016-07-17 00:39:12 +00003581 if (const auto *FD = dyn_cast<FunctionDecl>(D))
Adrian Prantld45ba252014-02-25 19:38:11 +00003582 if (FD->isVariadic()) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003583 SmallVector<llvm::Metadata *, 16> EltTys;
Adrian Prantld45ba252014-02-25 19:38:11 +00003584 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
David Majnemer58ed0f32016-07-17 00:39:12 +00003585 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3586 for (QualType ParamType : FPT->param_types())
3587 EltTys.push_back(getOrCreateType(ParamType, F));
Adrian Prantld45ba252014-02-25 19:38:11 +00003588 EltTys.push_back(DBuilder.createUnspecifiedParameter());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003589 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
Leny Kholodov80c047d2016-09-06 10:48:04 +00003590 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3591 getDwarfCC(CC));
Adrian Prantld45ba252014-02-25 19:38:11 +00003592 }
3593
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003594 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00003595}
3596
Eric Christophere7b87e52014-10-26 23:40:33 +00003597void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3598 SourceLocation ScopeLoc, QualType FnType,
Brock Wyma94ece8f2018-04-16 16:53:57 +00003599 llvm::Function *Fn, bool CurFuncIsThunk,
3600 CGBuilderTy &Builder) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003601
3602 StringRef Name;
3603 StringRef LinkageName;
3604
3605 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3606
3607 const Decl *D = GD.getDecl();
Craig Topper8a13c412014-05-21 05:09:00 +00003608 bool HasDecl = (D != nullptr);
Eric Christopher885c41b2014-04-01 22:25:28 +00003609
Leny Kholodov80c047d2016-09-06 10:48:04 +00003610 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Paul Robinsoncda54212018-11-19 18:29:28 +00003611 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003612 llvm::DIFile *Unit = getOrCreateFile(Loc);
3613 llvm::DIScope *FDContext = Unit;
3614 llvm::DINodeArray TParamsArray;
Guy Benyei11169dd2012-12-18 14:30:41 +00003615 if (!HasDecl) {
3616 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00003617 LinkageName = Fn->getName();
David Majnemer58ed0f32016-07-17 00:39:12 +00003618 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Duncan P. N. Exon Smitha7fbcbf2015-04-20 22:09:57 +00003619 // If there is a subprogram for this function available then use it.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003620 auto FI = SPCache.find(FD->getCanonicalDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00003621 if (FI != SPCache.end()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003622 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
Duncan P. N. Exon Smith87afdeb2015-04-14 03:24:14 +00003623 if (SP && SP->isDefinition()) {
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003624 LexicalBlockStack.emplace_back(SP);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003625 RegionMap[D].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00003626 return;
3627 }
3628 }
Frederic Riss9db79f12014-11-18 03:40:46 +00003629 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3630 TParamsArray, Flags);
David Majnemer58ed0f32016-07-17 00:39:12 +00003631 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003632 Name = getObjCMethodName(OMD);
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003633 Flags |= llvm::DINode::FlagPrototyped;
Reid Kleckner105c5652019-04-24 22:45:44 +00003634 } else if (isa<VarDecl>(D) &&
3635 GD.getDynamicInitKind() != DynamicInitKind::NoStub) {
3636 // This is a global initializer or atexit destructor for a global variable.
3637 Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
3638 Fn);
Guy Benyei11169dd2012-12-18 14:30:41 +00003639 } else {
3640 // Use llvm function name.
3641 Name = Fn->getName();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003642 Flags |= llvm::DINode::FlagPrototyped;
Guy Benyei11169dd2012-12-18 14:30:41 +00003643 }
David Majnemer58ed0f32016-07-17 00:39:12 +00003644 if (Name.startswith("\01"))
Guy Benyei11169dd2012-12-18 14:30:41 +00003645 Name = Name.substr(1);
3646
Alexandre Ganeacaf31662019-11-15 16:21:17 -05003647 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003648 Flags |= llvm::DINode::FlagArtificial;
Adrian Prantldb763572016-11-09 21:43:51 +00003649 // Artificial functions should not silently reuse CurLoc.
3650 CurLoc = SourceLocation();
Adrian Prantl42d71b92014-04-10 23:21:53 +00003651 }
Brock Wyma94ece8f2018-04-16 16:53:57 +00003652
3653 if (CurFuncIsThunk)
3654 Flags |= llvm::DINode::FlagThunk;
3655
Paul Robinsoncda54212018-11-19 18:29:28 +00003656 if (Fn->hasLocalLinkage())
3657 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3658 if (CGM.getLangOpts().Optimize)
3659 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3660
Vedant Kumar5931b4e2018-10-05 20:37:17 +00003661 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
Paul Robinsoncda54212018-11-19 18:29:28 +00003662 llvm::DISubprogram::DISPFlags SPFlagsForDef =
3663 SPFlags | llvm::DISubprogram::SPFlagDefinition;
Vedant Kumar5931b4e2018-10-05 20:37:17 +00003664
Adrian Prantl42d71b92014-04-10 23:21:53 +00003665 unsigned LineNo = getLineNumber(Loc);
3666 unsigned ScopeLine = getLineNumber(ScopeLoc);
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003667 llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
3668 llvm::DISubprogram *Decl = nullptr;
3669 if (D)
3670 Decl = isa<ObjCMethodDecl>(D)
3671 ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
3672 : getFunctionDeclaration(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003673
Eric Christopher8018e412014-03-27 18:50:35 +00003674 // FIXME: The function declaration we're constructing here is mostly reusing
3675 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3676 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3677 // all subprograms instead of the actual context since subprogram definitions
3678 // are emitted as CU level entities by the backend.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003679 llvm::DISubprogram *SP = DBuilder.createFunction(
Adrian Prantl901cc4a2019-11-08 09:24:31 -08003680 FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
3681 FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl);
Peter Collingbourne0900fe02015-11-05 22:04:14 +00003682 Fn->setSubprogram(SP);
Frederic Rissb1ab28c2014-11-05 19:19:04 +00003683 // We might get here with a VarDecl in the case we're generating
3684 // code for the initialization of globals. Do not record these decls
3685 // as they will overwrite the actual VarDecl Decl in the cache.
3686 if (HasDecl && isa<FunctionDecl>(D))
David Majnemer58ed0f32016-07-17 00:39:12 +00003687 DeclCache[D->getCanonicalDecl()].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00003688
Adrian Prantlbebb8932014-03-21 21:01:58 +00003689 // Push the function onto the lexical block stack.
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003690 LexicalBlockStack.emplace_back(SP);
Adrian Prantlbebb8932014-03-21 21:01:58 +00003691
Guy Benyei11169dd2012-12-18 14:30:41 +00003692 if (HasDecl)
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003693 RegionMap[D].reset(SP);
Guy Benyei11169dd2012-12-18 14:30:41 +00003694}
3695
Vedant Kumar8bd52142019-07-11 19:28:07 +00003696void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3697 QualType FnType, llvm::Function *Fn) {
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003698 StringRef Name;
3699 StringRef LinkageName;
3700
3701 const Decl *D = GD.getDecl();
3702 if (!D)
Vedant Kumar8bd52142019-07-11 19:28:07 +00003703 return;
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003704
Luboš Luňák4f2104c2019-11-02 16:39:59 +01003705 llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
3706 std::string Name;
3707 llvm::raw_string_ostream OS(Name);
3708 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3709 ND->getNameForDiagnostic(OS, getPrintingPolicy(),
3710 /*Qualified=*/true);
3711 return Name;
3712 });
3713
Leny Kholodov80c047d2016-09-06 10:48:04 +00003714 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003715 llvm::DIFile *Unit = getOrCreateFile(Loc);
Vedant Kumar8bd52142019-07-11 19:28:07 +00003716 bool IsDeclForCallSite = Fn ? true : false;
Djordje Todorovic0f651682019-06-27 06:44:44 +00003717 llvm::DIScope *FDContext =
3718 IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003719 llvm::DINodeArray TParamsArray;
3720 if (isa<FunctionDecl>(D)) {
3721 // If there is a DISubprogram for this function available then use it.
3722 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3723 TParamsArray, Flags);
David Majnemer58ed0f32016-07-17 00:39:12 +00003724 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003725 Name = getObjCMethodName(OMD);
3726 Flags |= llvm::DINode::FlagPrototyped;
3727 } else {
3728 llvm_unreachable("not a function or ObjC method");
3729 }
3730 if (!Name.empty() && Name[0] == '\01')
3731 Name = Name.substr(1);
3732
3733 if (D->isImplicit()) {
3734 Flags |= llvm::DINode::FlagArtificial;
3735 // Artificial functions without a location should not silently reuse CurLoc.
3736 if (Loc.isInvalid())
3737 CurLoc = SourceLocation();
3738 }
3739 unsigned LineNo = getLineNumber(Loc);
3740 unsigned ScopeLine = 0;
Paul Robinsoncda54212018-11-19 18:29:28 +00003741 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3742 if (CGM.getLangOpts().Optimize)
3743 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003744
Djordje Todorovic0f651682019-06-27 06:44:44 +00003745 llvm::DISubprogram *SP = DBuilder.createFunction(
Adrian Prantle76bda52016-04-15 15:55:45 +00003746 FDContext, Name, LinkageName, Unit, LineNo,
Paul Robinsoncda54212018-11-19 18:29:28 +00003747 getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
Djordje Todorovic0f651682019-06-27 06:44:44 +00003748 TParamsArray.get(), getFunctionDeclaration(D));
Vedant Kumar8bd52142019-07-11 19:28:07 +00003749
3750 if (IsDeclForCallSite)
3751 Fn->setSubprogram(SP);
3752
Djordje Todorovic0f651682019-06-27 06:44:44 +00003753 DBuilder.retainType(SP);
3754}
3755
3756void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
3757 QualType CalleeType,
3758 const FunctionDecl *CalleeDecl) {
Vedant Kumar568db782019-11-13 18:19:32 -08003759 if (!CallOrInvoke)
Djordje Todorovic0f651682019-06-27 06:44:44 +00003760 return;
Djordje Todorovic0f651682019-06-27 06:44:44 +00003761 auto *Func = CallOrInvoke->getCalledFunction();
3762 if (!Func)
3763 return;
Vedant Kumar568db782019-11-13 18:19:32 -08003764 if (Func->getSubprogram())
3765 return;
3766
3767 // Do not emit a declaration subprogram for a builtin or if call site info
3768 // isn't required. Also, elide declarations for functions with reserved names,
3769 // as call site-related features aren't interesting in this case (& also, the
3770 // compiler may emit calls to these functions without debug locations, which
3771 // makes the verifier complain).
3772 if (CalleeDecl->getBuiltinID() != 0 ||
3773 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
3774 return;
3775 if (const auto *Id = CalleeDecl->getIdentifier())
3776 if (Id->isReservedName())
3777 return;
Djordje Todorovic0f651682019-06-27 06:44:44 +00003778
3779 // If there is no DISubprogram attached to the function being called,
3780 // create the one describing the function in order to have complete
3781 // call site debug info.
Vedant Kumar8bd52142019-07-11 19:28:07 +00003782 if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
3783 EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
Adrian Prantl748a6cd2015-09-08 20:41:52 +00003784}
3785
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003786void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
3787 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3788 // If there is a subprogram for this function available then use it.
3789 auto FI = SPCache.find(FD->getCanonicalDecl());
3790 llvm::DISubprogram *SP = nullptr;
3791 if (FI != SPCache.end())
3792 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
Adrian Prantl8040a212017-08-23 21:24:12 +00003793 if (!SP || !SP->isDefinition())
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003794 SP = getFunctionStub(GD);
3795 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3796 LexicalBlockStack.emplace_back(SP);
3797 setInlinedAt(Builder.getCurrentDebugLocation());
3798 EmitLocation(Builder, FD->getLocation());
3799}
3800
3801void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
3802 assert(CurInlinedAt && "unbalanced inline scope stack");
Keno Fischer41d4b4e2017-06-01 21:14:03 +00003803 EmitFunctionEnd(Builder, nullptr);
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003804 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
3805}
3806
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003807void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003808 // Update our current location
3809 setLocation(Loc);
3810
Adrian Prantl42ab39f2018-11-09 21:17:38 +00003811 if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
Eric Christophere7b87e52014-10-26 23:40:33 +00003812 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00003813
Adrian Prantle83b1302014-01-07 22:05:52 +00003814 llvm::MDNode *Scope = LexicalBlockStack.back();
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003815 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3816 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt));
Guy Benyei11169dd2012-12-18 14:30:41 +00003817}
3818
Guy Benyei11169dd2012-12-18 14:30:41 +00003819void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
Duncan P. N. Exon Smitha66e3052014-12-09 19:22:40 +00003820 llvm::MDNode *Back = nullptr;
3821 if (!LexicalBlockStack.empty())
3822 Back = LexicalBlockStack.back().get();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003823 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003824 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00003825 getColumnNumber(CurLoc)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003826}
3827
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00003828void CGDebugInfo::AppendAddressSpaceXDeref(
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00003829 unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const {
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00003830 Optional<unsigned> DWARFAddressSpace =
3831 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
3832 if (!DWARFAddressSpace)
3833 return;
3834
3835 Expr.push_back(llvm::dwarf::DW_OP_constu);
3836 Expr.push_back(DWARFAddressSpace.getValue());
3837 Expr.push_back(llvm::dwarf::DW_OP_swap);
3838 Expr.push_back(llvm::dwarf::DW_OP_xderef);
3839}
3840
Eric Christopher0fdcb312013-05-16 00:52:20 +00003841void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
3842 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003843 // Set our current location.
3844 setLocation(Loc);
3845
Guy Benyei11169dd2012-12-18 14:30:41 +00003846 // Emit a line table change for the current location inside the new scope.
Adrian Prantlb7acfc02017-02-27 21:30:05 +00003847 Builder.SetCurrentDebugLocation(
3848 llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc),
3849 LexicalBlockStack.back(), CurInlinedAt));
David Blaikie60a877b2014-10-22 19:34:33 +00003850
Benjamin Kramer8c305922016-02-02 11:06:51 +00003851 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie60a877b2014-10-22 19:34:33 +00003852 return;
3853
3854 // Create a new lexical block and push it on the stack.
3855 CreateLexicalBlock(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003856}
3857
Eric Christopher0fdcb312013-05-16 00:52:20 +00003858void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
3859 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003860 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3861
3862 // Provide an entry in the line table for the end of the block.
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003863 EmitLocation(Builder, Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003864
Benjamin Kramer8c305922016-02-02 11:06:51 +00003865 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
David Blaikie60a877b2014-10-22 19:34:33 +00003866 return;
3867
Guy Benyei11169dd2012-12-18 14:30:41 +00003868 LexicalBlockStack.pop_back();
3869}
3870
Keno Fischer41d4b4e2017-06-01 21:14:03 +00003871void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003872 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3873 unsigned RCount = FnBeginRegionCount.back();
3874 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
3875
3876 // Pop all regions for this function.
David Blaikie60a877b2014-10-22 19:34:33 +00003877 while (LexicalBlockStack.size() != RCount) {
3878 // Provide an entry in the line table for the end of the block.
Calixte Denizetfcd661d2018-09-24 18:24:18 +00003879 EmitLocation(Builder, CurLoc);
David Blaikie60a877b2014-10-22 19:34:33 +00003880 LexicalBlockStack.pop_back();
3881 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003882 FnBeginRegionCount.pop_back();
Keno Fischer41d4b4e2017-06-01 21:14:03 +00003883
3884 if (Fn && Fn->getSubprogram())
3885 DBuilder.finalizeSubprogram(Fn->getSubprogram());
Guy Benyei11169dd2012-12-18 14:30:41 +00003886}
3887
Adrian Prantl05a623e2018-09-10 16:14:28 +00003888CGDebugInfo::BlockByRefType
3889CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
3890 uint64_t *XOffset) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00003891 SmallVector<llvm::Metadata *, 5> EltTys;
Guy Benyei11169dd2012-12-18 14:30:41 +00003892 QualType FType;
3893 uint64_t FieldSize, FieldOffset;
Victor Leschuk802e4a52016-10-19 22:11:07 +00003894 uint32_t FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00003895
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003896 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003897 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00003898
3899 FieldOffset = 0;
3900 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3901 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
3902 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
3903 FType = CGM.getContext().IntTy;
3904 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
3905 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
3906
3907 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
3908 if (HasCopyAndDispose) {
3909 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Eric Christophere7b87e52014-10-26 23:40:33 +00003910 EltTys.push_back(
3911 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
3912 EltTys.push_back(
3913 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00003914 }
3915 bool HasByrefExtendedLayout;
3916 Qualifiers::ObjCLifetime Lifetime;
Eric Christophere7b87e52014-10-26 23:40:33 +00003917 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
3918 HasByrefExtendedLayout) &&
3919 HasByrefExtendedLayout) {
Adrian Prantlead2ba42013-07-23 00:12:14 +00003920 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Eric Christophere7b87e52014-10-26 23:40:33 +00003921 EltTys.push_back(
3922 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00003923 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00003924
Guy Benyei11169dd2012-12-18 14:30:41 +00003925 CharUnits Align = CGM.getContext().getDeclAlign(VD);
3926 if (Align > CGM.getContext().toCharUnitsFromBits(
Eric Christophere7b87e52014-10-26 23:40:33 +00003927 CGM.getTarget().getPointerAlign(0))) {
3928 CharUnits FieldOffsetInBytes =
3929 CGM.getContext().toCharUnitsFromBits(FieldOffset);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003930 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
Eric Christophere7b87e52014-10-26 23:40:33 +00003931 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00003932
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 if (NumPaddingBytes.isPositive()) {
3934 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
Richard Smith772e2662019-10-04 01:25:59 +00003935 FType = CGM.getContext().getConstantArrayType(
3936 CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00003937 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
3938 }
3939 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00003940
Guy Benyei11169dd2012-12-18 14:30:41 +00003941 FType = Type;
Adrian Prantl05a623e2018-09-10 16:14:28 +00003942 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00003943 FieldSize = CGM.getContext().getTypeSize(FType);
3944 FieldAlign = CGM.getContext().toBits(Align);
3945
Eric Christopherb2a008c2013-05-16 00:45:12 +00003946 *XOffset = FieldOffset;
Adrian Prantl05a623e2018-09-10 16:14:28 +00003947 llvm::DIType *FieldTy = DBuilder.createMemberType(
3948 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
3949 llvm::DINode::FlagZero, WrappedTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003950 EltTys.push_back(FieldTy);
3951 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00003952
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003953 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
Adrian Prantl05a623e2018-09-10 16:14:28 +00003954 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
3955 llvm::DINode::FlagZero, nullptr, Elements),
3956 WrappedTy};
Guy Benyei11169dd2012-12-18 14:30:41 +00003957}
3958
Sander de Smalen891af03a2018-02-03 13:55:59 +00003959llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
3960 llvm::Value *Storage,
3961 llvm::Optional<unsigned> ArgNo,
Amy Huang7fac5c82019-06-20 17:15:21 +00003962 CGBuilderTy &Builder,
3963 const bool UsePointerValue) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00003964 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003965 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Paul Robinsonafd2dde2016-06-16 00:42:36 +00003966 if (VD->hasAttr<NoDebugAttr>())
Sander de Smalen891af03a2018-02-03 13:55:59 +00003967 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003968
David Blaikie7fceebf2013-08-19 03:37:48 +00003969 bool Unwritten =
3970 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
3971 cast<Decl>(VD->getDeclContext())->isImplicit());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003972 llvm::DIFile *Unit = nullptr;
David Blaikie7fceebf2013-08-19 03:37:48 +00003973 if (!Unwritten)
3974 Unit = getOrCreateFile(VD->getLocation());
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003975 llvm::DIType *Ty;
Guy Benyei11169dd2012-12-18 14:30:41 +00003976 uint64_t XOffset = 0;
3977 if (VD->hasAttr<BlocksAttr>())
Adrian Prantl05a623e2018-09-10 16:14:28 +00003978 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00003979 else
Guy Benyei11169dd2012-12-18 14:30:41 +00003980 Ty = getOrCreateType(VD->getType(), Unit);
3981
3982 // If there is no debug info for this type then do not emit debug info
3983 // for this variable.
3984 if (!Ty)
Sander de Smalen891af03a2018-02-03 13:55:59 +00003985 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003986
Guy Benyei11169dd2012-12-18 14:30:41 +00003987 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00003988 unsigned Line = 0;
3989 unsigned Column = 0;
3990 if (!Unwritten) {
3991 Line = getLineNumber(VD->getLocation());
3992 Column = getColumnNumber(VD->getLocation());
3993 }
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00003994 SmallVector<int64_t, 13> Expr;
Leny Kholodov80c047d2016-09-06 10:48:04 +00003995 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
Guy Benyei11169dd2012-12-18 14:30:41 +00003996 if (VD->isImplicit())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00003997 Flags |= llvm::DINode::FlagArtificial;
Victor Leschuka7ece032016-10-20 00:13:19 +00003998
3999 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4000
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004001 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
4002 AppendAddressSpaceXDeref(AddressSpace, Expr);
4003
Alexey Bataev24f710182017-06-09 13:55:08 +00004004 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4005 // object pointer flag.
Alexey Bataev56223232017-06-09 13:40:18 +00004006 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4007 if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
4008 IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4009 Flags |= llvm::DINode::FlagObjectPointer;
4010 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004011
Adrian Prantlc3782a12017-04-18 01:22:01 +00004012 // Note: Older versions of clang used to emit byval references with an extra
4013 // DW_OP_deref, because they referenced the IR arg directly instead of
4014 // referencing an alloca. Newer versions of LLVM don't treat allocas
4015 // differently from other function arguments when used in a dbg.declare.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004016 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
Guy Benyei11169dd2012-12-18 14:30:41 +00004017 StringRef Name = VD->getName();
4018 if (!Name.empty()) {
4019 if (VD->hasAttr<BlocksAttr>()) {
Adrian Prantlc3782a12017-04-18 01:22:01 +00004020 // Here, we need an offset *into* the alloca.
Guy Benyei11169dd2012-12-18 14:30:41 +00004021 CharUnits offset = CharUnits::fromQuantity(32);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004022 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004023 // offset of __forwarding field
4024 offset = CGM.getContext().toCharUnitsFromBits(
Eric Christophere7b87e52014-10-26 23:40:33 +00004025 CGM.getTarget().getPointerWidth(0));
Adrian Prantl7c6f9442015-01-19 17:51:58 +00004026 Expr.push_back(offset.getQuantity());
4027 Expr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004028 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004029 // offset of x field
4030 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
Adrian Prantl7c6f9442015-01-19 17:51:58 +00004031 Expr.push_back(offset.getQuantity());
Adrian Prantlc3782a12017-04-18 01:22:01 +00004032 }
David Majnemer58ed0f32016-07-17 00:39:12 +00004033 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
Adrian Prantl0d820892015-04-29 15:05:50 +00004034 // If VD is an anonymous union then Storage represents value for
4035 // all union fields.
George Burgess IV00f70bd2018-03-01 05:43:23 +00004036 const RecordDecl *RD = RT->getDecl();
Adrian Prantl0d820892015-04-29 15:05:50 +00004037 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Adrian Prantl00820ab2015-04-29 16:52:31 +00004038 // GDB has trouble finding local variables in anonymous unions, so we emit
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004039 // artificial local variables for each of the members.
Adrian Prantl00820ab2015-04-29 16:52:31 +00004040 //
4041 // FIXME: Remove this code as soon as GDB supports this.
4042 // The debug info verifier in LLVM operates based on the assumption that a
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004043 // variable has the same size as its storage and we had to disable the
4044 // check for artificial variables.
Adrian Prantl0d820892015-04-29 15:05:50 +00004045 for (const auto *Field : RD->fields()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004046 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
Adrian Prantl0d820892015-04-29 15:05:50 +00004047 StringRef FieldName = Field->getName();
4048
4049 // Ignore unnamed fields. Do not ignore unnamed records.
4050 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4051 continue;
4052
4053 // Use VarDecl's Tag, Scope and Line number.
Victor Leschuka7ece032016-10-20 00:13:19 +00004054 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004055 auto *D = DBuilder.createAutoVariable(
4056 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
Victor Leschuka7ece032016-10-20 00:13:19 +00004057 Flags | llvm::DINode::FlagArtificial, FieldAlign);
Adrian Prantl0d820892015-04-29 15:05:50 +00004058
4059 // Insert an llvm.dbg.declare into the current block.
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004060 DBuilder.insertDeclare(
4061 Storage, D, DBuilder.createExpression(Expr),
4062 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4063 Builder.GetInsertBlock());
Adrian Prantl0d820892015-04-29 15:05:50 +00004064 }
Adrian Prantl0d820892015-04-29 15:05:50 +00004065 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004066 }
David Blaikiea76a7c92013-01-05 05:58:35 +00004067
Amy Huang7fac5c82019-06-20 17:15:21 +00004068 // Clang stores the sret pointer provided by the caller in a static alloca.
4069 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4070 // the address of the variable.
4071 if (UsePointerValue) {
4072 assert(std::find(Expr.begin(), Expr.end(), llvm::dwarf::DW_OP_deref) ==
4073 Expr.end() &&
4074 "Debug info already contains DW_OP_deref.");
4075 Expr.push_back(llvm::dwarf::DW_OP_deref);
4076 }
4077
David Blaikiea76a7c92013-01-05 05:58:35 +00004078 // Create the descriptor for the variable.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004079 auto *D = ArgNo ? DBuilder.createParameterVariable(
4080 Scope, Name, *ArgNo, Unit, Line, Ty,
4081 CGM.getLangOpts().Optimize, Flags)
4082 : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4083 CGM.getLangOpts().Optimize,
4084 Flags, Align);
David Blaikiea76a7c92013-01-05 05:58:35 +00004085
4086 // Insert an llvm.dbg.declare into the current block.
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004087 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004088 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004089 Builder.GetInsertBlock());
Sander de Smalen891af03a2018-02-03 13:55:59 +00004090
4091 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00004092}
4093
Sander de Smalen891af03a2018-02-03 13:55:59 +00004094llvm::DILocalVariable *
4095CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
Amy Huang7fac5c82019-06-20 17:15:21 +00004096 CGBuilderTy &Builder,
4097 const bool UsePointerValue) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004098 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Amy Huang7fac5c82019-06-20 17:15:21 +00004099 return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue);
Guy Benyei11169dd2012-12-18 14:30:41 +00004100}
4101
Hsiangkai Wang35751492019-01-24 05:34:29 +00004102void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
4103 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
4104 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4105
4106 if (D->hasAttr<NoDebugAttr>())
4107 return;
4108
4109 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4110 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4111
4112 // Get location information.
4113 unsigned Line = getLineNumber(D->getLocation());
4114 unsigned Column = getColumnNumber(D->getLocation());
4115
4116 StringRef Name = D->getName();
4117
4118 // Create the descriptor for the label.
4119 auto *L =
4120 DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
4121
4122 // Insert an llvm.dbg.label into the current block.
4123 DBuilder.insertLabel(L,
4124 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4125 Builder.GetInsertBlock());
4126}
4127
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004128llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
4129 llvm::DIType *Ty) {
4130 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
Eric Christophere7b87e52014-10-26 23:40:33 +00004131 if (CachedTy)
4132 Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00004133 return DBuilder.createObjectPointerType(Ty);
4134}
4135
Eric Christophere7b87e52014-10-26 23:40:33 +00004136void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
4137 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
Adrian Prantl88eec392014-11-21 00:35:25 +00004138 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004139 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00004140 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00004141
Craig Topper8a13c412014-05-21 05:09:00 +00004142 if (Builder.GetInsertBlock() == nullptr)
Guy Benyei11169dd2012-12-18 14:30:41 +00004143 return;
Paul Robinsonafd2dde2016-06-16 00:42:36 +00004144 if (VD->hasAttr<NoDebugAttr>())
4145 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004146
Guy Benyei11169dd2012-12-18 14:30:41 +00004147 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00004148
Guy Benyei11169dd2012-12-18 14:30:41 +00004149 uint64_t XOffset = 0;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004150 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4151 llvm::DIType *Ty;
Guy Benyei11169dd2012-12-18 14:30:41 +00004152 if (isByRef)
Adrian Prantl05a623e2018-09-10 16:14:28 +00004153 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00004154 else
Guy Benyei11169dd2012-12-18 14:30:41 +00004155 Ty = getOrCreateType(VD->getType(), Unit);
4156
4157 // Self is passed along as an implicit non-arg variable in a
4158 // block. Mark it as the object pointer.
Alexey Bataev56223232017-06-09 13:40:18 +00004159 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
4160 if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4161 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00004162
4163 // Get location information.
4164 unsigned Line = getLineNumber(VD->getLocation());
4165 unsigned Column = getColumnNumber(VD->getLocation());
4166
4167 const llvm::DataLayout &target = CGM.getDataLayout();
4168
4169 CharUnits offset = CharUnits::fromQuantity(
Eric Christophere7b87e52014-10-26 23:40:33 +00004170 target.getStructLayout(blockInfo.StructureType)
Guy Benyei11169dd2012-12-18 14:30:41 +00004171 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
4172
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004173 SmallVector<int64_t, 9> addr;
Adrian Prantlc3782a12017-04-18 01:22:01 +00004174 addr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004175 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004176 addr.push_back(offset.getQuantity());
Guy Benyei11169dd2012-12-18 14:30:41 +00004177 if (isByRef) {
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004178 addr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004179 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004180 // offset of __forwarding field
Eric Christophere7b87e52014-10-26 23:40:33 +00004181 offset =
4182 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004183 addr.push_back(offset.getQuantity());
4184 addr.push_back(llvm::dwarf::DW_OP_deref);
Florian Hahn3dbcced2017-06-13 18:06:15 +00004185 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 // offset of x field
4187 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
Duncan P. N. Exon Smithf3dc4292014-10-01 20:26:18 +00004188 addr.push_back(offset.getQuantity());
Guy Benyei11169dd2012-12-18 14:30:41 +00004189 }
4190
4191 // Create the descriptor for the variable.
Victor Leschuka7ece032016-10-20 00:13:19 +00004192 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004193 auto *D = DBuilder.createAutoVariable(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004194 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
Victor Leschuka7ece032016-10-20 00:13:19 +00004195 Line, Ty, false, llvm::DINode::FlagZero, Align);
Adrian Prantl0f6df002013-03-29 19:20:35 +00004196
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 // Insert an llvm.dbg.declare into the current block.
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004198 auto DL =
4199 llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt);
Adrian Prantlc3782a12017-04-18 01:22:01 +00004200 auto *Expr = DBuilder.createExpression(addr);
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004201 if (InsertPoint)
Adrian Prantlc3782a12017-04-18 01:22:01 +00004202 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004203 else
Adrian Prantlc3782a12017-04-18 01:22:01 +00004204 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
Guy Benyei11169dd2012-12-18 14:30:41 +00004205}
4206
Guy Benyei11169dd2012-12-18 14:30:41 +00004207void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
4208 unsigned ArgNo,
4209 CGBuilderTy &Builder) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004210 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004211 EmitDeclare(VD, AI, ArgNo, Builder);
Guy Benyei11169dd2012-12-18 14:30:41 +00004212}
4213
4214namespace {
Eric Christophere7b87e52014-10-26 23:40:33 +00004215struct BlockLayoutChunk {
4216 uint64_t OffsetInBits;
4217 const BlockDecl::Capture *Capture;
4218};
4219bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
4220 return l.OffsetInBits < r.OffsetInBits;
4221}
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004222} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004223
Scott Linder58df0e42018-08-08 15:56:12 +00004224void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
4225 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
4226 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
4227 SmallVectorImpl<llvm::Metadata *> &Fields) {
4228 // Blocks in OpenCL have unique constraints which make the standard fields
4229 // redundant while requiring size and align fields for enqueue_kernel. See
4230 // initializeForBlockHeader in CGBlocks.cpp
4231 if (CGM.getLangOpts().OpenCL) {
4232 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
4233 BlockLayout.getElementOffsetInBits(0),
4234 Unit, Unit));
4235 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
4236 BlockLayout.getElementOffsetInBits(1),
4237 Unit, Unit));
4238 } else {
4239 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
4240 BlockLayout.getElementOffsetInBits(0),
4241 Unit, Unit));
4242 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
4243 BlockLayout.getElementOffsetInBits(1),
4244 Unit, Unit));
4245 Fields.push_back(
4246 createFieldType("__reserved", Context.IntTy, Loc, AS_public,
4247 BlockLayout.getElementOffsetInBits(2), Unit, Unit));
4248 auto *FnTy = Block.getBlockExpr()->getFunctionType();
4249 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
4250 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
4251 BlockLayout.getElementOffsetInBits(3),
4252 Unit, Unit));
4253 Fields.push_back(createFieldType(
4254 "__descriptor",
4255 Context.getPointerType(Block.NeedsCopyDispose
4256 ? Context.getBlockDescriptorExtendedType()
4257 : Context.getBlockDescriptorType()),
4258 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
4259 }
4260}
4261
Guy Benyei11169dd2012-12-18 14:30:41 +00004262void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl356347b2017-10-26 20:08:52 +00004263 StringRef Name,
David Blaikie77bbb5f2014-08-08 17:10:14 +00004264 unsigned ArgNo,
Adrian Prantl356347b2017-10-26 20:08:52 +00004265 llvm::AllocaInst *Alloca,
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 CGBuilderTy &Builder) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004267 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 ASTContext &C = CGM.getContext();
4269 const BlockDecl *blockDecl = block.getBlockDecl();
4270
4271 // Collect some general information about the block's location.
4272 SourceLocation loc = blockDecl->getCaretLocation();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004273 llvm::DIFile *tunit = getOrCreateFile(loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004274 unsigned line = getLineNumber(loc);
4275 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00004276
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 // Build the debug-info type for the block literal.
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004278 getDeclContextDescriptor(blockDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00004279
4280 const llvm::StructLayout *blockLayout =
Eric Christophere7b87e52014-10-26 23:40:33 +00004281 CGM.getDataLayout().getStructLayout(block.StructureType);
Guy Benyei11169dd2012-12-18 14:30:41 +00004282
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004283 SmallVector<llvm::Metadata *, 16> fields;
Scott Linder58df0e42018-08-08 15:56:12 +00004284 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4285 fields);
Guy Benyei11169dd2012-12-18 14:30:41 +00004286
4287 // We want to sort the captures by offset, not because DWARF
4288 // requires this, but because we're paranoid about debuggers.
4289 SmallVector<BlockLayoutChunk, 8> chunks;
4290
4291 // 'this' capture.
4292 if (blockDecl->capturesCXXThis()) {
4293 BlockLayoutChunk chunk;
4294 chunk.OffsetInBits =
Eric Christophere7b87e52014-10-26 23:40:33 +00004295 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
Craig Topper8a13c412014-05-21 05:09:00 +00004296 chunk.Capture = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004297 chunks.push_back(chunk);
4298 }
4299
4300 // Variable captures.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004301 for (const auto &capture : blockDecl->captures()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004302 const VarDecl *variable = capture.getVariable();
4303 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4304
4305 // Ignore constant captures.
4306 if (captureInfo.isConstant())
4307 continue;
4308
4309 BlockLayoutChunk chunk;
4310 chunk.OffsetInBits =
Eric Christophere7b87e52014-10-26 23:40:33 +00004311 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 chunk.Capture = &capture;
4313 chunks.push_back(chunk);
4314 }
4315
4316 // Sort by offset.
4317 llvm::array_pod_sort(chunks.begin(), chunks.end());
4318
David Majnemer58ed0f32016-07-17 00:39:12 +00004319 for (const BlockLayoutChunk &Chunk : chunks) {
4320 uint64_t offsetInBits = Chunk.OffsetInBits;
4321 const BlockDecl::Capture *capture = Chunk.Capture;
Guy Benyei11169dd2012-12-18 14:30:41 +00004322
4323 // If we have a null capture, this must be the C++ 'this' capture.
4324 if (!capture) {
Adrian Prantl2526fca2016-04-18 23:48:16 +00004325 QualType type;
4326 if (auto *Method =
4327 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
Brian Gesiak5488ab42019-01-11 01:54:53 +00004328 type = Method->getThisType();
Adrian Prantl2526fca2016-04-18 23:48:16 +00004329 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4330 type = QualType(RDecl->getTypeForDecl(), 0);
4331 else
4332 llvm_unreachable("unexpected block declcontext");
Guy Benyei11169dd2012-12-18 14:30:41 +00004333
David Majnemerb4b671e2016-06-30 03:01:59 +00004334 fields.push_back(createFieldType("this", type, loc, AS_public,
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 offsetInBits, tunit, tunit));
4336 continue;
4337 }
4338
4339 const VarDecl *variable = capture->getVariable();
4340 StringRef name = variable->getName();
4341
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004342 llvm::DIType *fieldType;
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 if (capture->isByRef()) {
David Majnemer34b57492014-07-30 01:30:47 +00004344 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
Victor Leschuka7ece032016-10-20 00:13:19 +00004345 auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004346 // FIXME: This recomputes the layout of the BlockByRefWrapper.
Guy Benyei11169dd2012-12-18 14:30:41 +00004347 uint64_t xoffset;
Adrian Prantl05a623e2018-09-10 16:14:28 +00004348 fieldType =
4349 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
David Majnemer34b57492014-07-30 01:30:47 +00004350 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
Victor Leschuka7ece032016-10-20 00:13:19 +00004351 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4352 PtrInfo.Width, Align, offsetInBits,
4353 llvm::DINode::FlagZero, fieldType);
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 } else {
Victor Leschuka7ece032016-10-20 00:13:19 +00004355 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
David Majnemerb4b671e2016-06-30 03:01:59 +00004356 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
Victor Leschuka7ece032016-10-20 00:13:19 +00004357 offsetInBits, Align, tunit, tunit);
Guy Benyei11169dd2012-12-18 14:30:41 +00004358 }
4359 fields.push_back(fieldType);
4360 }
4361
4362 SmallString<36> typeName;
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004363 llvm::raw_svector_ostream(typeName)
4364 << "__block_literal_" << CGM.getUniqueBlockCount();
Guy Benyei11169dd2012-12-18 14:30:41 +00004365
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004366 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
Guy Benyei11169dd2012-12-18 14:30:41 +00004367
Leny Kholodovdf050fd2016-09-06 17:06:14 +00004368 llvm::DIType *type =
4369 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
Victor Leschuka7ece032016-10-20 00:13:19 +00004370 CGM.getContext().toBits(block.BlockSize), 0,
Leny Kholodovdf050fd2016-09-06 17:06:14 +00004371 llvm::DINode::FlagZero, nullptr, fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00004372 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4373
4374 // Get overall information about the block.
Leny Kholodov80c047d2016-09-06 10:48:04 +00004375 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004376 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
Guy Benyei11169dd2012-12-18 14:30:41 +00004377
4378 // Create the descriptor for the parameter.
Duncan P. N. Exon Smithe4306542015-07-31 17:56:14 +00004379 auto *debugVar = DBuilder.createParameterVariable(
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004380 scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
Adrian Prantl51936dd2013-03-14 17:53:33 +00004381
Adrian Prantl616bef42013-03-14 21:52:59 +00004382 // Insert an llvm.dbg.declare into the current block.
Adrian Prantl356347b2017-10-26 20:08:52 +00004383 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
Adrian Prantlb7acfc02017-02-27 21:30:05 +00004384 llvm::DebugLoc::get(line, column, scope, CurInlinedAt),
Duncan P. N. Exon Smithfe88b482015-04-15 21:18:30 +00004385 Builder.GetInsertBlock());
Guy Benyei11169dd2012-12-18 14:30:41 +00004386}
4387
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004388llvm::DIDerivedType *
David Blaikie6943dea2013-08-20 01:28:15 +00004389CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004390 if (!D || !D->isStaticDataMember())
Duncan P. N. Exon Smithc09c5482015-04-20 21:17:26 +00004391 return nullptr;
Saleem Abdulrasoolcd187f02015-02-28 00:13:13 +00004392
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004393 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
David Blaikie6943dea2013-08-20 01:28:15 +00004394 if (MI != StaticDataMemberCache.end()) {
4395 assert(MI->second && "Static data member declaration should still exist");
Duncan P. N. Exon Smithac346ba2015-07-24 18:05:58 +00004396 return MI->second;
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00004397 }
David Blaikiece763042013-08-20 21:49:21 +00004398
4399 // If the member wasn't found in the cache, lazily construct and add it to the
4400 // type (used when a limited form of the type is emitted).
Adrian Prantl21361fb2014-08-29 22:44:27 +00004401 auto DC = D->getDeclContext();
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004402 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
Adrian Prantl21361fb2014-08-29 22:44:27 +00004403 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
David Blaikie6943dea2013-08-20 01:28:15 +00004404}
4405
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004406llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004407 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4408 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004409 llvm::DIGlobalVariableExpression *GVE = nullptr;
Eric Christophercab9fae2014-04-10 05:20:00 +00004410
4411 for (const auto *Field : RD->fields()) {
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004412 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
Eric Christophercab9fae2014-04-10 05:20:00 +00004413 StringRef FieldName = Field->getName();
4414
4415 // Ignore unnamed fields, but recurse into anonymous records.
4416 if (FieldName.empty()) {
David Majnemer58ed0f32016-07-17 00:39:12 +00004417 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004418 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004419 Var, DContext);
Eric Christophercab9fae2014-04-10 05:20:00 +00004420 continue;
4421 }
4422 // Use VarDecl's Tag, Scope and Line number.
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004423 GVE = DBuilder.createGlobalVariableExpression(
4424 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
4425 Var->hasLocalLinkage());
4426 Var->addDebugInfo(GVE);
Eric Christophercab9fae2014-04-10 05:20:00 +00004427 }
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004428 return GVE;
Eric Christophercab9fae2014-04-10 05:20:00 +00004429}
4430
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004431void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 const VarDecl *D) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004433 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Paul Robinsonb17327d2016-04-27 17:37:12 +00004434 if (D->hasAttr<NoDebugAttr>())
4435 return;
Adrian Prantl338ef7a2016-11-09 00:42:03 +00004436
Luboš Luňák4f2104c2019-11-02 16:39:59 +01004437 llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
4438 std::string Name;
4439 llvm::raw_string_ostream OS(Name);
4440 D->getNameForDiagnostic(OS, getPrintingPolicy(),
4441 /*Qualified=*/true);
4442 return Name;
4443 });
4444
Adrian Prantl338ef7a2016-11-09 00:42:03 +00004445 // If we already created a DIGlobalVariable for this declaration, just attach
4446 // it to the llvm::GlobalVariable.
4447 auto Cached = DeclCache.find(D->getCanonicalDecl());
4448 if (Cached != DeclCache.end())
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004449 return Var->addDebugInfo(
4450 cast<llvm::DIGlobalVariableExpression>(Cached->second));
Adrian Prantl338ef7a2016-11-09 00:42:03 +00004451
Guy Benyei11169dd2012-12-18 14:30:41 +00004452 // Create global variable debug descriptor.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004453 llvm::DIFile *Unit = nullptr;
4454 llvm::DIScope *DContext = nullptr;
Frederic Riss9db79f12014-11-18 03:40:46 +00004455 unsigned LineNo;
4456 StringRef DeclName, LinkageName;
4457 QualType T;
Matthew Voss20165362018-10-03 18:45:04 +00004458 llvm::MDTuple *TemplateParameters = nullptr;
4459 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
4460 TemplateParameters, DContext);
Eric Christophercab9fae2014-04-10 05:20:00 +00004461
4462 // Attempt to store one global variable for the declaration - even if we
4463 // emit a lot of fields.
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004464 llvm::DIGlobalVariableExpression *GVE = nullptr;
Eric Christophercab9fae2014-04-10 05:20:00 +00004465
4466 // If this is an anonymous union then we'll want to emit a global
4467 // variable for each member of the anonymous union so that it's possible
4468 // to find the name of any field in the union.
4469 if (T->isUnionType() && DeclName.empty()) {
Reid Kleckner43ecd7c2015-11-20 17:41:12 +00004470 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
Eric Christophere7b87e52014-10-26 23:40:33 +00004471 assert(RD->isAnonymousStructOrUnion() &&
4472 "unnamed non-anonymous struct or union?");
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004473 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
Eric Christophercab9fae2014-04-10 05:20:00 +00004474 } else {
Victor Leschuka7ece032016-10-20 00:13:19 +00004475 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004476
4477 SmallVector<int64_t, 4> Expr;
4478 unsigned AddressSpace =
4479 CGM.getContext().getTargetAddressSpace(D->getType());
Alexey Bataev1a9e05d2019-02-05 19:45:57 +00004480 if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
4481 if (D->hasAttr<CUDASharedAttr>())
4482 AddressSpace =
4483 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
4484 else if (D->hasAttr<CUDAConstantAttr>())
4485 AddressSpace =
4486 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4487 }
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004488 AppendAddressSpaceXDeref(AddressSpace, Expr);
4489
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004490 GVE = DBuilder.createGlobalVariableExpression(
Eric Christophercab9fae2014-04-10 05:20:00 +00004491 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Konstantin Zhuravlyov2b4917f2017-03-09 18:06:23 +00004492 Var->hasLocalLinkage(),
4493 Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
Matthew Voss20165362018-10-03 18:45:04 +00004494 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
4495 Align);
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004496 Var->addDebugInfo(GVE);
Eric Christophercab9fae2014-04-10 05:20:00 +00004497 }
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004498 DeclCache[D->getCanonicalDecl()].reset(GVE);
Guy Benyei11169dd2012-12-18 14:30:41 +00004499}
4500
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00004501void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004502 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
Paul Robinsonb17327d2016-04-27 17:37:12 +00004503 if (VD->hasAttr<NoDebugAttr>())
4504 return;
Luboš Luňák4f2104c2019-11-02 16:39:59 +01004505 llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
4506 std::string Name;
4507 llvm::raw_string_ostream OS(Name);
4508 VD->getNameForDiagnostic(OS, getPrintingPolicy(),
4509 /*Qualified=*/true);
4510 return Name;
4511 });
4512
Victor Leschuka7ece032016-10-20 00:13:19 +00004513 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004514 // Create the descriptor for the variable.
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004515 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004516 StringRef Name = VD->getName();
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004517 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
Amy Huang63305c82019-05-22 15:48:59 +00004518
David Majnemer58ed0f32016-07-17 00:39:12 +00004519 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
4520 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00004521 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004522
Yuanfang Chen48c6fad2019-09-04 20:58:15 +00004523 if (CGM.getCodeGenOpts().EmitCodeView) {
4524 // If CodeView, emit enums as global variables, unless they are defined
4525 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
4526 // enums in classes, and because it is difficult to attach this scope
4527 // information to the global variable.
4528 if (isa<RecordDecl>(ED->getDeclContext()))
4529 return;
4530 } else {
4531 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
4532 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
4533 // first time `ZERO` is referenced in a function.
4534 llvm::DIType *EDTy =
4535 getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
4536 assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
4537 (void)EDTy;
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004538 return;
Yuanfang Chen48c6fad2019-09-04 20:58:15 +00004539 }
Amy Huang63305c82019-05-22 15:48:59 +00004540 }
4541
Amy Huang325003b2019-05-29 21:45:34 +00004542 llvm::DIScope *DContext = nullptr;
4543
4544 // Do not emit separate definitions for function local consts.
David Blaikiea15565562014-04-04 20:56:17 +00004545 if (isa<FunctionDecl>(VD->getDeclContext()))
4546 return;
Amy Huang325003b2019-05-29 21:45:34 +00004547
4548 // Emit definition for static members in CodeView.
David Blaikiebb113912014-04-05 07:23:17 +00004549 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Amy Huangdd3a9ca2019-05-30 22:04:11 +00004550 auto *VarD = dyn_cast<VarDecl>(VD);
4551 if (VarD && VarD->isStaticDataMember()) {
David Blaikieaf080852014-11-21 00:20:58 +00004552 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004553 getDeclContextDescriptor(VarD);
David Blaikie423eb5a2014-11-19 19:42:40 +00004554 // Ensure that the type is retained even though it's otherwise unreferenced.
Duncan P. N. Exon Smith383f8412016-04-23 21:08:27 +00004555 //
4556 // FIXME: This is probably unnecessary, since Ty should reference RD
4557 // through its scope.
David Blaikie423eb5a2014-11-19 19:42:40 +00004558 RetainedTypes.push_back(
David Blaikieaf080852014-11-21 00:20:58 +00004559 CGM.getContext().getRecordType(RD).getAsOpaquePtr());
David Blaikie423eb5a2014-11-19 19:42:40 +00004560
Amy Huang325003b2019-05-29 21:45:34 +00004561 if (!CGM.getCodeGenOpts().EmitCodeView)
4562 return;
4563
4564 // Use the global scope for static members.
4565 DContext = getContextDescriptor(
4566 cast<Decl>(CGM.getContext().getTranslationUnitDecl()), TheCU);
4567 } else {
4568 DContext = getDeclContextDescriptor(VD);
4569 }
David Blaikieaf080852014-11-21 00:20:58 +00004570
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004571 auto &GV = DeclCache[VD];
4572 if (GV)
David Blaikiebb113912014-04-05 07:23:17 +00004573 return;
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00004574 llvm::DIExpression *InitExpr = nullptr;
Peter Collingbourneb7013632016-12-16 22:10:52 +00004575 if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
4576 // FIXME: Add a representation for integer constants wider than 64 bits.
4577 if (Init.isInt())
4578 InitExpr =
4579 DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
4580 else if (Init.isFloat())
4581 InitExpr = DBuilder.createConstantValueExpression(
4582 Init.getFloat().bitcastToAPInt().getZExtValue());
4583 }
Matthew Voss20165362018-10-03 18:45:04 +00004584
4585 llvm::MDTuple *TemplateParameters = nullptr;
4586
4587 if (isa<VarTemplateSpecializationDecl>(VD))
4588 if (VarD) {
4589 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
4590 TemplateParameters = parameterNodes.get();
4591 }
4592
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004593 GV.reset(DBuilder.createGlobalVariableExpression(
David Blaikie506a7452014-04-05 07:46:57 +00004594 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
Victor Leschuka7ece032016-10-20 00:13:19 +00004595 true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
Matthew Voss20165362018-10-03 18:45:04 +00004596 TemplateParameters, Align));
David Blaikiebd483762013-05-20 04:58:53 +00004597}
4598
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004599llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
David Blaikiebd483762013-05-20 04:58:53 +00004600 if (!LexicalBlockStack.empty())
Duncan P. N. Exon Smithfc8d9d92015-04-20 18:32:15 +00004601 return LexicalBlockStack.back();
Adrian Prantl5c8bd882015-09-11 17:23:08 +00004602 llvm::DIScope *Mod = getParentModuleOrNull(D);
4603 return getContextDescriptor(D, Mod ? Mod : TheCU);
Guy Benyei11169dd2012-12-18 14:30:41 +00004604}
4605
David Blaikie9f88fe82013-04-22 06:13:21 +00004606void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004607 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
David Blaikiebd483762013-05-20 04:58:53 +00004608 return;
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00004609 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
Adrian McCarthyab1e7862016-07-21 18:43:20 +00004610 if (!NSDecl->isAnonymousNamespace() ||
4611 CGM.getCodeGenOpts().DebugExplicitImport) {
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004612 auto Loc = UD.getLocation();
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00004613 DBuilder.createImportedModule(
4614 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004615 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
Ekaterina Romanova9218a3b2015-12-10 18:52:50 +00004616 }
David Blaikie9f88fe82013-04-22 06:13:21 +00004617}
4618
David Blaikiebd483762013-05-20 04:58:53 +00004619void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004620 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
David Blaikiebd483762013-05-20 04:58:53 +00004621 return;
4622 assert(UD.shadow_size() &&
4623 "We shouldn't be codegening an invalid UsingDecl containing no decls");
4624 // Emitting one decl is sufficient - debuggers can detect that this is an
4625 // overloaded name & provide lookup for all the overloads.
4626 const UsingShadowDecl &USD = **UD.shadow_begin();
David Blaikie2a58a182016-08-05 19:03:01 +00004627
4628 // FIXME: Skip functions with undeduced auto return type for now since we
4629 // don't currently have the plumbing for separate declarations & definitions
4630 // of free functions and mismatched types (auto in the declaration, concrete
4631 // return type in the definition)
4632 if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
4633 if (const auto *AT =
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00004634 FD->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
David Blaikie2a58a182016-08-05 19:03:01 +00004635 if (AT->getDeducedType().isNull())
4636 return;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004637 if (llvm::DINode *Target =
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004638 getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4639 auto Loc = USD.getLocation();
David Blaikiebd483762013-05-20 04:58:53 +00004640 DBuilder.createImportedDeclaration(
4641 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004642 getOrCreateFile(Loc), getLineNumber(Loc));
4643 }
David Blaikiebd483762013-05-20 04:58:53 +00004644}
4645
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00004646void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
David Blaikieaf09f4a2016-05-03 23:06:40 +00004647 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
4648 return;
Adrian Prantl8a634c12015-12-18 19:44:31 +00004649 if (Module *M = ID.getImportedModule()) {
Chad Rosiere5dafd12015-12-18 20:08:40 +00004650 auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004651 auto Loc = ID.getLocation();
Adrian Prantl8a634c12015-12-18 19:44:31 +00004652 DBuilder.createImportedDeclaration(
4653 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004654 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
4655 getLineNumber(Loc));
Adrian Prantl8a634c12015-12-18 19:44:31 +00004656 }
Adrian Prantlc4bb47e2015-06-30 17:39:51 +00004657}
4658
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004659llvm::DIImportedEntity *
David Blaikief121b932013-05-20 22:50:41 +00004660CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004661 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
Duncan P. N. Exon Smithdadc2b62015-04-21 18:43:54 +00004662 return nullptr;
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004663 auto &VH = NamespaceAliasCache[&NA];
David Blaikief121b932013-05-20 22:50:41 +00004664 if (VH)
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004665 return cast<llvm::DIImportedEntity>(VH);
4666 llvm::DIImportedEntity *R;
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004667 auto Loc = NA.getLocation();
David Majnemer58ed0f32016-07-17 00:39:12 +00004668 if (const auto *Underlying =
David Blaikief121b932013-05-20 22:50:41 +00004669 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
4670 // This could cache & dedup here rather than relying on metadata deduping.
David Blaikie551fb0a2014-04-06 06:30:03 +00004671 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00004672 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004673 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
4674 getLineNumber(Loc), NA.getName());
David Blaikief121b932013-05-20 22:50:41 +00004675 else
David Blaikie551fb0a2014-04-06 06:30:03 +00004676 R = DBuilder.createImportedDeclaration(
David Blaikief121b932013-05-20 22:50:41 +00004677 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
Adrian Prantlddb8e062017-05-12 16:23:53 +00004678 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
Adrian Prantl5649b0e2017-07-19 00:09:58 +00004679 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004680 VH.reset(R);
David Blaikief121b932013-05-20 22:50:41 +00004681 return R;
4682}
4683
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004684llvm::DINamespace *
Adrian Prantlddb8e062017-05-12 16:23:53 +00004685CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
4686 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
4687 // if necessary, and this way multiple declarations of the same namespace in
4688 // different parent modules stay distinct.
4689 auto I = NamespaceCache.find(NSDecl);
Adrian Prantld8870552017-05-11 22:59:19 +00004690 if (I != NamespaceCache.end())
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004691 return cast<llvm::DINamespace>(I->second);
Eric Christopherb2a008c2013-05-16 00:45:12 +00004692
Adrian Prantl6ec370a2015-09-10 18:39:45 +00004693 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
Adrian Prantld8870552017-05-11 22:59:19 +00004694 // Don't trust the context if it is a DIModule (see comment above).
Adrian Prantlddb8e062017-05-12 16:23:53 +00004695 llvm::DINamespace *NS =
4696 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
4697 NamespaceCache[NSDecl].reset(NS);
Guy Benyei11169dd2012-12-18 14:30:41 +00004698 return NS;
4699}
4700
Adrian Prantla5206ce2015-09-22 23:26:43 +00004701void CGDebugInfo::setDwoId(uint64_t Signature) {
4702 assert(TheCU && "no main compile unit");
4703 TheCU->setDWOId(Signature);
4704}
4705
Guy Benyei11169dd2012-12-18 14:30:41 +00004706void CGDebugInfo::finalize() {
David Blaikie87dab872014-05-07 16:56:58 +00004707 // Creating types might create further types - invalidating the current
4708 // element and the size(), so don't cache/reference them.
4709 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
4710 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004711 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
Duncan P. N. Exon Smith497d4d462015-04-11 19:05:04 +00004712 ? CreateTypeDefinition(E.Type, E.Unit)
4713 : E.Decl;
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004714 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
David Blaikie87dab872014-05-07 16:56:58 +00004715 }
4716
Adrian Prantle0cabe22019-11-21 09:56:01 -08004717 // Add methods to interface.
4718 for (const auto &P : ObjCMethodCache) {
4719 if (P.second.empty())
4720 continue;
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004721
Adrian Prantle0cabe22019-11-21 09:56:01 -08004722 QualType QTy(P.first->getTypeForDecl(), 0);
4723 auto It = TypeCache.find(QTy.getAsOpaquePtr());
4724 assert(It != TypeCache.end());
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004725
Adrian Prantle0cabe22019-11-21 09:56:01 -08004726 llvm::DICompositeType *InterfaceDecl =
4727 cast<llvm::DICompositeType>(It->second);
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004728
Adrian Prantle0cabe22019-11-21 09:56:01 -08004729 auto CurElts = InterfaceDecl->getElements();
4730 SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
4731
4732 // For DWARF v4 or earlier, only add objc_direct methods.
4733 for (auto &SubprogramDirect : P.second)
4734 if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
4735 EltTys.push_back(SubprogramDirect.getPointer());
4736
4737 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4738 DBuilder.replaceArrays(InterfaceDecl, Elements);
Jonas Devlieghered8ba8ae2018-06-27 17:31:59 +00004739 }
4740
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004741 for (const auto &P : ReplaceMap) {
4742 assert(P.second);
4743 auto *Ty = cast<llvm::DIType>(P.second);
Duncan P. N. Exon Smith4caa7f22015-04-16 01:00:56 +00004744 assert(Ty->isForwardDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00004745
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004746 auto It = TypeCache.find(P.first);
4747 assert(It != TypeCache.end());
4748 assert(It->second);
Adrian Prantl73409ce2013-03-11 18:33:46 +00004749
Duncan P. N. Exon Smith9dd4e4e2015-04-29 16:40:08 +00004750 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004751 cast<llvm::DIType>(It->second));
Guy Benyei11169dd2012-12-18 14:30:41 +00004752 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00004753
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004754 for (const auto &P : FwdDeclReplaceMap) {
4755 assert(P.second);
4756 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004757 llvm::Metadata *Repl;
Frederic Rissd253ed62014-11-18 03:40:51 +00004758
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004759 auto It = DeclCache.find(P.first);
Adrian Prantl97f76852014-12-19 01:02:11 +00004760 // If there has been no definition for the declaration, call RAUW
Frederic Rissd253ed62014-11-18 03:40:51 +00004761 // with ourselves, that will destroy the temporary MDNode and
4762 // replace it with a standard one, avoiding leaking memory.
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004763 if (It == DeclCache.end())
4764 Repl = P.second;
Frederic Rissd253ed62014-11-18 03:40:51 +00004765 else
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004766 Repl = It->second;
Frederic Rissdce60a72014-11-19 18:53:46 +00004767
Adrian Prantl5f4740d2016-12-20 02:10:02 +00004768 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
4769 Repl = GVE->getVariable();
Duncan P. N. Exon Smithd899f6e2015-04-18 00:07:30 +00004770 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
Frederic Rissd253ed62014-11-18 03:40:51 +00004771 }
4772
Adrian Prantl73409ce2013-03-11 18:33:46 +00004773 // We keep our own list of retained types, because we need to look
4774 // up the final type in the type cache.
Adrian Prantl3a884fa2015-08-27 22:56:46 +00004775 for (auto &RT : RetainedTypes)
Adrian Prantlad9a195e2015-08-27 21:21:19 +00004776 if (auto MD = TypeCache[RT])
4777 DBuilder.retainType(cast<llvm::DIType>(MD));
Adrian Prantl73409ce2013-03-11 18:33:46 +00004778
Guy Benyei11169dd2012-12-18 14:30:41 +00004779 DBuilder.finalize();
4780}
David Blaikie66088d52014-09-24 17:01:27 +00004781
4782void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00004783 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
David Blaikie66088d52014-09-24 17:01:27 +00004784 return;
Duncan P. N. Exon Smith5043f912015-03-27 22:58:05 +00004785
Adrian Prantlc2a44ec2018-12-11 16:58:46 +00004786 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
Duncan P. N. Exon Smith5043f912015-03-27 22:58:05 +00004787 // Don't ignore in case of explicit cast where it is referenced indirectly.
4788 DBuilder.retainType(DieTy);
David Blaikie66088d52014-09-24 17:01:27 +00004789}
Amara Emerson652795d2016-11-10 14:44:30 +00004790
4791llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
4792 if (LexicalBlockStack.empty())
4793 return llvm::DebugLoc();
4794
4795 llvm::MDNode *Scope = LexicalBlockStack.back();
Jonas Devlieghere9ef49652018-06-28 10:56:40 +00004796 return llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), Scope);
Amara Emerson652795d2016-11-10 14:44:30 +00004797}
Vedant Kumar5931b4e2018-10-05 20:37:17 +00004798
4799llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
4800 // Call site-related attributes are only useful in optimized programs, and
4801 // when there's a possibility of debugging backtraces.
4802 if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo ||
4803 DebugKind == codegenoptions::LocTrackingOnly)
4804 return llvm::DINode::FlagZero;
4805
4806 // Call site-related attributes are available in DWARF v5. Some debuggers,
4807 // while not fully DWARF v5-compliant, may accept these attributes as if they
4808 // were part of DWARF v4.
4809 bool SupportsDWARFv4Ext =
4810 CGM.getCodeGenOpts().DwarfVersion == 4 &&
Djordje Todorovic639d36b2019-06-26 09:38:09 +00004811 (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
Vedant Kumar568db782019-11-13 18:19:32 -08004812 CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
Djordje Todorovic639d36b2019-06-26 09:38:09 +00004813
Vedant Kumar568db782019-11-13 18:19:32 -08004814 if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5 &&
4815 !CGM.getCodeGenOpts().EnableDebugEntryValues)
Vedant Kumar5931b4e2018-10-05 20:37:17 +00004816 return llvm::DINode::FlagZero;
4817
4818 return llvm::DINode::FlagAllCallsDescribed;
4819}