1 | //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===// |
2 | // |
3 | // 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 |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This coordinates the debug information generation while generating code. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #include "CGDebugInfo.h" |
14 | #include "CGBlocks.h" |
15 | #include "CGCXXABI.h" |
16 | #include "CGObjCRuntime.h" |
17 | #include "CGRecordLayout.h" |
18 | #include "CodeGenFunction.h" |
19 | #include "CodeGenModule.h" |
20 | #include "ConstantEmitter.h" |
21 | #include "TargetInfo.h" |
22 | #include "clang/AST/ASTContext.h" |
23 | #include "clang/AST/Attr.h" |
24 | #include "clang/AST/DeclFriend.h" |
25 | #include "clang/AST/DeclObjC.h" |
26 | #include "clang/AST/DeclTemplate.h" |
27 | #include "clang/AST/Expr.h" |
28 | #include "clang/AST/RecordLayout.h" |
29 | #include "clang/AST/RecursiveASTVisitor.h" |
30 | #include "clang/AST/VTableBuilder.h" |
31 | #include "clang/Basic/CodeGenOptions.h" |
32 | #include "clang/Basic/FileManager.h" |
33 | #include "clang/Basic/SourceManager.h" |
34 | #include "clang/Basic/Version.h" |
35 | #include "clang/Frontend/FrontendOptions.h" |
36 | #include "clang/Lex/HeaderSearchOptions.h" |
37 | #include "clang/Lex/ModuleMap.h" |
38 | #include "clang/Lex/PreprocessorOptions.h" |
39 | #include "llvm/ADT/DenseSet.h" |
40 | #include "llvm/ADT/SmallVector.h" |
41 | #include "llvm/ADT/StringExtras.h" |
42 | #include "llvm/IR/Constants.h" |
43 | #include "llvm/IR/DataLayout.h" |
44 | #include "llvm/IR/DerivedTypes.h" |
45 | #include "llvm/IR/Instructions.h" |
46 | #include "llvm/IR/Intrinsics.h" |
47 | #include "llvm/IR/Metadata.h" |
48 | #include "llvm/IR/Module.h" |
49 | #include "llvm/Support/FileSystem.h" |
50 | #include "llvm/Support/MD5.h" |
51 | #include "llvm/Support/Path.h" |
52 | #include "llvm/Support/SHA1.h" |
53 | #include "llvm/Support/SHA256.h" |
54 | #include "llvm/Support/TimeProfiler.h" |
55 | #include <optional> |
56 | using namespace clang; |
57 | using namespace clang::CodeGen; |
58 | |
59 | static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) { |
60 | auto TI = Ctx.getTypeInfo(T: Ty); |
61 | return TI.isAlignRequired() ? TI.Align : 0; |
62 | } |
63 | |
64 | static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) { |
65 | return getTypeAlignIfRequired(Ty: Ty.getTypePtr(), Ctx); |
66 | } |
67 | |
68 | static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) { |
69 | return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0; |
70 | } |
71 | |
72 | CGDebugInfo::CGDebugInfo(CodeGenModule &CGM) |
73 | : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()), |
74 | DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs), |
75 | DBuilder(CGM.getModule()) { |
76 | CreateCompileUnit(); |
77 | } |
78 | |
79 | CGDebugInfo::~CGDebugInfo() { |
80 | assert(LexicalBlockStack.empty() && |
81 | "Region stack mismatch, stack not empty!" ); |
82 | } |
83 | |
84 | ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, |
85 | SourceLocation TemporaryLocation) |
86 | : CGF(&CGF) { |
87 | init(TemporaryLocation); |
88 | } |
89 | |
90 | ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, |
91 | bool DefaultToEmpty, |
92 | SourceLocation TemporaryLocation) |
93 | : CGF(&CGF) { |
94 | init(TemporaryLocation, DefaultToEmpty); |
95 | } |
96 | |
97 | void ApplyDebugLocation::init(SourceLocation TemporaryLocation, |
98 | bool DefaultToEmpty) { |
99 | auto *DI = CGF->getDebugInfo(); |
100 | if (!DI) { |
101 | CGF = nullptr; |
102 | return; |
103 | } |
104 | |
105 | OriginalLocation = CGF->Builder.getCurrentDebugLocation(); |
106 | |
107 | if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled()) |
108 | return; |
109 | |
110 | if (TemporaryLocation.isValid()) { |
111 | DI->EmitLocation(Builder&: CGF->Builder, Loc: TemporaryLocation); |
112 | return; |
113 | } |
114 | |
115 | if (DefaultToEmpty) { |
116 | CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc()); |
117 | return; |
118 | } |
119 | |
120 | // Construct a location that has a valid scope, but no line info. |
121 | assert(!DI->LexicalBlockStack.empty()); |
122 | CGF->Builder.SetCurrentDebugLocation( |
123 | llvm::DILocation::get(Context&: DI->LexicalBlockStack.back()->getContext(), Line: 0, Column: 0, |
124 | Scope: DI->LexicalBlockStack.back(), InlinedAt: DI->getInlinedAt())); |
125 | } |
126 | |
127 | ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E) |
128 | : CGF(&CGF) { |
129 | init(TemporaryLocation: E->getExprLoc()); |
130 | } |
131 | |
132 | ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc) |
133 | : CGF(&CGF) { |
134 | if (!CGF.getDebugInfo()) { |
135 | this->CGF = nullptr; |
136 | return; |
137 | } |
138 | OriginalLocation = CGF.Builder.getCurrentDebugLocation(); |
139 | if (Loc) |
140 | CGF.Builder.SetCurrentDebugLocation(std::move(Loc)); |
141 | } |
142 | |
143 | ApplyDebugLocation::~ApplyDebugLocation() { |
144 | // Query CGF so the location isn't overwritten when location updates are |
145 | // temporarily disabled (for C++ default function arguments) |
146 | if (CGF) |
147 | CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation)); |
148 | } |
149 | |
150 | ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF, |
151 | GlobalDecl InlinedFn) |
152 | : CGF(&CGF) { |
153 | if (!CGF.getDebugInfo()) { |
154 | this->CGF = nullptr; |
155 | return; |
156 | } |
157 | auto &DI = *CGF.getDebugInfo(); |
158 | SavedLocation = DI.getLocation(); |
159 | assert((DI.getInlinedAt() == |
160 | CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) && |
161 | "CGDebugInfo and IRBuilder are out of sync" ); |
162 | |
163 | DI.EmitInlineFunctionStart(Builder&: CGF.Builder, GD: InlinedFn); |
164 | } |
165 | |
166 | ApplyInlineDebugLocation::~ApplyInlineDebugLocation() { |
167 | if (!CGF) |
168 | return; |
169 | auto &DI = *CGF->getDebugInfo(); |
170 | DI.EmitInlineFunctionEnd(Builder&: CGF->Builder); |
171 | DI.EmitLocation(Builder&: CGF->Builder, Loc: SavedLocation); |
172 | } |
173 | |
174 | void CGDebugInfo::setLocation(SourceLocation Loc) { |
175 | // If the new location isn't valid return. |
176 | if (Loc.isInvalid()) |
177 | return; |
178 | |
179 | CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc); |
180 | |
181 | // If we've changed files in the middle of a lexical scope go ahead |
182 | // and create a new lexical scope with file node if it's different |
183 | // from the one in the scope. |
184 | if (LexicalBlockStack.empty()) |
185 | return; |
186 | |
187 | SourceManager &SM = CGM.getContext().getSourceManager(); |
188 | auto *Scope = cast<llvm::DIScope>(Val&: LexicalBlockStack.back()); |
189 | PresumedLoc PCLoc = SM.getPresumedLoc(Loc: CurLoc); |
190 | if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(Loc: CurLoc)) |
191 | return; |
192 | |
193 | if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Val: Scope)) { |
194 | LexicalBlockStack.pop_back(); |
195 | LexicalBlockStack.emplace_back(args: DBuilder.createLexicalBlockFile( |
196 | Scope: LBF->getScope(), File: getOrCreateFile(Loc: CurLoc))); |
197 | } else if (isa<llvm::DILexicalBlock>(Val: Scope) || |
198 | isa<llvm::DISubprogram>(Val: Scope)) { |
199 | LexicalBlockStack.pop_back(); |
200 | LexicalBlockStack.emplace_back( |
201 | args: DBuilder.createLexicalBlockFile(Scope, File: getOrCreateFile(Loc: CurLoc))); |
202 | } |
203 | } |
204 | |
205 | llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) { |
206 | llvm::DIScope *Mod = getParentModuleOrNull(D); |
207 | return getContextDescriptor(Context: cast<Decl>(Val: D->getDeclContext()), |
208 | Default: Mod ? Mod : TheCU); |
209 | } |
210 | |
211 | llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context, |
212 | llvm::DIScope *Default) { |
213 | if (!Context) |
214 | return Default; |
215 | |
216 | auto I = RegionMap.find(Val: Context); |
217 | if (I != RegionMap.end()) { |
218 | llvm::Metadata *V = I->second; |
219 | return dyn_cast_or_null<llvm::DIScope>(Val: V); |
220 | } |
221 | |
222 | // Check namespace. |
223 | if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Val: Context)) |
224 | return getOrCreateNamespace(N: NSDecl); |
225 | |
226 | if (const auto *RDecl = dyn_cast<RecordDecl>(Val: Context)) |
227 | if (!RDecl->isDependentType()) |
228 | return getOrCreateType(Ty: CGM.getContext().getTypeDeclType(RDecl), |
229 | Fg: TheCU->getFile()); |
230 | return Default; |
231 | } |
232 | |
233 | PrintingPolicy CGDebugInfo::getPrintingPolicy() const { |
234 | PrintingPolicy PP = CGM.getContext().getPrintingPolicy(); |
235 | |
236 | // If we're emitting codeview, it's important to try to match MSVC's naming so |
237 | // that visualizers written for MSVC will trigger for our class names. In |
238 | // particular, we can't have spaces between arguments of standard templates |
239 | // like basic_string and vector, but we must have spaces between consecutive |
240 | // angle brackets that close nested template argument lists. |
241 | if (CGM.getCodeGenOpts().EmitCodeView) { |
242 | PP.MSVCFormatting = true; |
243 | PP.SplitTemplateClosers = true; |
244 | } else { |
245 | // For DWARF, printing rules are underspecified. |
246 | // SplitTemplateClosers yields better interop with GCC and GDB (PR46052). |
247 | PP.SplitTemplateClosers = true; |
248 | } |
249 | |
250 | PP.SuppressInlineNamespace = false; |
251 | PP.PrintCanonicalTypes = true; |
252 | PP.UsePreferredNames = false; |
253 | PP.AlwaysIncludeTypeForTemplateArgument = true; |
254 | PP.UseEnumerators = false; |
255 | |
256 | // Apply -fdebug-prefix-map. |
257 | PP.Callbacks = &PrintCB; |
258 | return PP; |
259 | } |
260 | |
261 | StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) { |
262 | return internString(A: GetName(FD)); |
263 | } |
264 | |
265 | StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) { |
266 | SmallString<256> MethodName; |
267 | llvm::raw_svector_ostream OS(MethodName); |
268 | OS << (OMD->isInstanceMethod() ? '-' : '+') << '['; |
269 | const DeclContext *DC = OMD->getDeclContext(); |
270 | if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) { |
271 | OS << OID->getName(); |
272 | } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) { |
273 | OS << OID->getName(); |
274 | } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) { |
275 | if (OC->IsClassExtension()) { |
276 | OS << OC->getClassInterface()->getName(); |
277 | } else { |
278 | OS << OC->getIdentifier()->getNameStart() << '(' |
279 | << OC->getIdentifier()->getNameStart() << ')'; |
280 | } |
281 | } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) { |
282 | OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')'; |
283 | } |
284 | OS << ' ' << OMD->getSelector().getAsString() << ']'; |
285 | |
286 | return internString(A: OS.str()); |
287 | } |
288 | |
289 | StringRef CGDebugInfo::getSelectorName(Selector S) { |
290 | return internString(A: S.getAsString()); |
291 | } |
292 | |
293 | StringRef CGDebugInfo::getClassName(const RecordDecl *RD) { |
294 | if (isa<ClassTemplateSpecializationDecl>(Val: RD)) { |
295 | // Copy this name on the side and use its reference. |
296 | return internString(A: GetName(RD)); |
297 | } |
298 | |
299 | // quick optimization to avoid having to intern strings that are already |
300 | // stored reliably elsewhere |
301 | if (const IdentifierInfo *II = RD->getIdentifier()) |
302 | return II->getName(); |
303 | |
304 | // The CodeView printer in LLVM wants to see the names of unnamed types |
305 | // because they need to have a unique identifier. |
306 | // These names are used to reconstruct the fully qualified type names. |
307 | if (CGM.getCodeGenOpts().EmitCodeView) { |
308 | if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) { |
309 | assert(RD->getDeclContext() == D->getDeclContext() && |
310 | "Typedef should not be in another decl context!" ); |
311 | assert(D->getDeclName().getAsIdentifierInfo() && |
312 | "Typedef was not named!" ); |
313 | return D->getDeclName().getAsIdentifierInfo()->getName(); |
314 | } |
315 | |
316 | if (CGM.getLangOpts().CPlusPlus) { |
317 | StringRef Name; |
318 | |
319 | ASTContext &Context = CGM.getContext(); |
320 | if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD)) |
321 | // Anonymous types without a name for linkage purposes have their |
322 | // declarator mangled in if they have one. |
323 | Name = DD->getName(); |
324 | else if (const TypedefNameDecl *TND = |
325 | Context.getTypedefNameForUnnamedTagDecl(RD)) |
326 | // Anonymous types without a name for linkage purposes have their |
327 | // associate typedef mangled in if they have one. |
328 | Name = TND->getName(); |
329 | |
330 | // Give lambdas a display name based on their name mangling. |
331 | if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) |
332 | if (CXXRD->isLambda()) |
333 | return internString( |
334 | A: CGM.getCXXABI().getMangleContext().getLambdaString(Lambda: CXXRD)); |
335 | |
336 | if (!Name.empty()) { |
337 | SmallString<256> UnnamedType("<unnamed-type-" ); |
338 | UnnamedType += Name; |
339 | UnnamedType += '>'; |
340 | return internString(A: UnnamedType); |
341 | } |
342 | } |
343 | } |
344 | |
345 | return StringRef(); |
346 | } |
347 | |
348 | std::optional<llvm::DIFile::ChecksumKind> |
349 | CGDebugInfo::computeChecksum(FileID FID, SmallString<64> &Checksum) const { |
350 | Checksum.clear(); |
351 | |
352 | if (!CGM.getCodeGenOpts().EmitCodeView && |
353 | CGM.getCodeGenOpts().DwarfVersion < 5) |
354 | return std::nullopt; |
355 | |
356 | SourceManager &SM = CGM.getContext().getSourceManager(); |
357 | std::optional<llvm::MemoryBufferRef> MemBuffer = SM.getBufferOrNone(FID); |
358 | if (!MemBuffer) |
359 | return std::nullopt; |
360 | |
361 | auto Data = llvm::arrayRefFromStringRef(Input: MemBuffer->getBuffer()); |
362 | switch (CGM.getCodeGenOpts().getDebugSrcHash()) { |
363 | case clang::CodeGenOptions::DSH_MD5: |
364 | llvm::toHex(Input: llvm::MD5::hash(Data), /*LowerCase=*/true, Output&: Checksum); |
365 | return llvm::DIFile::CSK_MD5; |
366 | case clang::CodeGenOptions::DSH_SHA1: |
367 | llvm::toHex(Input: llvm::SHA1::hash(Data), /*LowerCase=*/true, Output&: Checksum); |
368 | return llvm::DIFile::CSK_SHA1; |
369 | case clang::CodeGenOptions::DSH_SHA256: |
370 | llvm::toHex(Input: llvm::SHA256::hash(Data), /*LowerCase=*/true, Output&: Checksum); |
371 | return llvm::DIFile::CSK_SHA256; |
372 | } |
373 | llvm_unreachable("Unhandled DebugSrcHashKind enum" ); |
374 | } |
375 | |
376 | std::optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM, |
377 | FileID FID) { |
378 | if (!CGM.getCodeGenOpts().EmbedSource) |
379 | return std::nullopt; |
380 | |
381 | bool SourceInvalid = false; |
382 | StringRef Source = SM.getBufferData(FID, Invalid: &SourceInvalid); |
383 | |
384 | if (SourceInvalid) |
385 | return std::nullopt; |
386 | |
387 | return Source; |
388 | } |
389 | |
390 | llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) { |
391 | SourceManager &SM = CGM.getContext().getSourceManager(); |
392 | StringRef FileName; |
393 | FileID FID; |
394 | std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo; |
395 | |
396 | if (Loc.isInvalid()) { |
397 | // The DIFile used by the CU is distinct from the main source file. Call |
398 | // createFile() below for canonicalization if the source file was specified |
399 | // with an absolute path. |
400 | FileName = TheCU->getFile()->getFilename(); |
401 | CSInfo = TheCU->getFile()->getChecksum(); |
402 | } else { |
403 | PresumedLoc PLoc = SM.getPresumedLoc(Loc); |
404 | FileName = PLoc.getFilename(); |
405 | |
406 | if (FileName.empty()) { |
407 | FileName = TheCU->getFile()->getFilename(); |
408 | } else { |
409 | FileName = PLoc.getFilename(); |
410 | } |
411 | FID = PLoc.getFileID(); |
412 | } |
413 | |
414 | // Cache the results. |
415 | auto It = DIFileCache.find(Val: FileName.data()); |
416 | if (It != DIFileCache.end()) { |
417 | // Verify that the information still exists. |
418 | if (llvm::Metadata *V = It->second) |
419 | return cast<llvm::DIFile>(Val: V); |
420 | } |
421 | |
422 | // Put Checksum at a scope where it will persist past the createFile call. |
423 | SmallString<64> Checksum; |
424 | if (!CSInfo) { |
425 | std::optional<llvm::DIFile::ChecksumKind> CSKind = |
426 | computeChecksum(FID, Checksum); |
427 | if (CSKind) |
428 | CSInfo.emplace(args&: *CSKind, args&: Checksum); |
429 | } |
430 | return createFile(FileName, CSInfo, Source: getSource(SM, FID: SM.getFileID(SpellingLoc: Loc))); |
431 | } |
432 | |
433 | llvm::DIFile *CGDebugInfo::createFile( |
434 | StringRef FileName, |
435 | std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo, |
436 | std::optional<StringRef> Source) { |
437 | StringRef Dir; |
438 | StringRef File; |
439 | std::string RemappedFile = remapDIPath(FileName); |
440 | std::string CurDir = remapDIPath(getCurrentDirname()); |
441 | SmallString<128> DirBuf; |
442 | SmallString<128> FileBuf; |
443 | if (llvm::sys::path::is_absolute(path: RemappedFile)) { |
444 | // Strip the common prefix (if it is more than just "/" or "C:\") from |
445 | // current directory and FileName for a more space-efficient encoding. |
446 | auto FileIt = llvm::sys::path::begin(path: RemappedFile); |
447 | auto FileE = llvm::sys::path::end(path: RemappedFile); |
448 | auto CurDirIt = llvm::sys::path::begin(path: CurDir); |
449 | auto CurDirE = llvm::sys::path::end(path: CurDir); |
450 | for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt) |
451 | llvm::sys::path::append(path&: DirBuf, a: *CurDirIt); |
452 | if (llvm::sys::path::root_path(path: DirBuf) == DirBuf) { |
453 | // Don't strip the common prefix if it is only the root ("/" or "C:\") |
454 | // since that would make LLVM diagnostic locations confusing. |
455 | Dir = {}; |
456 | File = RemappedFile; |
457 | } else { |
458 | for (; FileIt != FileE; ++FileIt) |
459 | llvm::sys::path::append(path&: FileBuf, a: *FileIt); |
460 | Dir = DirBuf; |
461 | File = FileBuf; |
462 | } |
463 | } else { |
464 | if (!llvm::sys::path::is_absolute(path: FileName)) |
465 | Dir = CurDir; |
466 | File = RemappedFile; |
467 | } |
468 | llvm::DIFile *F = DBuilder.createFile(Filename: File, Directory: Dir, Checksum: CSInfo, Source); |
469 | DIFileCache[FileName.data()].reset(MD: F); |
470 | return F; |
471 | } |
472 | |
473 | std::string CGDebugInfo::remapDIPath(StringRef Path) const { |
474 | SmallString<256> P = Path; |
475 | for (auto &[From, To] : llvm::reverse(C: CGM.getCodeGenOpts().DebugPrefixMap)) |
476 | if (llvm::sys::path::replace_path_prefix(Path&: P, OldPrefix: From, NewPrefix: To)) |
477 | break; |
478 | return P.str().str(); |
479 | } |
480 | |
481 | unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) { |
482 | if (Loc.isInvalid()) |
483 | return 0; |
484 | SourceManager &SM = CGM.getContext().getSourceManager(); |
485 | return SM.getPresumedLoc(Loc).getLine(); |
486 | } |
487 | |
488 | unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) { |
489 | // We may not want column information at all. |
490 | if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo) |
491 | return 0; |
492 | |
493 | // If the location is invalid then use the current column. |
494 | if (Loc.isInvalid() && CurLoc.isInvalid()) |
495 | return 0; |
496 | SourceManager &SM = CGM.getContext().getSourceManager(); |
497 | PresumedLoc PLoc = SM.getPresumedLoc(Loc: Loc.isValid() ? Loc : CurLoc); |
498 | return PLoc.isValid() ? PLoc.getColumn() : 0; |
499 | } |
500 | |
501 | StringRef CGDebugInfo::getCurrentDirname() { |
502 | if (!CGM.getCodeGenOpts().DebugCompilationDir.empty()) |
503 | return CGM.getCodeGenOpts().DebugCompilationDir; |
504 | |
505 | if (!CWDName.empty()) |
506 | return CWDName; |
507 | llvm::ErrorOr<std::string> CWD = |
508 | CGM.getFileSystem()->getCurrentWorkingDirectory(); |
509 | if (!CWD) |
510 | return StringRef(); |
511 | return CWDName = internString(A: *CWD); |
512 | } |
513 | |
514 | void CGDebugInfo::CreateCompileUnit() { |
515 | SmallString<64> Checksum; |
516 | std::optional<llvm::DIFile::ChecksumKind> CSKind; |
517 | std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo; |
518 | |
519 | // Should we be asking the SourceManager for the main file name, instead of |
520 | // accepting it as an argument? This just causes the main file name to |
521 | // mismatch with source locations and create extra lexical scopes or |
522 | // mismatched debug info (a CU with a DW_AT_file of "-", because that's what |
523 | // the driver passed, but functions/other things have DW_AT_file of "<stdin>" |
524 | // because that's what the SourceManager says) |
525 | |
526 | // Get absolute path name. |
527 | SourceManager &SM = CGM.getContext().getSourceManager(); |
528 | auto &CGO = CGM.getCodeGenOpts(); |
529 | const LangOptions &LO = CGM.getLangOpts(); |
530 | std::string MainFileName = CGO.MainFileName; |
531 | if (MainFileName.empty()) |
532 | MainFileName = "<stdin>" ; |
533 | |
534 | // The main file name provided via the "-main-file-name" option contains just |
535 | // the file name itself with no path information. This file name may have had |
536 | // a relative path, so we look into the actual file entry for the main |
537 | // file to determine the real absolute path for the file. |
538 | std::string MainFileDir; |
539 | if (OptionalFileEntryRef MainFile = |
540 | SM.getFileEntryRefForID(FID: SM.getMainFileID())) { |
541 | MainFileDir = std::string(MainFile->getDir().getName()); |
542 | if (!llvm::sys::path::is_absolute(path: MainFileName)) { |
543 | llvm::SmallString<1024> MainFileDirSS(MainFileDir); |
544 | llvm::sys::path::Style Style = |
545 | LO.UseTargetPathSeparator |
546 | ? (CGM.getTarget().getTriple().isOSWindows() |
547 | ? llvm::sys::path::Style::windows_backslash |
548 | : llvm::sys::path::Style::posix) |
549 | : llvm::sys::path::Style::native; |
550 | llvm::sys::path::append(path&: MainFileDirSS, style: Style, a: MainFileName); |
551 | MainFileName = std::string( |
552 | llvm::sys::path::remove_leading_dotslash(path: MainFileDirSS, style: Style)); |
553 | } |
554 | // If the main file name provided is identical to the input file name, and |
555 | // if the input file is a preprocessed source, use the module name for |
556 | // debug info. The module name comes from the name specified in the first |
557 | // linemarker if the input is a preprocessed source. In this case we don't |
558 | // know the content to compute a checksum. |
559 | if (MainFile->getName() == MainFileName && |
560 | FrontendOptions::getInputKindForExtension( |
561 | Extension: MainFile->getName().rsplit(Separator: '.').second) |
562 | .isPreprocessed()) { |
563 | MainFileName = CGM.getModule().getName().str(); |
564 | } else { |
565 | CSKind = computeChecksum(FID: SM.getMainFileID(), Checksum); |
566 | } |
567 | } |
568 | |
569 | llvm::dwarf::SourceLanguage LangTag; |
570 | if (LO.CPlusPlus) { |
571 | if (LO.ObjC) |
572 | LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus; |
573 | else if (CGO.DebugStrictDwarf && CGO.DwarfVersion < 5) |
574 | LangTag = llvm::dwarf::DW_LANG_C_plus_plus; |
575 | else if (LO.CPlusPlus14) |
576 | LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14; |
577 | else if (LO.CPlusPlus11) |
578 | LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11; |
579 | else |
580 | LangTag = llvm::dwarf::DW_LANG_C_plus_plus; |
581 | } else if (LO.ObjC) { |
582 | LangTag = llvm::dwarf::DW_LANG_ObjC; |
583 | } else if (LO.OpenCL && (!CGM.getCodeGenOpts().DebugStrictDwarf || |
584 | CGM.getCodeGenOpts().DwarfVersion >= 5)) { |
585 | LangTag = llvm::dwarf::DW_LANG_OpenCL; |
586 | } else if (LO.RenderScript) { |
587 | LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript; |
588 | } else if (LO.C11 && !(CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)) { |
589 | LangTag = llvm::dwarf::DW_LANG_C11; |
590 | } else if (LO.C99) { |
591 | LangTag = llvm::dwarf::DW_LANG_C99; |
592 | } else { |
593 | LangTag = llvm::dwarf::DW_LANG_C89; |
594 | } |
595 | |
596 | std::string Producer = getClangFullVersion(); |
597 | |
598 | // Figure out which version of the ObjC runtime we have. |
599 | unsigned RuntimeVers = 0; |
600 | if (LO.ObjC) |
601 | RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1; |
602 | |
603 | llvm::DICompileUnit::DebugEmissionKind EmissionKind; |
604 | switch (DebugKind) { |
605 | case llvm::codegenoptions::NoDebugInfo: |
606 | case llvm::codegenoptions::LocTrackingOnly: |
607 | EmissionKind = llvm::DICompileUnit::NoDebug; |
608 | break; |
609 | case llvm::codegenoptions::DebugLineTablesOnly: |
610 | EmissionKind = llvm::DICompileUnit::LineTablesOnly; |
611 | break; |
612 | case llvm::codegenoptions::DebugDirectivesOnly: |
613 | EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly; |
614 | break; |
615 | case llvm::codegenoptions::DebugInfoConstructor: |
616 | case llvm::codegenoptions::LimitedDebugInfo: |
617 | case llvm::codegenoptions::FullDebugInfo: |
618 | case llvm::codegenoptions::UnusedTypeInfo: |
619 | EmissionKind = llvm::DICompileUnit::FullDebug; |
620 | break; |
621 | } |
622 | |
623 | uint64_t DwoId = 0; |
624 | auto &CGOpts = CGM.getCodeGenOpts(); |
625 | // The DIFile used by the CU is distinct from the main source |
626 | // file. Its directory part specifies what becomes the |
627 | // DW_AT_comp_dir (the compilation directory), even if the source |
628 | // file was specified with an absolute path. |
629 | if (CSKind) |
630 | CSInfo.emplace(args&: *CSKind, args&: Checksum); |
631 | llvm::DIFile *CUFile = DBuilder.createFile( |
632 | Filename: remapDIPath(Path: MainFileName), Directory: remapDIPath(Path: getCurrentDirname()), Checksum: CSInfo, |
633 | Source: getSource(SM, FID: SM.getMainFileID())); |
634 | |
635 | StringRef Sysroot, SDK; |
636 | if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) { |
637 | Sysroot = CGM.getHeaderSearchOpts().Sysroot; |
638 | auto B = llvm::sys::path::rbegin(path: Sysroot); |
639 | auto E = llvm::sys::path::rend(path: Sysroot); |
640 | auto It = |
641 | std::find_if(first: B, last: E, pred: [](auto SDK) { return SDK.ends_with(".sdk" ); }); |
642 | if (It != E) |
643 | SDK = *It; |
644 | } |
645 | |
646 | llvm::DICompileUnit::DebugNameTableKind NameTableKind = |
647 | static_cast<llvm::DICompileUnit::DebugNameTableKind>( |
648 | CGOpts.DebugNameTable); |
649 | if (CGM.getTarget().getTriple().isNVPTX()) |
650 | NameTableKind = llvm::DICompileUnit::DebugNameTableKind::None; |
651 | else if (CGM.getTarget().getTriple().getVendor() == llvm::Triple::Apple) |
652 | NameTableKind = llvm::DICompileUnit::DebugNameTableKind::Apple; |
653 | |
654 | // Create new compile unit. |
655 | TheCU = DBuilder.createCompileUnit( |
656 | Lang: LangTag, File: CUFile, Producer: CGOpts.EmitVersionIdentMetadata ? Producer : "" , |
657 | isOptimized: LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO, |
658 | Flags: CGOpts.DwarfDebugFlags, RV: RuntimeVers, SplitName: CGOpts.SplitDwarfFile, Kind: EmissionKind, |
659 | DWOId: DwoId, SplitDebugInlining: CGOpts.SplitDwarfInlining, DebugInfoForProfiling: CGOpts.DebugInfoForProfiling, |
660 | NameTableKind, RangesBaseAddress: CGOpts.DebugRangesBaseAddress, SysRoot: remapDIPath(Path: Sysroot), SDK); |
661 | } |
662 | |
663 | llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) { |
664 | llvm::dwarf::TypeKind Encoding; |
665 | StringRef BTName; |
666 | switch (BT->getKind()) { |
667 | #define BUILTIN_TYPE(Id, SingletonId) |
668 | #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id: |
669 | #include "clang/AST/BuiltinTypes.def" |
670 | case BuiltinType::Dependent: |
671 | llvm_unreachable("Unexpected builtin type" ); |
672 | case BuiltinType::NullPtr: |
673 | return DBuilder.createNullPtrType(); |
674 | case BuiltinType::Void: |
675 | return nullptr; |
676 | case BuiltinType::ObjCClass: |
677 | if (!ClassTy) |
678 | ClassTy = |
679 | DBuilder.createForwardDecl(Tag: llvm::dwarf::DW_TAG_structure_type, |
680 | Name: "objc_class" , Scope: TheCU, F: TheCU->getFile(), Line: 0); |
681 | return ClassTy; |
682 | case BuiltinType::ObjCId: { |
683 | // typedef struct objc_class *Class; |
684 | // typedef struct objc_object { |
685 | // Class isa; |
686 | // } *id; |
687 | |
688 | if (ObjTy) |
689 | return ObjTy; |
690 | |
691 | if (!ClassTy) |
692 | ClassTy = |
693 | DBuilder.createForwardDecl(Tag: llvm::dwarf::DW_TAG_structure_type, |
694 | Name: "objc_class" , Scope: TheCU, F: TheCU->getFile(), Line: 0); |
695 | |
696 | unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); |
697 | |
698 | auto *ISATy = DBuilder.createPointerType(PointeeTy: ClassTy, SizeInBits: Size); |
699 | |
700 | ObjTy = DBuilder.createStructType(Scope: TheCU, Name: "objc_object" , File: TheCU->getFile(), LineNumber: 0, |
701 | SizeInBits: 0, AlignInBits: 0, Flags: llvm::DINode::FlagZero, DerivedFrom: nullptr, |
702 | Elements: llvm::DINodeArray()); |
703 | |
704 | DBuilder.replaceArrays( |
705 | T&: ObjTy, Elements: DBuilder.getOrCreateArray(Elements: &*DBuilder.createMemberType( |
706 | Scope: ObjTy, Name: "isa" , File: TheCU->getFile(), LineNo: 0, SizeInBits: Size, AlignInBits: 0, OffsetInBits: 0, |
707 | Flags: llvm::DINode::FlagZero, Ty: ISATy))); |
708 | return ObjTy; |
709 | } |
710 | case BuiltinType::ObjCSel: { |
711 | if (!SelTy) |
712 | SelTy = DBuilder.createForwardDecl(Tag: llvm::dwarf::DW_TAG_structure_type, |
713 | Name: "objc_selector" , Scope: TheCU, |
714 | F: TheCU->getFile(), Line: 0); |
715 | return SelTy; |
716 | } |
717 | |
718 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
719 | case BuiltinType::Id: \ |
720 | return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \ |
721 | SingletonId); |
722 | #include "clang/Basic/OpenCLImageTypes.def" |
723 | case BuiltinType::OCLSampler: |
724 | return getOrCreateStructPtrType(Name: "opencl_sampler_t" , Cache&: OCLSamplerDITy); |
725 | case BuiltinType::OCLEvent: |
726 | return getOrCreateStructPtrType(Name: "opencl_event_t" , Cache&: OCLEventDITy); |
727 | case BuiltinType::OCLClkEvent: |
728 | return getOrCreateStructPtrType(Name: "opencl_clk_event_t" , Cache&: OCLClkEventDITy); |
729 | case BuiltinType::OCLQueue: |
730 | return getOrCreateStructPtrType(Name: "opencl_queue_t" , Cache&: OCLQueueDITy); |
731 | case BuiltinType::OCLReserveID: |
732 | return getOrCreateStructPtrType(Name: "opencl_reserve_id_t" , Cache&: OCLReserveIDDITy); |
733 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
734 | case BuiltinType::Id: \ |
735 | return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty); |
736 | #include "clang/Basic/OpenCLExtensionTypes.def" |
737 | |
738 | #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
739 | #include "clang/Basic/AArch64SVEACLETypes.def" |
740 | { |
741 | ASTContext::BuiltinVectorTypeInfo Info = |
742 | // For svcount_t, only the lower 2 bytes are relevant. |
743 | BT->getKind() == BuiltinType::SveCount |
744 | ? ASTContext::BuiltinVectorTypeInfo( |
745 | CGM.getContext().BoolTy, llvm::ElementCount::getFixed(MinVal: 16), |
746 | 1) |
747 | : CGM.getContext().getBuiltinVectorTypeInfo(VecTy: BT); |
748 | |
749 | // A single vector of bytes may not suffice as the representation of |
750 | // svcount_t tuples because of the gap between the active 16bits of |
751 | // successive tuple members. Currently no such tuples are defined for |
752 | // svcount_t, so assert that NumVectors is 1. |
753 | assert((BT->getKind() != BuiltinType::SveCount || Info.NumVectors == 1) && |
754 | "Unsupported number of vectors for svcount_t" ); |
755 | |
756 | // Debuggers can't extract 1bit from a vector, so will display a |
757 | // bitpattern for predicates instead. |
758 | unsigned NumElems = Info.EC.getKnownMinValue() * Info.NumVectors; |
759 | if (Info.ElementType == CGM.getContext().BoolTy) { |
760 | NumElems /= 8; |
761 | Info.ElementType = CGM.getContext().UnsignedCharTy; |
762 | } |
763 | |
764 | llvm::Metadata *LowerBound, *UpperBound; |
765 | LowerBound = llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::getSigned( |
766 | Ty: llvm::Type::getInt64Ty(C&: CGM.getLLVMContext()), V: 0)); |
767 | if (Info.EC.isScalable()) { |
768 | unsigned NumElemsPerVG = NumElems / 2; |
769 | SmallVector<uint64_t, 9> Expr( |
770 | {llvm::dwarf::DW_OP_constu, NumElemsPerVG, llvm::dwarf::DW_OP_bregx, |
771 | /* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul, |
772 | llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus}); |
773 | UpperBound = DBuilder.createExpression(Addr: Expr); |
774 | } else |
775 | UpperBound = llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::getSigned( |
776 | Ty: llvm::Type::getInt64Ty(C&: CGM.getLLVMContext()), V: NumElems - 1)); |
777 | |
778 | llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange( |
779 | /*count*/ Count: nullptr, LowerBound, UpperBound, /*stride*/ Stride: nullptr); |
780 | llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Elements: Subscript); |
781 | llvm::DIType *ElemTy = |
782 | getOrCreateType(Ty: Info.ElementType, Fg: TheCU->getFile()); |
783 | auto Align = getTypeAlignIfRequired(BT, CGM.getContext()); |
784 | return DBuilder.createVectorType(/*Size*/ 0, AlignInBits: Align, Ty: ElemTy, |
785 | Subscripts: SubscriptArray); |
786 | } |
787 | // It doesn't make sense to generate debug info for PowerPC MMA vector types. |
788 | // So we return a safe type here to avoid generating an error. |
789 | #define PPC_VECTOR_TYPE(Name, Id, size) \ |
790 | case BuiltinType::Id: |
791 | #include "clang/Basic/PPCTypes.def" |
792 | return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy)); |
793 | |
794 | #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: |
795 | #include "clang/Basic/RISCVVTypes.def" |
796 | { |
797 | ASTContext::BuiltinVectorTypeInfo Info = |
798 | CGM.getContext().getBuiltinVectorTypeInfo(VecTy: BT); |
799 | |
800 | unsigned ElementCount = Info.EC.getKnownMinValue(); |
801 | unsigned SEW = CGM.getContext().getTypeSize(Info.ElementType); |
802 | |
803 | bool Fractional = false; |
804 | unsigned LMUL; |
805 | unsigned FixedSize = ElementCount * SEW; |
806 | if (Info.ElementType == CGM.getContext().BoolTy) { |
807 | // Mask type only occupies one vector register. |
808 | LMUL = 1; |
809 | } else if (FixedSize < 64) { |
810 | // In RVV scalable vector types, we encode 64 bits in the fixed part. |
811 | Fractional = true; |
812 | LMUL = 64 / FixedSize; |
813 | } else { |
814 | LMUL = FixedSize / 64; |
815 | } |
816 | |
817 | // Element count = (VLENB / SEW) x LMUL |
818 | SmallVector<uint64_t, 12> Expr( |
819 | // The DW_OP_bregx operation has two operands: a register which is |
820 | // specified by an unsigned LEB128 number, followed by a signed LEB128 |
821 | // offset. |
822 | {llvm::dwarf::DW_OP_bregx, // Read the contents of a register. |
823 | 4096 + 0xC22, // RISC-V VLENB CSR register. |
824 | 0, // Offset for DW_OP_bregx. It is dummy here. |
825 | llvm::dwarf::DW_OP_constu, |
826 | SEW / 8, // SEW is in bits. |
827 | llvm::dwarf::DW_OP_div, llvm::dwarf::DW_OP_constu, LMUL}); |
828 | if (Fractional) |
829 | Expr.push_back(Elt: llvm::dwarf::DW_OP_div); |
830 | else |
831 | Expr.push_back(Elt: llvm::dwarf::DW_OP_mul); |
832 | // Element max index = count - 1 |
833 | Expr.append(IL: {llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus}); |
834 | |
835 | auto *LowerBound = |
836 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::getSigned( |
837 | Ty: llvm::Type::getInt64Ty(C&: CGM.getLLVMContext()), V: 0)); |
838 | auto *UpperBound = DBuilder.createExpression(Addr: Expr); |
839 | llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange( |
840 | /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr); |
841 | llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Elements: Subscript); |
842 | llvm::DIType *ElemTy = |
843 | getOrCreateType(Ty: Info.ElementType, Fg: TheCU->getFile()); |
844 | |
845 | auto Align = getTypeAlignIfRequired(BT, CGM.getContext()); |
846 | return DBuilder.createVectorType(/*Size=*/0, AlignInBits: Align, Ty: ElemTy, |
847 | Subscripts: SubscriptArray); |
848 | } |
849 | |
850 | #define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \ |
851 | case BuiltinType::Id: { \ |
852 | if (!SingletonId) \ |
853 | SingletonId = \ |
854 | DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, \ |
855 | MangledName, TheCU, TheCU->getFile(), 0); \ |
856 | return SingletonId; \ |
857 | } |
858 | #include "clang/Basic/WebAssemblyReferenceTypes.def" |
859 | |
860 | case BuiltinType::UChar: |
861 | case BuiltinType::Char_U: |
862 | Encoding = llvm::dwarf::DW_ATE_unsigned_char; |
863 | break; |
864 | case BuiltinType::Char_S: |
865 | case BuiltinType::SChar: |
866 | Encoding = llvm::dwarf::DW_ATE_signed_char; |
867 | break; |
868 | case BuiltinType::Char8: |
869 | case BuiltinType::Char16: |
870 | case BuiltinType::Char32: |
871 | Encoding = llvm::dwarf::DW_ATE_UTF; |
872 | break; |
873 | case BuiltinType::UShort: |
874 | case BuiltinType::UInt: |
875 | case BuiltinType::UInt128: |
876 | case BuiltinType::ULong: |
877 | case BuiltinType::WChar_U: |
878 | case BuiltinType::ULongLong: |
879 | Encoding = llvm::dwarf::DW_ATE_unsigned; |
880 | break; |
881 | case BuiltinType::Short: |
882 | case BuiltinType::Int: |
883 | case BuiltinType::Int128: |
884 | case BuiltinType::Long: |
885 | case BuiltinType::WChar_S: |
886 | case BuiltinType::LongLong: |
887 | Encoding = llvm::dwarf::DW_ATE_signed; |
888 | break; |
889 | case BuiltinType::Bool: |
890 | Encoding = llvm::dwarf::DW_ATE_boolean; |
891 | break; |
892 | case BuiltinType::Half: |
893 | case BuiltinType::Float: |
894 | case BuiltinType::LongDouble: |
895 | case BuiltinType::Float16: |
896 | case BuiltinType::BFloat16: |
897 | case BuiltinType::Float128: |
898 | case BuiltinType::Double: |
899 | case BuiltinType::Ibm128: |
900 | // FIXME: For targets where long double, __ibm128 and __float128 have the |
901 | // same size, they are currently indistinguishable in the debugger without |
902 | // some special treatment. However, there is currently no consensus on |
903 | // encoding and this should be updated once a DWARF encoding exists for |
904 | // distinct floating point types of the same size. |
905 | Encoding = llvm::dwarf::DW_ATE_float; |
906 | break; |
907 | case BuiltinType::ShortAccum: |
908 | case BuiltinType::Accum: |
909 | case BuiltinType::LongAccum: |
910 | case BuiltinType::ShortFract: |
911 | case BuiltinType::Fract: |
912 | case BuiltinType::LongFract: |
913 | case BuiltinType::SatShortFract: |
914 | case BuiltinType::SatFract: |
915 | case BuiltinType::SatLongFract: |
916 | case BuiltinType::SatShortAccum: |
917 | case BuiltinType::SatAccum: |
918 | case BuiltinType::SatLongAccum: |
919 | Encoding = llvm::dwarf::DW_ATE_signed_fixed; |
920 | break; |
921 | case BuiltinType::UShortAccum: |
922 | case BuiltinType::UAccum: |
923 | case BuiltinType::ULongAccum: |
924 | case BuiltinType::UShortFract: |
925 | case BuiltinType::UFract: |
926 | case BuiltinType::ULongFract: |
927 | case BuiltinType::SatUShortAccum: |
928 | case BuiltinType::SatUAccum: |
929 | case BuiltinType::SatULongAccum: |
930 | case BuiltinType::SatUShortFract: |
931 | case BuiltinType::SatUFract: |
932 | case BuiltinType::SatULongFract: |
933 | Encoding = llvm::dwarf::DW_ATE_unsigned_fixed; |
934 | break; |
935 | } |
936 | |
937 | BTName = BT->getName(Policy: CGM.getLangOpts()); |
938 | // Bit size and offset of the type. |
939 | uint64_t Size = CGM.getContext().getTypeSize(BT); |
940 | return DBuilder.createBasicType(Name: BTName, SizeInBits: Size, Encoding); |
941 | } |
942 | |
943 | llvm::DIType *CGDebugInfo::CreateType(const BitIntType *Ty) { |
944 | |
945 | StringRef Name = Ty->isUnsigned() ? "unsigned _BitInt" : "_BitInt" ; |
946 | llvm::dwarf::TypeKind Encoding = Ty->isUnsigned() |
947 | ? llvm::dwarf::DW_ATE_unsigned |
948 | : llvm::dwarf::DW_ATE_signed; |
949 | |
950 | return DBuilder.createBasicType(Name, SizeInBits: CGM.getContext().getTypeSize(Ty), |
951 | Encoding); |
952 | } |
953 | |
954 | llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) { |
955 | // Bit size and offset of the type. |
956 | llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float; |
957 | if (Ty->isComplexIntegerType()) |
958 | Encoding = llvm::dwarf::DW_ATE_lo_user; |
959 | |
960 | uint64_t Size = CGM.getContext().getTypeSize(Ty); |
961 | return DBuilder.createBasicType(Name: "complex" , SizeInBits: Size, Encoding); |
962 | } |
963 | |
964 | static void stripUnusedQualifiers(Qualifiers &Q) { |
965 | // Ignore these qualifiers for now. |
966 | Q.removeObjCGCAttr(); |
967 | Q.removeAddressSpace(); |
968 | Q.removeObjCLifetime(); |
969 | Q.removeUnaligned(); |
970 | } |
971 | |
972 | static llvm::dwarf::Tag getNextQualifier(Qualifiers &Q) { |
973 | if (Q.hasConst()) { |
974 | Q.removeConst(); |
975 | return llvm::dwarf::DW_TAG_const_type; |
976 | } |
977 | if (Q.hasVolatile()) { |
978 | Q.removeVolatile(); |
979 | return llvm::dwarf::DW_TAG_volatile_type; |
980 | } |
981 | if (Q.hasRestrict()) { |
982 | Q.removeRestrict(); |
983 | return llvm::dwarf::DW_TAG_restrict_type; |
984 | } |
985 | return (llvm::dwarf::Tag)0; |
986 | } |
987 | |
988 | llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty, |
989 | llvm::DIFile *Unit) { |
990 | QualifierCollector Qc; |
991 | const Type *T = Qc.strip(type: Ty); |
992 | |
993 | stripUnusedQualifiers(Q&: Qc); |
994 | |
995 | // We will create one Derived type for one qualifier and recurse to handle any |
996 | // additional ones. |
997 | llvm::dwarf::Tag Tag = getNextQualifier(Q&: Qc); |
998 | if (!Tag) { |
999 | assert(Qc.empty() && "Unknown type qualifier for debug info" ); |
1000 | return getOrCreateType(Ty: QualType(T, 0), Fg: Unit); |
1001 | } |
1002 | |
1003 | auto *FromTy = getOrCreateType(Ty: Qc.apply(Context: CGM.getContext(), T), Fg: Unit); |
1004 | |
1005 | // No need to fill in the Name, Line, Size, Alignment, Offset in case of |
1006 | // CVR derived types. |
1007 | return DBuilder.createQualifiedType(Tag, FromTy); |
1008 | } |
1009 | |
1010 | llvm::DIType *CGDebugInfo::CreateQualifiedType(const FunctionProtoType *F, |
1011 | llvm::DIFile *Unit) { |
1012 | FunctionProtoType::ExtProtoInfo EPI = F->getExtProtoInfo(); |
1013 | Qualifiers &Q = EPI.TypeQuals; |
1014 | stripUnusedQualifiers(Q); |
1015 | |
1016 | // We will create one Derived type for one qualifier and recurse to handle any |
1017 | // additional ones. |
1018 | llvm::dwarf::Tag Tag = getNextQualifier(Q); |
1019 | if (!Tag) { |
1020 | assert(Q.empty() && "Unknown type qualifier for debug info" ); |
1021 | return nullptr; |
1022 | } |
1023 | |
1024 | auto *FromTy = |
1025 | getOrCreateType(Ty: CGM.getContext().getFunctionType(ResultTy: F->getReturnType(), |
1026 | Args: F->getParamTypes(), EPI), |
1027 | Fg: Unit); |
1028 | |
1029 | // No need to fill in the Name, Line, Size, Alignment, Offset in case of |
1030 | // CVR derived types. |
1031 | return DBuilder.createQualifiedType(Tag, FromTy: FromTy); |
1032 | } |
1033 | |
1034 | llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty, |
1035 | llvm::DIFile *Unit) { |
1036 | |
1037 | // The frontend treats 'id' as a typedef to an ObjCObjectType, |
1038 | // whereas 'id<protocol>' is treated as an ObjCPointerType. For the |
1039 | // debug info, we want to emit 'id' in both cases. |
1040 | if (Ty->isObjCQualifiedIdType()) |
1041 | return getOrCreateType(Ty: CGM.getContext().getObjCIdType(), Fg: Unit); |
1042 | |
1043 | return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, |
1044 | Ty->getPointeeType(), Unit); |
1045 | } |
1046 | |
1047 | llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty, |
1048 | llvm::DIFile *Unit) { |
1049 | return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty, |
1050 | Ty->getPointeeType(), Unit); |
1051 | } |
1052 | |
1053 | /// \return whether a C++ mangling exists for the type defined by TD. |
1054 | static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) { |
1055 | switch (TheCU->getSourceLanguage()) { |
1056 | case llvm::dwarf::DW_LANG_C_plus_plus: |
1057 | case llvm::dwarf::DW_LANG_C_plus_plus_11: |
1058 | case llvm::dwarf::DW_LANG_C_plus_plus_14: |
1059 | return true; |
1060 | case llvm::dwarf::DW_LANG_ObjC_plus_plus: |
1061 | return isa<CXXRecordDecl>(Val: TD) || isa<EnumDecl>(Val: TD); |
1062 | default: |
1063 | return false; |
1064 | } |
1065 | } |
1066 | |
1067 | // Determines if the debug info for this tag declaration needs a type |
1068 | // identifier. The purpose of the unique identifier is to deduplicate type |
1069 | // information for identical types across TUs. Because of the C++ one definition |
1070 | // rule (ODR), it is valid to assume that the type is defined the same way in |
1071 | // every TU and its debug info is equivalent. |
1072 | // |
1073 | // C does not have the ODR, and it is common for codebases to contain multiple |
1074 | // different definitions of a struct with the same name in different TUs. |
1075 | // Therefore, if the type doesn't have a C++ mangling, don't give it an |
1076 | // identifer. Type information in C is smaller and simpler than C++ type |
1077 | // information, so the increase in debug info size is negligible. |
1078 | // |
1079 | // If the type is not externally visible, it should be unique to the current TU, |
1080 | // and should not need an identifier to participate in type deduplication. |
1081 | // However, when emitting CodeView, the format internally uses these |
1082 | // unique type name identifers for references between debug info. For example, |
1083 | // the method of a class in an anonymous namespace uses the identifer to refer |
1084 | // to its parent class. The Microsoft C++ ABI attempts to provide unique names |
1085 | // for such types, so when emitting CodeView, always use identifiers for C++ |
1086 | // types. This may create problems when attempting to emit CodeView when the MS |
1087 | // C++ ABI is not in use. |
1088 | static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM, |
1089 | llvm::DICompileUnit *TheCU) { |
1090 | // We only add a type identifier for types with C++ name mangling. |
1091 | if (!hasCXXMangling(TD, TheCU)) |
1092 | return false; |
1093 | |
1094 | // Externally visible types with C++ mangling need a type identifier. |
1095 | if (TD->isExternallyVisible()) |
1096 | return true; |
1097 | |
1098 | // CodeView types with C++ mangling need a type identifier. |
1099 | if (CGM.getCodeGenOpts().EmitCodeView) |
1100 | return true; |
1101 | |
1102 | return false; |
1103 | } |
1104 | |
1105 | // Returns a unique type identifier string if one exists, or an empty string. |
1106 | static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM, |
1107 | llvm::DICompileUnit *TheCU) { |
1108 | SmallString<256> Identifier; |
1109 | const TagDecl *TD = Ty->getDecl(); |
1110 | |
1111 | if (!needsTypeIdentifier(TD, CGM, TheCU)) |
1112 | return Identifier; |
1113 | if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: TD)) |
1114 | if (RD->getDefinition()) |
1115 | if (RD->isDynamicClass() && |
1116 | CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage) |
1117 | return Identifier; |
1118 | |
1119 | // TODO: This is using the RTTI name. Is there a better way to get |
1120 | // a unique string for a type? |
1121 | llvm::raw_svector_ostream Out(Identifier); |
1122 | CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(T: QualType(Ty, 0), Out); |
1123 | return Identifier; |
1124 | } |
1125 | |
1126 | /// \return the appropriate DWARF tag for a composite type. |
1127 | static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) { |
1128 | llvm::dwarf::Tag Tag; |
1129 | if (RD->isStruct() || RD->isInterface()) |
1130 | Tag = llvm::dwarf::DW_TAG_structure_type; |
1131 | else if (RD->isUnion()) |
1132 | Tag = llvm::dwarf::DW_TAG_union_type; |
1133 | else { |
1134 | // FIXME: This could be a struct type giving a default visibility different |
1135 | // than C++ class type, but needs llvm metadata changes first. |
1136 | assert(RD->isClass()); |
1137 | Tag = llvm::dwarf::DW_TAG_class_type; |
1138 | } |
1139 | return Tag; |
1140 | } |
1141 | |
1142 | llvm::DICompositeType * |
1143 | CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty, |
1144 | llvm::DIScope *Ctx) { |
1145 | const RecordDecl *RD = Ty->getDecl(); |
1146 | if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(Decl: RD))) |
1147 | return cast<llvm::DICompositeType>(Val: T); |
1148 | llvm::DIFile *DefUnit = getOrCreateFile(Loc: RD->getLocation()); |
1149 | const unsigned Line = |
1150 | getLineNumber(Loc: RD->getLocation().isValid() ? RD->getLocation() : CurLoc); |
1151 | StringRef RDName = getClassName(RD); |
1152 | |
1153 | uint64_t Size = 0; |
1154 | uint32_t Align = 0; |
1155 | |
1156 | const RecordDecl *D = RD->getDefinition(); |
1157 | if (D && D->isCompleteDefinition()) |
1158 | Size = CGM.getContext().getTypeSize(Ty); |
1159 | |
1160 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl; |
1161 | |
1162 | // Add flag to nontrivial forward declarations. To be consistent with MSVC, |
1163 | // add the flag if a record has no definition because we don't know whether |
1164 | // it will be trivial or not. |
1165 | if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) |
1166 | if (!CXXRD->hasDefinition() || |
1167 | (CXXRD->hasDefinition() && !CXXRD->isTrivial())) |
1168 | Flags |= llvm::DINode::FlagNonTrivial; |
1169 | |
1170 | // Create the type. |
1171 | SmallString<256> Identifier; |
1172 | // Don't include a linkage name in line tables only. |
1173 | if (CGM.getCodeGenOpts().hasReducedDebugInfo()) |
1174 | Identifier = getTypeIdentifier(Ty, CGM, TheCU); |
1175 | llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType( |
1176 | Tag: getTagForRecord(RD), Name: RDName, Scope: Ctx, F: DefUnit, Line, RuntimeLang: 0, SizeInBits: Size, AlignInBits: Align, Flags, |
1177 | UniqueIdentifier: Identifier); |
1178 | if (CGM.getCodeGenOpts().DebugFwdTemplateParams) |
1179 | if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD)) |
1180 | DBuilder.replaceArrays(T&: RetTy, Elements: llvm::DINodeArray(), |
1181 | TParams: CollectCXXTemplateParams(TSpecial, DefUnit)); |
1182 | ReplaceMap.emplace_back( |
1183 | args: std::piecewise_construct, args: std::make_tuple(args&: Ty), |
1184 | args: std::make_tuple(args: static_cast<llvm::Metadata *>(RetTy))); |
1185 | return RetTy; |
1186 | } |
1187 | |
1188 | llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag, |
1189 | const Type *Ty, |
1190 | QualType PointeeTy, |
1191 | llvm::DIFile *Unit) { |
1192 | // Bit size, align and offset of the type. |
1193 | // Size is always the size of a pointer. |
1194 | uint64_t Size = CGM.getContext().getTypeSize(T: Ty); |
1195 | auto Align = getTypeAlignIfRequired(Ty, Ctx: CGM.getContext()); |
1196 | std::optional<unsigned> DWARFAddressSpace = |
1197 | CGM.getTarget().getDWARFAddressSpace( |
1198 | AddressSpace: CGM.getTypes().getTargetAddressSpace(T: PointeeTy)); |
1199 | |
1200 | SmallVector<llvm::Metadata *, 4> Annots; |
1201 | auto *BTFAttrTy = dyn_cast<BTFTagAttributedType>(Val&: PointeeTy); |
1202 | while (BTFAttrTy) { |
1203 | StringRef Tag = BTFAttrTy->getAttr()->getBTFTypeTag(); |
1204 | if (!Tag.empty()) { |
1205 | llvm::Metadata *Ops[2] = { |
1206 | llvm::MDString::get(Context&: CGM.getLLVMContext(), Str: StringRef("btf_type_tag" )), |
1207 | llvm::MDString::get(Context&: CGM.getLLVMContext(), Str: Tag)}; |
1208 | Annots.insert(I: Annots.begin(), |
1209 | Elt: llvm::MDNode::get(Context&: CGM.getLLVMContext(), MDs: Ops)); |
1210 | } |
1211 | BTFAttrTy = dyn_cast<BTFTagAttributedType>(Val: BTFAttrTy->getWrappedType()); |
1212 | } |
1213 | |
1214 | llvm::DINodeArray Annotations = nullptr; |
1215 | if (Annots.size() > 0) |
1216 | Annotations = DBuilder.getOrCreateArray(Elements: Annots); |
1217 | |
1218 | if (Tag == llvm::dwarf::DW_TAG_reference_type || |
1219 | Tag == llvm::dwarf::DW_TAG_rvalue_reference_type) |
1220 | return DBuilder.createReferenceType(Tag, RTy: getOrCreateType(Ty: PointeeTy, Fg: Unit), |
1221 | SizeInBits: Size, AlignInBits: Align, DWARFAddressSpace); |
1222 | else |
1223 | return DBuilder.createPointerType(PointeeTy: getOrCreateType(Ty: PointeeTy, Fg: Unit), SizeInBits: Size, |
1224 | AlignInBits: Align, DWARFAddressSpace, Name: StringRef(), |
1225 | Annotations); |
1226 | } |
1227 | |
1228 | llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name, |
1229 | llvm::DIType *&Cache) { |
1230 | if (Cache) |
1231 | return Cache; |
1232 | Cache = DBuilder.createForwardDecl(Tag: llvm::dwarf::DW_TAG_structure_type, Name, |
1233 | Scope: TheCU, F: TheCU->getFile(), Line: 0); |
1234 | unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); |
1235 | Cache = DBuilder.createPointerType(PointeeTy: Cache, SizeInBits: Size); |
1236 | return Cache; |
1237 | } |
1238 | |
1239 | uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer( |
1240 | const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy, |
1241 | unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) { |
1242 | QualType FType; |
1243 | |
1244 | // Advanced by calls to CreateMemberType in increments of FType, then |
1245 | // returned as the overall size of the default elements. |
1246 | uint64_t FieldOffset = 0; |
1247 | |
1248 | // Blocks in OpenCL have unique constraints which make the standard fields |
1249 | // redundant while requiring size and align fields for enqueue_kernel. See |
1250 | // initializeForBlockHeader in CGBlocks.cpp |
1251 | if (CGM.getLangOpts().OpenCL) { |
1252 | FType = CGM.getContext().IntTy; |
1253 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__size" , Offset: &FieldOffset)); |
1254 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__align" , Offset: &FieldOffset)); |
1255 | } else { |
1256 | FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); |
1257 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__isa" , Offset: &FieldOffset)); |
1258 | FType = CGM.getContext().IntTy; |
1259 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__flags" , Offset: &FieldOffset)); |
1260 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__reserved" , Offset: &FieldOffset)); |
1261 | FType = CGM.getContext().getPointerType(T: Ty->getPointeeType()); |
1262 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__FuncPtr" , Offset: &FieldOffset)); |
1263 | FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); |
1264 | uint64_t FieldSize = CGM.getContext().getTypeSize(Ty); |
1265 | uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty); |
1266 | EltTys.push_back(Elt: DBuilder.createMemberType( |
1267 | Scope: Unit, Name: "__descriptor" , File: nullptr, LineNo, SizeInBits: FieldSize, AlignInBits: FieldAlign, |
1268 | OffsetInBits: FieldOffset, Flags: llvm::DINode::FlagZero, Ty: DescTy)); |
1269 | FieldOffset += FieldSize; |
1270 | } |
1271 | |
1272 | return FieldOffset; |
1273 | } |
1274 | |
1275 | llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty, |
1276 | llvm::DIFile *Unit) { |
1277 | SmallVector<llvm::Metadata *, 8> EltTys; |
1278 | QualType FType; |
1279 | uint64_t FieldOffset; |
1280 | llvm::DINodeArray Elements; |
1281 | |
1282 | FieldOffset = 0; |
1283 | FType = CGM.getContext().UnsignedLongTy; |
1284 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "reserved" , Offset: &FieldOffset)); |
1285 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "Size" , Offset: &FieldOffset)); |
1286 | |
1287 | Elements = DBuilder.getOrCreateArray(Elements: EltTys); |
1288 | EltTys.clear(); |
1289 | |
1290 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock; |
1291 | |
1292 | auto *EltTy = |
1293 | DBuilder.createStructType(Scope: Unit, Name: "__block_descriptor" , File: nullptr, LineNumber: 0, |
1294 | SizeInBits: FieldOffset, AlignInBits: 0, Flags, DerivedFrom: nullptr, Elements); |
1295 | |
1296 | // Bit size, align and offset of the type. |
1297 | uint64_t Size = CGM.getContext().getTypeSize(Ty); |
1298 | |
1299 | auto *DescTy = DBuilder.createPointerType(PointeeTy: EltTy, SizeInBits: Size); |
1300 | |
1301 | FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy: DescTy, |
1302 | LineNo: 0, EltTys); |
1303 | |
1304 | Elements = DBuilder.getOrCreateArray(Elements: EltTys); |
1305 | |
1306 | // The __block_literal_generic structs are marked with a special |
1307 | // DW_AT_APPLE_BLOCK attribute and are an implementation detail only |
1308 | // the debugger needs to know about. To allow type uniquing, emit |
1309 | // them without a name or a location. |
1310 | EltTy = DBuilder.createStructType(Scope: Unit, Name: "" , File: nullptr, LineNumber: 0, SizeInBits: FieldOffset, AlignInBits: 0, |
1311 | Flags, DerivedFrom: nullptr, Elements); |
1312 | |
1313 | return DBuilder.createPointerType(PointeeTy: EltTy, SizeInBits: Size); |
1314 | } |
1315 | |
1316 | static llvm::SmallVector<TemplateArgument> |
1317 | GetTemplateArgs(const TemplateDecl *TD, const TemplateSpecializationType *Ty) { |
1318 | assert(Ty->isTypeAlias()); |
1319 | // TemplateSpecializationType doesn't know if its template args are |
1320 | // being substituted into a parameter pack. We can find out if that's |
1321 | // the case now by inspecting the TypeAliasTemplateDecl template |
1322 | // parameters. Insert Ty's template args into SpecArgs, bundling args |
1323 | // passed to a parameter pack into a TemplateArgument::Pack. It also |
1324 | // doesn't know the value of any defaulted args, so collect those now |
1325 | // too. |
1326 | SmallVector<TemplateArgument> SpecArgs; |
1327 | ArrayRef SubstArgs = Ty->template_arguments(); |
1328 | for (const NamedDecl *Param : TD->getTemplateParameters()->asArray()) { |
1329 | // If Param is a parameter pack, pack the remaining arguments. |
1330 | if (Param->isParameterPack()) { |
1331 | SpecArgs.push_back(Elt: TemplateArgument(SubstArgs)); |
1332 | break; |
1333 | } |
1334 | |
1335 | // Skip defaulted args. |
1336 | // FIXME: Ideally, we wouldn't do this. We can read the default values |
1337 | // for each parameter. However, defaulted arguments which are dependent |
1338 | // values or dependent types can't (easily?) be resolved here. |
1339 | if (SubstArgs.empty()) { |
1340 | // If SubstArgs is now empty (we're taking from it each iteration) and |
1341 | // this template parameter isn't a pack, then that should mean we're |
1342 | // using default values for the remaining template parameters (after |
1343 | // which there may be an empty pack too which we will ignore). |
1344 | break; |
1345 | } |
1346 | |
1347 | // Take the next argument. |
1348 | SpecArgs.push_back(Elt: SubstArgs.front()); |
1349 | SubstArgs = SubstArgs.drop_front(); |
1350 | } |
1351 | return SpecArgs; |
1352 | } |
1353 | |
1354 | llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty, |
1355 | llvm::DIFile *Unit) { |
1356 | assert(Ty->isTypeAlias()); |
1357 | llvm::DIType *Src = getOrCreateType(Ty: Ty->getAliasedType(), Fg: Unit); |
1358 | |
1359 | const TemplateDecl *TD = Ty->getTemplateName().getAsTemplateDecl(); |
1360 | if (isa<BuiltinTemplateDecl>(Val: TD)) |
1361 | return Src; |
1362 | |
1363 | const auto *AliasDecl = cast<TypeAliasTemplateDecl>(Val: TD)->getTemplatedDecl(); |
1364 | if (AliasDecl->hasAttr<NoDebugAttr>()) |
1365 | return Src; |
1366 | |
1367 | SmallString<128> NS; |
1368 | llvm::raw_svector_ostream OS(NS); |
1369 | |
1370 | auto PP = getPrintingPolicy(); |
1371 | Ty->getTemplateName().print(OS, Policy: PP, Qual: TemplateName::Qualified::None); |
1372 | |
1373 | SourceLocation Loc = AliasDecl->getLocation(); |
1374 | |
1375 | if (CGM.getCodeGenOpts().DebugTemplateAlias) { |
1376 | auto ArgVector = ::GetTemplateArgs(TD, Ty); |
1377 | TemplateArgs Args = {.TList: TD->getTemplateParameters(), .Args: ArgVector}; |
1378 | |
1379 | // FIXME: Respect DebugTemplateNameKind::Mangled, e.g. by using GetName. |
1380 | // Note we can't use GetName without additional work: TypeAliasTemplateDecl |
1381 | // doesn't have instantiation information, so |
1382 | // TypeAliasTemplateDecl::getNameForDiagnostic wouldn't have access to the |
1383 | // template args. |
1384 | std::string Name; |
1385 | llvm::raw_string_ostream OS(Name); |
1386 | TD->getNameForDiagnostic(OS, PP, /*Qualified=*/false); |
1387 | if (CGM.getCodeGenOpts().getDebugSimpleTemplateNames() != |
1388 | llvm::codegenoptions::DebugTemplateNamesKind::Simple || |
1389 | !HasReconstitutableArgs(Args: Args.Args)) |
1390 | printTemplateArgumentList(OS, Args: Args.Args, Policy: PP); |
1391 | |
1392 | llvm::DIDerivedType *AliasTy = DBuilder.createTemplateAlias( |
1393 | Ty: Src, Name, File: getOrCreateFile(Loc), LineNo: getLineNumber(Loc), |
1394 | Context: getDeclContextDescriptor(AliasDecl), TParams: CollectTemplateParams(Args, Unit)); |
1395 | return AliasTy; |
1396 | } |
1397 | |
1398 | // Disable PrintCanonicalTypes here because we want |
1399 | // the DW_AT_name to benefit from the TypePrinter's ability |
1400 | // to skip defaulted template arguments. |
1401 | // |
1402 | // FIXME: Once -gsimple-template-names is enabled by default |
1403 | // and we attach template parameters to alias template DIEs |
1404 | // we don't need to worry about customizing the PrintingPolicy |
1405 | // here anymore. |
1406 | PP.PrintCanonicalTypes = false; |
1407 | printTemplateArgumentList(OS, Args: Ty->template_arguments(), Policy: PP, |
1408 | TPL: TD->getTemplateParameters()); |
1409 | return DBuilder.createTypedef(Ty: Src, Name: OS.str(), File: getOrCreateFile(Loc), |
1410 | LineNo: getLineNumber(Loc), |
1411 | Context: getDeclContextDescriptor(AliasDecl)); |
1412 | } |
1413 | |
1414 | /// Convert an AccessSpecifier into the corresponding DINode flag. |
1415 | /// As an optimization, return 0 if the access specifier equals the |
1416 | /// default for the containing type. |
1417 | static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access, |
1418 | const RecordDecl *RD) { |
1419 | AccessSpecifier Default = clang::AS_none; |
1420 | if (RD && RD->isClass()) |
1421 | Default = clang::AS_private; |
1422 | else if (RD && (RD->isStruct() || RD->isUnion())) |
1423 | Default = clang::AS_public; |
1424 | |
1425 | if (Access == Default) |
1426 | return llvm::DINode::FlagZero; |
1427 | |
1428 | switch (Access) { |
1429 | case clang::AS_private: |
1430 | return llvm::DINode::FlagPrivate; |
1431 | case clang::AS_protected: |
1432 | return llvm::DINode::FlagProtected; |
1433 | case clang::AS_public: |
1434 | return llvm::DINode::FlagPublic; |
1435 | case clang::AS_none: |
1436 | return llvm::DINode::FlagZero; |
1437 | } |
1438 | llvm_unreachable("unexpected access enumerator" ); |
1439 | } |
1440 | |
1441 | llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty, |
1442 | llvm::DIFile *Unit) { |
1443 | llvm::DIType *Underlying = |
1444 | getOrCreateType(Ty: Ty->getDecl()->getUnderlyingType(), Fg: Unit); |
1445 | |
1446 | if (Ty->getDecl()->hasAttr<NoDebugAttr>()) |
1447 | return Underlying; |
1448 | |
1449 | // We don't set size information, but do specify where the typedef was |
1450 | // declared. |
1451 | SourceLocation Loc = Ty->getDecl()->getLocation(); |
1452 | |
1453 | uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext()); |
1454 | // Typedefs are derived from some other type. |
1455 | llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(Ty->getDecl()); |
1456 | |
1457 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
1458 | const DeclContext *DC = Ty->getDecl()->getDeclContext(); |
1459 | if (isa<RecordDecl>(Val: DC)) |
1460 | Flags = getAccessFlag(Ty->getDecl()->getAccess(), cast<RecordDecl>(Val: DC)); |
1461 | |
1462 | return DBuilder.createTypedef(Ty: Underlying, Name: Ty->getDecl()->getName(), |
1463 | File: getOrCreateFile(Loc), LineNo: getLineNumber(Loc), |
1464 | Context: getDeclContextDescriptor(Ty->getDecl()), AlignInBits: Align, |
1465 | Flags, Annotations); |
1466 | } |
1467 | |
1468 | static unsigned getDwarfCC(CallingConv CC) { |
1469 | switch (CC) { |
1470 | case CC_C: |
1471 | // Avoid emitting DW_AT_calling_convention if the C convention was used. |
1472 | return 0; |
1473 | |
1474 | case CC_X86StdCall: |
1475 | return llvm::dwarf::DW_CC_BORLAND_stdcall; |
1476 | case CC_X86FastCall: |
1477 | return llvm::dwarf::DW_CC_BORLAND_msfastcall; |
1478 | case CC_X86ThisCall: |
1479 | return llvm::dwarf::DW_CC_BORLAND_thiscall; |
1480 | case CC_X86VectorCall: |
1481 | return llvm::dwarf::DW_CC_LLVM_vectorcall; |
1482 | case CC_X86Pascal: |
1483 | return llvm::dwarf::DW_CC_BORLAND_pascal; |
1484 | case CC_Win64: |
1485 | return llvm::dwarf::DW_CC_LLVM_Win64; |
1486 | case CC_X86_64SysV: |
1487 | return llvm::dwarf::DW_CC_LLVM_X86_64SysV; |
1488 | case CC_AAPCS: |
1489 | case CC_AArch64VectorCall: |
1490 | case CC_AArch64SVEPCS: |
1491 | return llvm::dwarf::DW_CC_LLVM_AAPCS; |
1492 | case CC_AAPCS_VFP: |
1493 | return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP; |
1494 | case CC_IntelOclBicc: |
1495 | return llvm::dwarf::DW_CC_LLVM_IntelOclBicc; |
1496 | case CC_SpirFunction: |
1497 | return llvm::dwarf::DW_CC_LLVM_SpirFunction; |
1498 | case CC_OpenCLKernel: |
1499 | case CC_AMDGPUKernelCall: |
1500 | return llvm::dwarf::DW_CC_LLVM_OpenCLKernel; |
1501 | case CC_Swift: |
1502 | return llvm::dwarf::DW_CC_LLVM_Swift; |
1503 | case CC_SwiftAsync: |
1504 | return llvm::dwarf::DW_CC_LLVM_SwiftTail; |
1505 | case CC_PreserveMost: |
1506 | return llvm::dwarf::DW_CC_LLVM_PreserveMost; |
1507 | case CC_PreserveAll: |
1508 | return llvm::dwarf::DW_CC_LLVM_PreserveAll; |
1509 | case CC_X86RegCall: |
1510 | return llvm::dwarf::DW_CC_LLVM_X86RegCall; |
1511 | case CC_M68kRTD: |
1512 | return llvm::dwarf::DW_CC_LLVM_M68kRTD; |
1513 | case CC_PreserveNone: |
1514 | return llvm::dwarf::DW_CC_LLVM_PreserveNone; |
1515 | case CC_RISCVVectorCall: |
1516 | return llvm::dwarf::DW_CC_LLVM_RISCVVectorCall; |
1517 | } |
1518 | return 0; |
1519 | } |
1520 | |
1521 | static llvm::DINode::DIFlags getRefFlags(const FunctionProtoType *Func) { |
1522 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
1523 | if (Func->getExtProtoInfo().RefQualifier == RQ_LValue) |
1524 | Flags |= llvm::DINode::FlagLValueReference; |
1525 | if (Func->getExtProtoInfo().RefQualifier == RQ_RValue) |
1526 | Flags |= llvm::DINode::FlagRValueReference; |
1527 | return Flags; |
1528 | } |
1529 | |
1530 | llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty, |
1531 | llvm::DIFile *Unit) { |
1532 | const auto *FPT = dyn_cast<FunctionProtoType>(Val: Ty); |
1533 | if (FPT) { |
1534 | if (llvm::DIType *QTy = CreateQualifiedType(F: FPT, Unit)) |
1535 | return QTy; |
1536 | } |
1537 | |
1538 | // Create the type without any qualifiers |
1539 | |
1540 | SmallVector<llvm::Metadata *, 16> EltTys; |
1541 | |
1542 | // Add the result type at least. |
1543 | EltTys.push_back(Elt: getOrCreateType(Ty: Ty->getReturnType(), Fg: Unit)); |
1544 | |
1545 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
1546 | // Set up remainder of arguments if there is a prototype. |
1547 | // otherwise emit it as a variadic function. |
1548 | if (!FPT) { |
1549 | EltTys.push_back(Elt: DBuilder.createUnspecifiedParameter()); |
1550 | } else { |
1551 | Flags = getRefFlags(Func: FPT); |
1552 | for (const QualType &ParamType : FPT->param_types()) |
1553 | EltTys.push_back(Elt: getOrCreateType(Ty: ParamType, Fg: Unit)); |
1554 | if (FPT->isVariadic()) |
1555 | EltTys.push_back(Elt: DBuilder.createUnspecifiedParameter()); |
1556 | } |
1557 | |
1558 | llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elements: EltTys); |
1559 | llvm::DIType *F = DBuilder.createSubroutineType( |
1560 | ParameterTypes: EltTypeArray, Flags, CC: getDwarfCC(CC: Ty->getCallConv())); |
1561 | return F; |
1562 | } |
1563 | |
1564 | llvm::DIDerivedType * |
1565 | CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl, |
1566 | llvm::DIScope *RecordTy, const RecordDecl *RD) { |
1567 | StringRef Name = BitFieldDecl->getName(); |
1568 | QualType Ty = BitFieldDecl->getType(); |
1569 | if (BitFieldDecl->hasAttr<PreferredTypeAttr>()) |
1570 | Ty = BitFieldDecl->getAttr<PreferredTypeAttr>()->getType(); |
1571 | SourceLocation Loc = BitFieldDecl->getLocation(); |
1572 | llvm::DIFile *VUnit = getOrCreateFile(Loc); |
1573 | llvm::DIType *DebugType = getOrCreateType(Ty, Fg: VUnit); |
1574 | |
1575 | // Get the location for the field. |
1576 | llvm::DIFile *File = getOrCreateFile(Loc); |
1577 | unsigned Line = getLineNumber(Loc); |
1578 | |
1579 | const CGBitFieldInfo &BitFieldInfo = |
1580 | CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(FD: BitFieldDecl); |
1581 | uint64_t SizeInBits = BitFieldInfo.Size; |
1582 | assert(SizeInBits > 0 && "found named 0-width bitfield" ); |
1583 | uint64_t StorageOffsetInBits = |
1584 | CGM.getContext().toBits(CharSize: BitFieldInfo.StorageOffset); |
1585 | uint64_t Offset = BitFieldInfo.Offset; |
1586 | // The bit offsets for big endian machines are reversed for big |
1587 | // endian target, compensate for that as the DIDerivedType requires |
1588 | // un-reversed offsets. |
1589 | if (CGM.getDataLayout().isBigEndian()) |
1590 | Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset; |
1591 | uint64_t OffsetInBits = StorageOffsetInBits + Offset; |
1592 | llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD); |
1593 | llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(BitFieldDecl); |
1594 | return DBuilder.createBitFieldMemberType( |
1595 | Scope: RecordTy, Name, File, LineNo: Line, SizeInBits, OffsetInBits, StorageOffsetInBits, |
1596 | Flags, Ty: DebugType, Annotations); |
1597 | } |
1598 | |
1599 | llvm::DIDerivedType *CGDebugInfo::createBitFieldSeparatorIfNeeded( |
1600 | const FieldDecl *BitFieldDecl, const llvm::DIDerivedType *BitFieldDI, |
1601 | llvm::ArrayRef<llvm::Metadata *> PreviousFieldsDI, const RecordDecl *RD) { |
1602 | |
1603 | if (!CGM.getTargetCodeGenInfo().shouldEmitDWARFBitFieldSeparators()) |
1604 | return nullptr; |
1605 | |
1606 | /* |
1607 | Add a *single* zero-bitfield separator between two non-zero bitfields |
1608 | separated by one or more zero-bitfields. This is used to distinguish between |
1609 | structures such the ones below, where the memory layout is the same, but how |
1610 | the ABI assigns fields to registers differs. |
1611 | |
1612 | struct foo { |
1613 | int space[4]; |
1614 | char a : 8; // on amdgpu, passed on v4 |
1615 | char b : 8; |
1616 | char x : 8; |
1617 | char y : 8; |
1618 | }; |
1619 | struct bar { |
1620 | int space[4]; |
1621 | char a : 8; // on amdgpu, passed on v4 |
1622 | char b : 8; |
1623 | char : 0; |
1624 | char x : 8; // passed on v5 |
1625 | char y : 8; |
1626 | }; |
1627 | */ |
1628 | if (PreviousFieldsDI.empty()) |
1629 | return nullptr; |
1630 | |
1631 | // If we already emitted metadata for a 0-length bitfield, nothing to do here. |
1632 | auto *PreviousMDEntry = |
1633 | PreviousFieldsDI.empty() ? nullptr : PreviousFieldsDI.back(); |
1634 | auto *PreviousMDField = |
1635 | dyn_cast_or_null<llvm::DIDerivedType>(Val: PreviousMDEntry); |
1636 | if (!PreviousMDField || !PreviousMDField->isBitField() || |
1637 | PreviousMDField->getSizeInBits() == 0) |
1638 | return nullptr; |
1639 | |
1640 | auto PreviousBitfield = RD->field_begin(); |
1641 | std::advance(i&: PreviousBitfield, n: BitFieldDecl->getFieldIndex() - 1); |
1642 | |
1643 | assert(PreviousBitfield->isBitField()); |
1644 | |
1645 | ASTContext &Context = CGM.getContext(); |
1646 | if (!PreviousBitfield->isZeroLengthBitField(Ctx: Context)) |
1647 | return nullptr; |
1648 | |
1649 | QualType Ty = PreviousBitfield->getType(); |
1650 | SourceLocation Loc = PreviousBitfield->getLocation(); |
1651 | llvm::DIFile *VUnit = getOrCreateFile(Loc); |
1652 | llvm::DIType *DebugType = getOrCreateType(Ty, Fg: VUnit); |
1653 | llvm::DIScope *RecordTy = BitFieldDI->getScope(); |
1654 | |
1655 | llvm::DIFile *File = getOrCreateFile(Loc); |
1656 | unsigned Line = getLineNumber(Loc); |
1657 | |
1658 | uint64_t StorageOffsetInBits = |
1659 | cast<llvm::ConstantInt>(Val: BitFieldDI->getStorageOffsetInBits()) |
1660 | ->getZExtValue(); |
1661 | |
1662 | llvm::DINode::DIFlags Flags = |
1663 | getAccessFlag(PreviousBitfield->getAccess(), RD); |
1664 | llvm::DINodeArray Annotations = |
1665 | CollectBTFDeclTagAnnotations(*PreviousBitfield); |
1666 | return DBuilder.createBitFieldMemberType( |
1667 | Scope: RecordTy, Name: "" , File, LineNo: Line, SizeInBits: 0, OffsetInBits: StorageOffsetInBits, StorageOffsetInBits, |
1668 | Flags, Ty: DebugType, Annotations); |
1669 | } |
1670 | |
1671 | llvm::DIType *CGDebugInfo::createFieldType( |
1672 | StringRef name, QualType type, SourceLocation loc, AccessSpecifier AS, |
1673 | uint64_t offsetInBits, uint32_t AlignInBits, llvm::DIFile *tunit, |
1674 | llvm::DIScope *scope, const RecordDecl *RD, llvm::DINodeArray Annotations) { |
1675 | llvm::DIType *debugType = getOrCreateType(Ty: type, Fg: tunit); |
1676 | |
1677 | // Get the location for the field. |
1678 | llvm::DIFile *file = getOrCreateFile(Loc: loc); |
1679 | const unsigned line = getLineNumber(Loc: loc.isValid() ? loc : CurLoc); |
1680 | |
1681 | uint64_t SizeInBits = 0; |
1682 | auto Align = AlignInBits; |
1683 | if (!type->isIncompleteArrayType()) { |
1684 | TypeInfo TI = CGM.getContext().getTypeInfo(T: type); |
1685 | SizeInBits = TI.Width; |
1686 | if (!Align) |
1687 | Align = getTypeAlignIfRequired(Ty: type, Ctx: CGM.getContext()); |
1688 | } |
1689 | |
1690 | llvm::DINode::DIFlags flags = getAccessFlag(Access: AS, RD); |
1691 | return DBuilder.createMemberType(Scope: scope, Name: name, File: file, LineNo: line, SizeInBits, AlignInBits: Align, |
1692 | OffsetInBits: offsetInBits, Flags: flags, Ty: debugType, Annotations); |
1693 | } |
1694 | |
1695 | void CGDebugInfo::CollectRecordLambdaFields( |
1696 | const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements, |
1697 | llvm::DIType *RecordTy) { |
1698 | // For C++11 Lambdas a Field will be the same as a Capture, but the Capture |
1699 | // has the name and the location of the variable so we should iterate over |
1700 | // both concurrently. |
1701 | const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl); |
1702 | RecordDecl::field_iterator Field = CXXDecl->field_begin(); |
1703 | unsigned fieldno = 0; |
1704 | for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(), |
1705 | E = CXXDecl->captures_end(); |
1706 | I != E; ++I, ++Field, ++fieldno) { |
1707 | const LambdaCapture &C = *I; |
1708 | if (C.capturesVariable()) { |
1709 | SourceLocation Loc = C.getLocation(); |
1710 | assert(!Field->isBitField() && "lambdas don't have bitfield members!" ); |
1711 | ValueDecl *V = C.getCapturedVar(); |
1712 | StringRef VName = V->getName(); |
1713 | llvm::DIFile *VUnit = getOrCreateFile(Loc); |
1714 | auto Align = getDeclAlignIfRequired(V, CGM.getContext()); |
1715 | llvm::DIType *FieldType = createFieldType( |
1716 | VName, Field->getType(), Loc, Field->getAccess(), |
1717 | layout.getFieldOffset(FieldNo: fieldno), Align, VUnit, RecordTy, CXXDecl); |
1718 | elements.push_back(Elt: FieldType); |
1719 | } else if (C.capturesThis()) { |
1720 | // TODO: Need to handle 'this' in some way by probably renaming the |
1721 | // this of the lambda class and having a field member of 'this' or |
1722 | // by using AT_object_pointer for the function and having that be |
1723 | // used as 'this' for semantic references. |
1724 | FieldDecl *f = *Field; |
1725 | llvm::DIFile *VUnit = getOrCreateFile(Loc: f->getLocation()); |
1726 | QualType type = f->getType(); |
1727 | StringRef ThisName = |
1728 | CGM.getCodeGenOpts().EmitCodeView ? "__this" : "this" ; |
1729 | llvm::DIType *fieldType = createFieldType( |
1730 | ThisName, type, f->getLocation(), f->getAccess(), |
1731 | layout.getFieldOffset(FieldNo: fieldno), VUnit, RecordTy, CXXDecl); |
1732 | |
1733 | elements.push_back(Elt: fieldType); |
1734 | } |
1735 | } |
1736 | } |
1737 | |
1738 | llvm::DIDerivedType * |
1739 | CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy, |
1740 | const RecordDecl *RD) { |
1741 | // Create the descriptor for the static variable, with or without |
1742 | // constant initializers. |
1743 | Var = Var->getCanonicalDecl(); |
1744 | llvm::DIFile *VUnit = getOrCreateFile(Loc: Var->getLocation()); |
1745 | llvm::DIType *VTy = getOrCreateType(Ty: Var->getType(), Fg: VUnit); |
1746 | |
1747 | unsigned LineNumber = getLineNumber(Loc: Var->getLocation()); |
1748 | StringRef VName = Var->getName(); |
1749 | |
1750 | // FIXME: to avoid complications with type merging we should |
1751 | // emit the constant on the definition instead of the declaration. |
1752 | llvm::Constant *C = nullptr; |
1753 | if (Var->getInit()) { |
1754 | const APValue *Value = Var->evaluateValue(); |
1755 | if (Value) { |
1756 | if (Value->isInt()) |
1757 | C = llvm::ConstantInt::get(Context&: CGM.getLLVMContext(), V: Value->getInt()); |
1758 | if (Value->isFloat()) |
1759 | C = llvm::ConstantFP::get(Context&: CGM.getLLVMContext(), V: Value->getFloat()); |
1760 | } |
1761 | } |
1762 | |
1763 | llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD); |
1764 | auto Tag = CGM.getCodeGenOpts().DwarfVersion >= 5 |
1765 | ? llvm::dwarf::DW_TAG_variable |
1766 | : llvm::dwarf::DW_TAG_member; |
1767 | auto Align = getDeclAlignIfRequired(Var, CGM.getContext()); |
1768 | llvm::DIDerivedType *GV = DBuilder.createStaticMemberType( |
1769 | Scope: RecordTy, Name: VName, File: VUnit, LineNo: LineNumber, Ty: VTy, Flags, Val: C, Tag, AlignInBits: Align); |
1770 | StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV); |
1771 | return GV; |
1772 | } |
1773 | |
1774 | void CGDebugInfo::CollectRecordNormalField( |
1775 | const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit, |
1776 | SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy, |
1777 | const RecordDecl *RD) { |
1778 | StringRef name = field->getName(); |
1779 | QualType type = field->getType(); |
1780 | |
1781 | // Ignore unnamed fields unless they're anonymous structs/unions. |
1782 | if (name.empty() && !type->isRecordType()) |
1783 | return; |
1784 | |
1785 | llvm::DIType *FieldType; |
1786 | if (field->isBitField()) { |
1787 | llvm::DIDerivedType *BitFieldType; |
1788 | FieldType = BitFieldType = createBitFieldType(BitFieldDecl: field, RecordTy, RD); |
1789 | if (llvm::DIType *Separator = |
1790 | createBitFieldSeparatorIfNeeded(BitFieldDecl: field, BitFieldDI: BitFieldType, PreviousFieldsDI: elements, RD)) |
1791 | elements.push_back(Elt: Separator); |
1792 | } else { |
1793 | auto Align = getDeclAlignIfRequired(field, CGM.getContext()); |
1794 | llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(field); |
1795 | FieldType = |
1796 | createFieldType(name, type, field->getLocation(), field->getAccess(), |
1797 | OffsetInBits, Align, tunit, RecordTy, RD, Annotations); |
1798 | } |
1799 | |
1800 | elements.push_back(Elt: FieldType); |
1801 | } |
1802 | |
1803 | void CGDebugInfo::CollectRecordNestedType( |
1804 | const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) { |
1805 | QualType Ty = CGM.getContext().getTypeDeclType(Decl: TD); |
1806 | // Injected class names are not considered nested records. |
1807 | if (isa<InjectedClassNameType>(Val: Ty)) |
1808 | return; |
1809 | SourceLocation Loc = TD->getLocation(); |
1810 | llvm::DIType *nestedType = getOrCreateType(Ty, Fg: getOrCreateFile(Loc)); |
1811 | elements.push_back(Elt: nestedType); |
1812 | } |
1813 | |
1814 | void CGDebugInfo::CollectRecordFields( |
1815 | const RecordDecl *record, llvm::DIFile *tunit, |
1816 | SmallVectorImpl<llvm::Metadata *> &elements, |
1817 | llvm::DICompositeType *RecordTy) { |
1818 | const auto *CXXDecl = dyn_cast<CXXRecordDecl>(Val: record); |
1819 | |
1820 | if (CXXDecl && CXXDecl->isLambda()) |
1821 | CollectRecordLambdaFields(CXXDecl, elements, RecordTy); |
1822 | else { |
1823 | const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(D: record); |
1824 | |
1825 | // Field number for non-static fields. |
1826 | unsigned fieldNo = 0; |
1827 | |
1828 | // Static and non-static members should appear in the same order as |
1829 | // the corresponding declarations in the source program. |
1830 | for (const auto *I : record->decls()) |
1831 | if (const auto *V = dyn_cast<VarDecl>(I)) { |
1832 | if (V->hasAttr<NoDebugAttr>()) |
1833 | continue; |
1834 | |
1835 | // Skip variable template specializations when emitting CodeView. MSVC |
1836 | // doesn't emit them. |
1837 | if (CGM.getCodeGenOpts().EmitCodeView && |
1838 | isa<VarTemplateSpecializationDecl>(V)) |
1839 | continue; |
1840 | |
1841 | if (isa<VarTemplatePartialSpecializationDecl>(V)) |
1842 | continue; |
1843 | |
1844 | // Reuse the existing static member declaration if one exists |
1845 | auto MI = StaticDataMemberCache.find(V->getCanonicalDecl()); |
1846 | if (MI != StaticDataMemberCache.end()) { |
1847 | assert(MI->second && |
1848 | "Static data member declaration should still exist" ); |
1849 | elements.push_back(MI->second); |
1850 | } else { |
1851 | auto Field = CreateRecordStaticField(V, RecordTy, record); |
1852 | elements.push_back(Field); |
1853 | } |
1854 | } else if (const auto *field = dyn_cast<FieldDecl>(I)) { |
1855 | CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit, |
1856 | elements, RecordTy, record); |
1857 | |
1858 | // Bump field number for next field. |
1859 | ++fieldNo; |
1860 | } else if (CGM.getCodeGenOpts().EmitCodeView) { |
1861 | // Debug info for nested types is included in the member list only for |
1862 | // CodeView. |
1863 | if (const auto *nestedType = dyn_cast<TypeDecl>(I)) { |
1864 | // MSVC doesn't generate nested type for anonymous struct/union. |
1865 | if (isa<RecordDecl>(I) && |
1866 | cast<RecordDecl>(I)->isAnonymousStructOrUnion()) |
1867 | continue; |
1868 | if (!nestedType->isImplicit() && |
1869 | nestedType->getDeclContext() == record) |
1870 | CollectRecordNestedType(nestedType, elements); |
1871 | } |
1872 | } |
1873 | } |
1874 | } |
1875 | |
1876 | llvm::DISubroutineType * |
1877 | CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method, |
1878 | llvm::DIFile *Unit) { |
1879 | const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>(); |
1880 | if (Method->isStatic()) |
1881 | return cast_or_null<llvm::DISubroutineType>( |
1882 | Val: getOrCreateType(Ty: QualType(Func, 0), Fg: Unit)); |
1883 | return getOrCreateInstanceMethodType(ThisPtr: Method->getThisType(), Func, Unit); |
1884 | } |
1885 | |
1886 | llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType( |
1887 | QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) { |
1888 | FunctionProtoType::ExtProtoInfo EPI = Func->getExtProtoInfo(); |
1889 | Qualifiers &Qc = EPI.TypeQuals; |
1890 | Qc.removeConst(); |
1891 | Qc.removeVolatile(); |
1892 | Qc.removeRestrict(); |
1893 | Qc.removeUnaligned(); |
1894 | // Keep the removed qualifiers in sync with |
1895 | // CreateQualifiedType(const FunctionPrototype*, DIFile *Unit) |
1896 | // On a 'real' member function type, these qualifiers are carried on the type |
1897 | // of the first parameter, not as separate DW_TAG_const_type (etc) decorator |
1898 | // tags around them. (But, in the raw function types with qualifiers, they have |
1899 | // to use wrapper types.) |
1900 | |
1901 | // Add "this" pointer. |
1902 | const auto *OriginalFunc = cast<llvm::DISubroutineType>( |
1903 | getOrCreateType(Ty: CGM.getContext().getFunctionType( |
1904 | ResultTy: Func->getReturnType(), Args: Func->getParamTypes(), EPI), |
1905 | Fg: Unit)); |
1906 | llvm::DITypeRefArray Args = OriginalFunc->getTypeArray(); |
1907 | assert(Args.size() && "Invalid number of arguments!" ); |
1908 | |
1909 | SmallVector<llvm::Metadata *, 16> Elts; |
1910 | |
1911 | // First element is always return type. For 'void' functions it is NULL. |
1912 | Elts.push_back(Elt: Args[0]); |
1913 | |
1914 | // "this" pointer is always first argument. |
1915 | const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl(); |
1916 | if (isa<ClassTemplateSpecializationDecl>(Val: RD)) { |
1917 | // Create pointer type directly in this case. |
1918 | const PointerType *ThisPtrTy = cast<PointerType>(Val&: ThisPtr); |
1919 | uint64_t Size = CGM.getContext().getTypeSize(ThisPtrTy); |
1920 | auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext()); |
1921 | llvm::DIType *PointeeType = |
1922 | getOrCreateType(Ty: ThisPtrTy->getPointeeType(), Fg: Unit); |
1923 | llvm::DIType *ThisPtrType = |
1924 | DBuilder.createPointerType(PointeeTy: PointeeType, SizeInBits: Size, AlignInBits: Align); |
1925 | TypeCache[ThisPtr.getAsOpaquePtr()].reset(MD: ThisPtrType); |
1926 | // TODO: This and the artificial type below are misleading, the |
1927 | // types aren't artificial the argument is, but the current |
1928 | // metadata doesn't represent that. |
1929 | ThisPtrType = DBuilder.createObjectPointerType(Ty: ThisPtrType); |
1930 | Elts.push_back(Elt: ThisPtrType); |
1931 | } else { |
1932 | llvm::DIType *ThisPtrType = getOrCreateType(Ty: ThisPtr, Fg: Unit); |
1933 | TypeCache[ThisPtr.getAsOpaquePtr()].reset(MD: ThisPtrType); |
1934 | ThisPtrType = DBuilder.createObjectPointerType(Ty: ThisPtrType); |
1935 | Elts.push_back(Elt: ThisPtrType); |
1936 | } |
1937 | |
1938 | // Copy rest of the arguments. |
1939 | for (unsigned i = 1, e = Args.size(); i != e; ++i) |
1940 | Elts.push_back(Elt: Args[i]); |
1941 | |
1942 | llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elements: Elts); |
1943 | |
1944 | return DBuilder.createSubroutineType(ParameterTypes: EltTypeArray, Flags: OriginalFunc->getFlags(), |
1945 | CC: getDwarfCC(Func->getCallConv())); |
1946 | } |
1947 | |
1948 | /// isFunctionLocalClass - Return true if CXXRecordDecl is defined |
1949 | /// inside a function. |
1950 | static bool isFunctionLocalClass(const CXXRecordDecl *RD) { |
1951 | if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext())) |
1952 | return isFunctionLocalClass(NRD); |
1953 | if (isa<FunctionDecl>(RD->getDeclContext())) |
1954 | return true; |
1955 | return false; |
1956 | } |
1957 | |
1958 | llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction( |
1959 | const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) { |
1960 | bool IsCtorOrDtor = |
1961 | isa<CXXConstructorDecl>(Val: Method) || isa<CXXDestructorDecl>(Val: Method); |
1962 | |
1963 | StringRef MethodName = getFunctionName(Method); |
1964 | llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit); |
1965 | |
1966 | // Since a single ctor/dtor corresponds to multiple functions, it doesn't |
1967 | // make sense to give a single ctor/dtor a linkage name. |
1968 | StringRef MethodLinkageName; |
1969 | // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional |
1970 | // property to use here. It may've been intended to model "is non-external |
1971 | // type" but misses cases of non-function-local but non-external classes such |
1972 | // as those in anonymous namespaces as well as the reverse - external types |
1973 | // that are function local, such as those in (non-local) inline functions. |
1974 | if (!IsCtorOrDtor && !isFunctionLocalClass(RD: Method->getParent())) |
1975 | MethodLinkageName = CGM.getMangledName(Method); |
1976 | |
1977 | // Get the location for the method. |
1978 | llvm::DIFile *MethodDefUnit = nullptr; |
1979 | unsigned MethodLine = 0; |
1980 | if (!Method->isImplicit()) { |
1981 | MethodDefUnit = getOrCreateFile(Loc: Method->getLocation()); |
1982 | MethodLine = getLineNumber(Loc: Method->getLocation()); |
1983 | } |
1984 | |
1985 | // Collect virtual method info. |
1986 | llvm::DIType *ContainingType = nullptr; |
1987 | unsigned VIndex = 0; |
1988 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
1989 | llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; |
1990 | int ThisAdjustment = 0; |
1991 | |
1992 | if (VTableContextBase::hasVtableSlot(MD: Method)) { |
1993 | if (Method->isPureVirtual()) |
1994 | SPFlags |= llvm::DISubprogram::SPFlagPureVirtual; |
1995 | else |
1996 | SPFlags |= llvm::DISubprogram::SPFlagVirtual; |
1997 | |
1998 | if (CGM.getTarget().getCXXABI().isItaniumFamily()) { |
1999 | // It doesn't make sense to give a virtual destructor a vtable index, |
2000 | // since a single destructor has two entries in the vtable. |
2001 | if (!isa<CXXDestructorDecl>(Val: Method)) |
2002 | VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method); |
2003 | } else { |
2004 | // Emit MS ABI vftable information. There is only one entry for the |
2005 | // deleting dtor. |
2006 | const auto *DD = dyn_cast<CXXDestructorDecl>(Val: Method); |
2007 | GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method); |
2008 | MethodVFTableLocation ML = |
2009 | CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD); |
2010 | VIndex = ML.Index; |
2011 | |
2012 | // CodeView only records the vftable offset in the class that introduces |
2013 | // the virtual method. This is possible because, unlike Itanium, the MS |
2014 | // C++ ABI does not include all virtual methods from non-primary bases in |
2015 | // the vtable for the most derived class. For example, if C inherits from |
2016 | // A and B, C's primary vftable will not include B's virtual methods. |
2017 | if (Method->size_overridden_methods() == 0) |
2018 | Flags |= llvm::DINode::FlagIntroducedVirtual; |
2019 | |
2020 | // The 'this' adjustment accounts for both the virtual and non-virtual |
2021 | // portions of the adjustment. Presumably the debugger only uses it when |
2022 | // it knows the dynamic type of an object. |
2023 | ThisAdjustment = CGM.getCXXABI() |
2024 | .getVirtualFunctionPrologueThisAdjustment(GD) |
2025 | .getQuantity(); |
2026 | } |
2027 | ContainingType = RecordTy; |
2028 | } |
2029 | |
2030 | if (Method->getCanonicalDecl()->isDeleted()) |
2031 | SPFlags |= llvm::DISubprogram::SPFlagDeleted; |
2032 | |
2033 | if (Method->isNoReturn()) |
2034 | Flags |= llvm::DINode::FlagNoReturn; |
2035 | |
2036 | if (Method->isStatic()) |
2037 | Flags |= llvm::DINode::FlagStaticMember; |
2038 | if (Method->isImplicit()) |
2039 | Flags |= llvm::DINode::FlagArtificial; |
2040 | Flags |= getAccessFlag(Method->getAccess(), Method->getParent()); |
2041 | if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Val: Method)) { |
2042 | if (CXXC->isExplicit()) |
2043 | Flags |= llvm::DINode::FlagExplicit; |
2044 | } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Val: Method)) { |
2045 | if (CXXC->isExplicit()) |
2046 | Flags |= llvm::DINode::FlagExplicit; |
2047 | } |
2048 | if (Method->hasPrototype()) |
2049 | Flags |= llvm::DINode::FlagPrototyped; |
2050 | if (Method->getRefQualifier() == RQ_LValue) |
2051 | Flags |= llvm::DINode::FlagLValueReference; |
2052 | if (Method->getRefQualifier() == RQ_RValue) |
2053 | Flags |= llvm::DINode::FlagRValueReference; |
2054 | if (!Method->isExternallyVisible()) |
2055 | SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit; |
2056 | if (CGM.getLangOpts().Optimize) |
2057 | SPFlags |= llvm::DISubprogram::SPFlagOptimized; |
2058 | |
2059 | // In this debug mode, emit type info for a class when its constructor type |
2060 | // info is emitted. |
2061 | if (DebugKind == llvm::codegenoptions::DebugInfoConstructor) |
2062 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: Method)) |
2063 | completeUnusedClass(D: *CD->getParent()); |
2064 | |
2065 | llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit); |
2066 | llvm::DISubprogram *SP = DBuilder.createMethod( |
2067 | Scope: RecordTy, Name: MethodName, LinkageName: MethodLinkageName, File: MethodDefUnit, LineNo: MethodLine, |
2068 | Ty: MethodTy, VTableIndex: VIndex, ThisAdjustment, VTableHolder: ContainingType, Flags, SPFlags, |
2069 | TParams: TParamsArray.get()); |
2070 | |
2071 | SPCache[Method->getCanonicalDecl()].reset(SP); |
2072 | |
2073 | return SP; |
2074 | } |
2075 | |
2076 | void CGDebugInfo::CollectCXXMemberFunctions( |
2077 | const CXXRecordDecl *RD, llvm::DIFile *Unit, |
2078 | SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) { |
2079 | |
2080 | // Since we want more than just the individual member decls if we |
2081 | // have templated functions iterate over every declaration to gather |
2082 | // the functions. |
2083 | for (const auto *I : RD->decls()) { |
2084 | const auto *Method = dyn_cast<CXXMethodDecl>(I); |
2085 | // If the member is implicit, don't add it to the member list. This avoids |
2086 | // the member being added to type units by LLVM, while still allowing it |
2087 | // to be emitted into the type declaration/reference inside the compile |
2088 | // unit. |
2089 | // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp. |
2090 | // FIXME: Handle Using(Shadow?)Decls here to create |
2091 | // DW_TAG_imported_declarations inside the class for base decls brought into |
2092 | // derived classes. GDB doesn't seem to notice/leverage these when I tried |
2093 | // it, so I'm not rushing to fix this. (GCC seems to produce them, if |
2094 | // referenced) |
2095 | if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>()) |
2096 | continue; |
2097 | |
2098 | if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType()) |
2099 | continue; |
2100 | |
2101 | // Reuse the existing member function declaration if it exists. |
2102 | // It may be associated with the declaration of the type & should be |
2103 | // reused as we're building the definition. |
2104 | // |
2105 | // This situation can arise in the vtable-based debug info reduction where |
2106 | // implicit members are emitted in a non-vtable TU. |
2107 | auto MI = SPCache.find(Method->getCanonicalDecl()); |
2108 | EltTys.push_back(MI == SPCache.end() |
2109 | ? CreateCXXMemberFunction(Method, Unit, RecordTy) |
2110 | : static_cast<llvm::Metadata *>(MI->second)); |
2111 | } |
2112 | } |
2113 | |
2114 | void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit, |
2115 | SmallVectorImpl<llvm::Metadata *> &EltTys, |
2116 | llvm::DIType *RecordTy) { |
2117 | llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes; |
2118 | CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, Bases: RD->bases(), SeenTypes, |
2119 | StartingFlags: llvm::DINode::FlagZero); |
2120 | |
2121 | // If we are generating CodeView debug info, we also need to emit records for |
2122 | // indirect virtual base classes. |
2123 | if (CGM.getCodeGenOpts().EmitCodeView) { |
2124 | CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, Bases: RD->vbases(), SeenTypes, |
2125 | StartingFlags: llvm::DINode::FlagIndirectVirtualBase); |
2126 | } |
2127 | } |
2128 | |
2129 | void CGDebugInfo::CollectCXXBasesAux( |
2130 | const CXXRecordDecl *RD, llvm::DIFile *Unit, |
2131 | SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy, |
2132 | const CXXRecordDecl::base_class_const_range &Bases, |
2133 | llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes, |
2134 | llvm::DINode::DIFlags StartingFlags) { |
2135 | const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); |
2136 | for (const auto &BI : Bases) { |
2137 | const auto *Base = |
2138 | cast<CXXRecordDecl>(Val: BI.getType()->castAs<RecordType>()->getDecl()); |
2139 | if (!SeenTypes.insert(V: Base).second) |
2140 | continue; |
2141 | auto *BaseTy = getOrCreateType(Ty: BI.getType(), Fg: Unit); |
2142 | llvm::DINode::DIFlags BFlags = StartingFlags; |
2143 | uint64_t BaseOffset; |
2144 | uint32_t VBPtrOffset = 0; |
2145 | |
2146 | if (BI.isVirtual()) { |
2147 | if (CGM.getTarget().getCXXABI().isItaniumFamily()) { |
2148 | // virtual base offset offset is -ve. The code generator emits dwarf |
2149 | // expression where it expects +ve number. |
2150 | BaseOffset = 0 - CGM.getItaniumVTableContext() |
2151 | .getVirtualBaseOffsetOffset(RD, VBase: Base) |
2152 | .getQuantity(); |
2153 | } else { |
2154 | // In the MS ABI, store the vbtable offset, which is analogous to the |
2155 | // vbase offset offset in Itanium. |
2156 | BaseOffset = |
2157 | 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(Derived: RD, VBase: Base); |
2158 | VBPtrOffset = CGM.getContext() |
2159 | .getASTRecordLayout(RD) |
2160 | .getVBPtrOffset() |
2161 | .getQuantity(); |
2162 | } |
2163 | BFlags |= llvm::DINode::FlagVirtual; |
2164 | } else |
2165 | BaseOffset = CGM.getContext().toBits(CharSize: RL.getBaseClassOffset(Base)); |
2166 | // FIXME: Inconsistent units for BaseOffset. It is in bytes when |
2167 | // BI->isVirtual() and bits when not. |
2168 | |
2169 | BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD); |
2170 | llvm::DIType *DTy = DBuilder.createInheritance(Ty: RecordTy, BaseTy, BaseOffset, |
2171 | VBPtrOffset, Flags: BFlags); |
2172 | EltTys.push_back(Elt: DTy); |
2173 | } |
2174 | } |
2175 | |
2176 | llvm::DINodeArray |
2177 | CGDebugInfo::CollectTemplateParams(std::optional<TemplateArgs> OArgs, |
2178 | llvm::DIFile *Unit) { |
2179 | if (!OArgs) |
2180 | return llvm::DINodeArray(); |
2181 | TemplateArgs &Args = *OArgs; |
2182 | SmallVector<llvm::Metadata *, 16> TemplateParams; |
2183 | for (unsigned i = 0, e = Args.Args.size(); i != e; ++i) { |
2184 | const TemplateArgument &TA = Args.Args[i]; |
2185 | StringRef Name; |
2186 | const bool defaultParameter = TA.getIsDefaulted(); |
2187 | if (Args.TList) |
2188 | Name = Args.TList->getParam(Idx: i)->getName(); |
2189 | |
2190 | switch (TA.getKind()) { |
2191 | case TemplateArgument::Type: { |
2192 | llvm::DIType *TTy = getOrCreateType(Ty: TA.getAsType(), Fg: Unit); |
2193 | TemplateParams.push_back(Elt: DBuilder.createTemplateTypeParameter( |
2194 | Scope: TheCU, Name, Ty: TTy, IsDefault: defaultParameter)); |
2195 | |
2196 | } break; |
2197 | case TemplateArgument::Integral: { |
2198 | llvm::DIType *TTy = getOrCreateType(Ty: TA.getIntegralType(), Fg: Unit); |
2199 | TemplateParams.push_back(Elt: DBuilder.createTemplateValueParameter( |
2200 | Scope: TheCU, Name, Ty: TTy, IsDefault: defaultParameter, |
2201 | Val: llvm::ConstantInt::get(Context&: CGM.getLLVMContext(), V: TA.getAsIntegral()))); |
2202 | } break; |
2203 | case TemplateArgument::Declaration: { |
2204 | const ValueDecl *D = TA.getAsDecl(); |
2205 | QualType T = TA.getParamTypeForDecl().getDesugaredType(Context: CGM.getContext()); |
2206 | llvm::DIType *TTy = getOrCreateType(Ty: T, Fg: Unit); |
2207 | llvm::Constant *V = nullptr; |
2208 | // Skip retrieve the value if that template parameter has cuda device |
2209 | // attribute, i.e. that value is not available at the host side. |
2210 | if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice || |
2211 | !D->hasAttr<CUDADeviceAttr>()) { |
2212 | // Variable pointer template parameters have a value that is the address |
2213 | // of the variable. |
2214 | if (const auto *VD = dyn_cast<VarDecl>(Val: D)) |
2215 | V = CGM.GetAddrOfGlobalVar(D: VD); |
2216 | // Member function pointers have special support for building them, |
2217 | // though this is currently unsupported in LLVM CodeGen. |
2218 | else if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: D); |
2219 | MD && MD->isImplicitObjectMemberFunction()) |
2220 | V = CGM.getCXXABI().EmitMemberFunctionPointer(MD); |
2221 | else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) |
2222 | V = CGM.GetAddrOfFunction(GD: FD); |
2223 | // Member data pointers have special handling too to compute the fixed |
2224 | // offset within the object. |
2225 | else if (const auto *MPT = |
2226 | dyn_cast<MemberPointerType>(Val: T.getTypePtr())) { |
2227 | // These five lines (& possibly the above member function pointer |
2228 | // handling) might be able to be refactored to use similar code in |
2229 | // CodeGenModule::getMemberPointerConstant |
2230 | uint64_t fieldOffset = CGM.getContext().getFieldOffset(FD: D); |
2231 | CharUnits chars = |
2232 | CGM.getContext().toCharUnitsFromBits(BitSize: (int64_t)fieldOffset); |
2233 | V = CGM.getCXXABI().EmitMemberDataPointer(MPT, offset: chars); |
2234 | } else if (const auto *GD = dyn_cast<MSGuidDecl>(Val: D)) { |
2235 | V = CGM.GetAddrOfMSGuidDecl(GD).getPointer(); |
2236 | } else if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: D)) { |
2237 | if (T->isRecordType()) |
2238 | V = ConstantEmitter(CGM).emitAbstract( |
2239 | SourceLocation(), TPO->getValue(), TPO->getType()); |
2240 | else |
2241 | V = CGM.GetAddrOfTemplateParamObject(TPO).getPointer(); |
2242 | } |
2243 | assert(V && "Failed to find template parameter pointer" ); |
2244 | V = V->stripPointerCasts(); |
2245 | } |
2246 | TemplateParams.push_back(Elt: DBuilder.createTemplateValueParameter( |
2247 | Scope: TheCU, Name, Ty: TTy, IsDefault: defaultParameter, Val: cast_or_null<llvm::Constant>(Val: V))); |
2248 | } break; |
2249 | case TemplateArgument::NullPtr: { |
2250 | QualType T = TA.getNullPtrType(); |
2251 | llvm::DIType *TTy = getOrCreateType(Ty: T, Fg: Unit); |
2252 | llvm::Constant *V = nullptr; |
2253 | // Special case member data pointer null values since they're actually -1 |
2254 | // instead of zero. |
2255 | if (const auto *MPT = dyn_cast<MemberPointerType>(Val: T.getTypePtr())) |
2256 | // But treat member function pointers as simple zero integers because |
2257 | // it's easier than having a special case in LLVM's CodeGen. If LLVM |
2258 | // CodeGen grows handling for values of non-null member function |
2259 | // pointers then perhaps we could remove this special case and rely on |
2260 | // EmitNullMemberPointer for member function pointers. |
2261 | if (MPT->isMemberDataPointer()) |
2262 | V = CGM.getCXXABI().EmitNullMemberPointer(MPT); |
2263 | if (!V) |
2264 | V = llvm::ConstantInt::get(Ty: CGM.Int8Ty, V: 0); |
2265 | TemplateParams.push_back(Elt: DBuilder.createTemplateValueParameter( |
2266 | Scope: TheCU, Name, Ty: TTy, IsDefault: defaultParameter, Val: V)); |
2267 | } break; |
2268 | case TemplateArgument::StructuralValue: { |
2269 | QualType T = TA.getStructuralValueType(); |
2270 | llvm::DIType *TTy = getOrCreateType(Ty: T, Fg: Unit); |
2271 | llvm::Constant *V = ConstantEmitter(CGM).emitAbstract( |
2272 | loc: SourceLocation(), value: TA.getAsStructuralValue(), T); |
2273 | TemplateParams.push_back(Elt: DBuilder.createTemplateValueParameter( |
2274 | Scope: TheCU, Name, Ty: TTy, IsDefault: defaultParameter, Val: V)); |
2275 | } break; |
2276 | case TemplateArgument::Template: { |
2277 | std::string QualName; |
2278 | llvm::raw_string_ostream OS(QualName); |
2279 | TA.getAsTemplate().getAsTemplateDecl()->printQualifiedName( |
2280 | OS, getPrintingPolicy()); |
2281 | TemplateParams.push_back(Elt: DBuilder.createTemplateTemplateParameter( |
2282 | Scope: TheCU, Name, Ty: nullptr, Val: OS.str(), IsDefault: defaultParameter)); |
2283 | break; |
2284 | } |
2285 | case TemplateArgument::Pack: |
2286 | TemplateParams.push_back(Elt: DBuilder.createTemplateParameterPack( |
2287 | Scope: TheCU, Name, Ty: nullptr, |
2288 | Val: CollectTemplateParams(OArgs: {{.TList: nullptr, .Args: TA.getPackAsArray()}}, Unit))); |
2289 | break; |
2290 | case TemplateArgument::Expression: { |
2291 | const Expr *E = TA.getAsExpr(); |
2292 | QualType T = E->getType(); |
2293 | if (E->isGLValue()) |
2294 | T = CGM.getContext().getLValueReferenceType(T); |
2295 | llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T); |
2296 | assert(V && "Expression in template argument isn't constant" ); |
2297 | llvm::DIType *TTy = getOrCreateType(Ty: T, Fg: Unit); |
2298 | TemplateParams.push_back(Elt: DBuilder.createTemplateValueParameter( |
2299 | Scope: TheCU, Name, Ty: TTy, IsDefault: defaultParameter, Val: V->stripPointerCasts())); |
2300 | } break; |
2301 | // And the following should never occur: |
2302 | case TemplateArgument::TemplateExpansion: |
2303 | case TemplateArgument::Null: |
2304 | llvm_unreachable( |
2305 | "These argument types shouldn't exist in concrete types" ); |
2306 | } |
2307 | } |
2308 | return DBuilder.getOrCreateArray(Elements: TemplateParams); |
2309 | } |
2310 | |
2311 | std::optional<CGDebugInfo::TemplateArgs> |
2312 | CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const { |
2313 | if (FD->getTemplatedKind() == |
2314 | FunctionDecl::TK_FunctionTemplateSpecialization) { |
2315 | const TemplateParameterList *TList = FD->getTemplateSpecializationInfo() |
2316 | ->getTemplate() |
2317 | ->getTemplateParameters(); |
2318 | return {{.TList: TList, .Args: FD->getTemplateSpecializationArgs()->asArray()}}; |
2319 | } |
2320 | return std::nullopt; |
2321 | } |
2322 | std::optional<CGDebugInfo::TemplateArgs> |
2323 | CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const { |
2324 | // Always get the full list of parameters, not just the ones from the |
2325 | // specialization. A partial specialization may have fewer parameters than |
2326 | // there are arguments. |
2327 | auto *TS = dyn_cast<VarTemplateSpecializationDecl>(Val: VD); |
2328 | if (!TS) |
2329 | return std::nullopt; |
2330 | VarTemplateDecl *T = TS->getSpecializedTemplate(); |
2331 | const TemplateParameterList *TList = T->getTemplateParameters(); |
2332 | auto TA = TS->getTemplateArgs().asArray(); |
2333 | return {{.TList: TList, .Args: TA}}; |
2334 | } |
2335 | std::optional<CGDebugInfo::TemplateArgs> |
2336 | CGDebugInfo::GetTemplateArgs(const RecordDecl *RD) const { |
2337 | if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD)) { |
2338 | // Always get the full list of parameters, not just the ones from the |
2339 | // specialization. A partial specialization may have fewer parameters than |
2340 | // there are arguments. |
2341 | TemplateParameterList *TPList = |
2342 | TSpecial->getSpecializedTemplate()->getTemplateParameters(); |
2343 | const TemplateArgumentList &TAList = TSpecial->getTemplateArgs(); |
2344 | return {{.TList: TPList, .Args: TAList.asArray()}}; |
2345 | } |
2346 | return std::nullopt; |
2347 | } |
2348 | |
2349 | llvm::DINodeArray |
2350 | CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD, |
2351 | llvm::DIFile *Unit) { |
2352 | return CollectTemplateParams(OArgs: GetTemplateArgs(FD), Unit); |
2353 | } |
2354 | |
2355 | llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL, |
2356 | llvm::DIFile *Unit) { |
2357 | return CollectTemplateParams(OArgs: GetTemplateArgs(VD: VL), Unit); |
2358 | } |
2359 | |
2360 | llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(const RecordDecl *RD, |
2361 | llvm::DIFile *Unit) { |
2362 | return CollectTemplateParams(OArgs: GetTemplateArgs(RD), Unit); |
2363 | } |
2364 | |
2365 | llvm::DINodeArray CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl *D) { |
2366 | if (!D->hasAttr<BTFDeclTagAttr>()) |
2367 | return nullptr; |
2368 | |
2369 | SmallVector<llvm::Metadata *, 4> Annotations; |
2370 | for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) { |
2371 | llvm::Metadata *Ops[2] = { |
2372 | llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_decl_tag" )), |
2373 | llvm::MDString::get(CGM.getLLVMContext(), I->getBTFDeclTag())}; |
2374 | Annotations.push_back(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); |
2375 | } |
2376 | return DBuilder.getOrCreateArray(Elements: Annotations); |
2377 | } |
2378 | |
2379 | llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) { |
2380 | if (VTablePtrType) |
2381 | return VTablePtrType; |
2382 | |
2383 | ASTContext &Context = CGM.getContext(); |
2384 | |
2385 | /* Function type */ |
2386 | llvm::Metadata *STy = getOrCreateType(Ty: Context.IntTy, Fg: Unit); |
2387 | llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(Elements: STy); |
2388 | llvm::DIType *SubTy = DBuilder.createSubroutineType(ParameterTypes: SElements); |
2389 | unsigned Size = Context.getTypeSize(Context.VoidPtrTy); |
2390 | unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace(); |
2391 | std::optional<unsigned> DWARFAddressSpace = |
2392 | CGM.getTarget().getDWARFAddressSpace(AddressSpace: VtblPtrAddressSpace); |
2393 | |
2394 | llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType( |
2395 | PointeeTy: SubTy, SizeInBits: Size, AlignInBits: 0, DWARFAddressSpace, Name: "__vtbl_ptr_type" ); |
2396 | VTablePtrType = DBuilder.createPointerType(PointeeTy: vtbl_ptr_type, SizeInBits: Size); |
2397 | return VTablePtrType; |
2398 | } |
2399 | |
2400 | StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) { |
2401 | // Copy the gdb compatible name on the side and use its reference. |
2402 | return internString(A: "_vptr$" , B: RD->getNameAsString()); |
2403 | } |
2404 | |
2405 | StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD, |
2406 | DynamicInitKind StubKind, |
2407 | llvm::Function *InitFn) { |
2408 | // If we're not emitting codeview, use the mangled name. For Itanium, this is |
2409 | // arbitrary. |
2410 | if (!CGM.getCodeGenOpts().EmitCodeView || |
2411 | StubKind == DynamicInitKind::GlobalArrayDestructor) |
2412 | return InitFn->getName(); |
2413 | |
2414 | // Print the normal qualified name for the variable, then break off the last |
2415 | // NNS, and add the appropriate other text. Clang always prints the global |
2416 | // variable name without template arguments, so we can use rsplit("::") and |
2417 | // then recombine the pieces. |
2418 | SmallString<128> QualifiedGV; |
2419 | StringRef Quals; |
2420 | StringRef GVName; |
2421 | { |
2422 | llvm::raw_svector_ostream OS(QualifiedGV); |
2423 | VD->printQualifiedName(OS, getPrintingPolicy()); |
2424 | std::tie(args&: Quals, args&: GVName) = OS.str().rsplit(Separator: "::" ); |
2425 | if (GVName.empty()) |
2426 | std::swap(a&: Quals, b&: GVName); |
2427 | } |
2428 | |
2429 | SmallString<128> InitName; |
2430 | llvm::raw_svector_ostream OS(InitName); |
2431 | if (!Quals.empty()) |
2432 | OS << Quals << "::" ; |
2433 | |
2434 | switch (StubKind) { |
2435 | case DynamicInitKind::NoStub: |
2436 | case DynamicInitKind::GlobalArrayDestructor: |
2437 | llvm_unreachable("not an initializer" ); |
2438 | case DynamicInitKind::Initializer: |
2439 | OS << "`dynamic initializer for '" ; |
2440 | break; |
2441 | case DynamicInitKind::AtExit: |
2442 | OS << "`dynamic atexit destructor for '" ; |
2443 | break; |
2444 | } |
2445 | |
2446 | OS << GVName; |
2447 | |
2448 | // Add any template specialization args. |
2449 | if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) { |
2450 | printTemplateArgumentList(OS, Args: VTpl->getTemplateArgs().asArray(), |
2451 | Policy: getPrintingPolicy()); |
2452 | } |
2453 | |
2454 | OS << '\''; |
2455 | |
2456 | return internString(A: OS.str()); |
2457 | } |
2458 | |
2459 | void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit, |
2460 | SmallVectorImpl<llvm::Metadata *> &EltTys) { |
2461 | // If this class is not dynamic then there is not any vtable info to collect. |
2462 | if (!RD->isDynamicClass()) |
2463 | return; |
2464 | |
2465 | // Don't emit any vtable shape or vptr info if this class doesn't have an |
2466 | // extendable vfptr. This can happen if the class doesn't have virtual |
2467 | // methods, or in the MS ABI if those virtual methods only come from virtually |
2468 | // inherited bases. |
2469 | const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); |
2470 | if (!RL.hasExtendableVFPtr()) |
2471 | return; |
2472 | |
2473 | // CodeView needs to know how large the vtable of every dynamic class is, so |
2474 | // emit a special named pointer type into the element list. The vptr type |
2475 | // points to this type as well. |
2476 | llvm::DIType *VPtrTy = nullptr; |
2477 | bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView && |
2478 | CGM.getTarget().getCXXABI().isMicrosoft(); |
2479 | if (NeedVTableShape) { |
2480 | uint64_t PtrWidth = |
2481 | CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); |
2482 | const VTableLayout &VFTLayout = |
2483 | CGM.getMicrosoftVTableContext().getVFTableLayout(RD, VFPtrOffset: CharUnits::Zero()); |
2484 | unsigned VSlotCount = |
2485 | VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData; |
2486 | unsigned VTableWidth = PtrWidth * VSlotCount; |
2487 | unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace(); |
2488 | std::optional<unsigned> DWARFAddressSpace = |
2489 | CGM.getTarget().getDWARFAddressSpace(AddressSpace: VtblPtrAddressSpace); |
2490 | |
2491 | // Create a very wide void* type and insert it directly in the element list. |
2492 | llvm::DIType *VTableType = DBuilder.createPointerType( |
2493 | PointeeTy: nullptr, SizeInBits: VTableWidth, AlignInBits: 0, DWARFAddressSpace, Name: "__vtbl_ptr_type" ); |
2494 | EltTys.push_back(Elt: VTableType); |
2495 | |
2496 | // The vptr is a pointer to this special vtable type. |
2497 | VPtrTy = DBuilder.createPointerType(PointeeTy: VTableType, SizeInBits: PtrWidth); |
2498 | } |
2499 | |
2500 | // If there is a primary base then the artificial vptr member lives there. |
2501 | if (RL.getPrimaryBase()) |
2502 | return; |
2503 | |
2504 | if (!VPtrTy) |
2505 | VPtrTy = getOrCreateVTablePtrType(Unit); |
2506 | |
2507 | unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy); |
2508 | llvm::DIType *VPtrMember = |
2509 | DBuilder.createMemberType(Scope: Unit, Name: getVTableName(RD), File: Unit, LineNo: 0, SizeInBits: Size, AlignInBits: 0, OffsetInBits: 0, |
2510 | Flags: llvm::DINode::FlagArtificial, Ty: VPtrTy); |
2511 | EltTys.push_back(Elt: VPtrMember); |
2512 | } |
2513 | |
2514 | llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy, |
2515 | SourceLocation Loc) { |
2516 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
2517 | llvm::DIType *T = getOrCreateType(Ty: RTy, Fg: getOrCreateFile(Loc)); |
2518 | return T; |
2519 | } |
2520 | |
2521 | llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D, |
2522 | SourceLocation Loc) { |
2523 | return getOrCreateStandaloneType(Ty: D, Loc); |
2524 | } |
2525 | |
2526 | llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D, |
2527 | SourceLocation Loc) { |
2528 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
2529 | assert(!D.isNull() && "null type" ); |
2530 | llvm::DIType *T = getOrCreateType(Ty: D, Fg: getOrCreateFile(Loc)); |
2531 | assert(T && "could not create debug info for type" ); |
2532 | |
2533 | RetainedTypes.push_back(x: D.getAsOpaquePtr()); |
2534 | return T; |
2535 | } |
2536 | |
2537 | void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase *CI, |
2538 | QualType AllocatedTy, |
2539 | SourceLocation Loc) { |
2540 | if (CGM.getCodeGenOpts().getDebugInfo() <= |
2541 | llvm::codegenoptions::DebugLineTablesOnly) |
2542 | return; |
2543 | llvm::MDNode *node; |
2544 | if (AllocatedTy->isVoidType()) |
2545 | node = llvm::MDNode::get(Context&: CGM.getLLVMContext(), MDs: std::nullopt); |
2546 | else |
2547 | node = getOrCreateType(Ty: AllocatedTy, Fg: getOrCreateFile(Loc)); |
2548 | |
2549 | CI->setMetadata(Kind: "heapallocsite" , Node: node); |
2550 | } |
2551 | |
2552 | void CGDebugInfo::completeType(const EnumDecl *ED) { |
2553 | if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly) |
2554 | return; |
2555 | QualType Ty = CGM.getContext().getEnumType(Decl: ED); |
2556 | void *TyPtr = Ty.getAsOpaquePtr(); |
2557 | auto I = TypeCache.find(Val: TyPtr); |
2558 | if (I == TypeCache.end() || !cast<llvm::DIType>(Val&: I->second)->isForwardDecl()) |
2559 | return; |
2560 | llvm::DIType *Res = CreateTypeDefinition(Ty: Ty->castAs<EnumType>()); |
2561 | assert(!Res->isForwardDecl()); |
2562 | TypeCache[TyPtr].reset(MD: Res); |
2563 | } |
2564 | |
2565 | void CGDebugInfo::completeType(const RecordDecl *RD) { |
2566 | if (DebugKind > llvm::codegenoptions::LimitedDebugInfo || |
2567 | !CGM.getLangOpts().CPlusPlus) |
2568 | completeRequiredType(RD); |
2569 | } |
2570 | |
2571 | /// Return true if the class or any of its methods are marked dllimport. |
2572 | static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) { |
2573 | if (RD->hasAttr<DLLImportAttr>()) |
2574 | return true; |
2575 | for (const CXXMethodDecl *MD : RD->methods()) |
2576 | if (MD->hasAttr<DLLImportAttr>()) |
2577 | return true; |
2578 | return false; |
2579 | } |
2580 | |
2581 | /// Does a type definition exist in an imported clang module? |
2582 | static bool isDefinedInClangModule(const RecordDecl *RD) { |
2583 | // Only definitions that where imported from an AST file come from a module. |
2584 | if (!RD || !RD->isFromASTFile()) |
2585 | return false; |
2586 | // Anonymous entities cannot be addressed. Treat them as not from module. |
2587 | if (!RD->isExternallyVisible() && RD->getName().empty()) |
2588 | return false; |
2589 | if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(Val: RD)) { |
2590 | if (!CXXDecl->isCompleteDefinition()) |
2591 | return false; |
2592 | // Check wether RD is a template. |
2593 | auto TemplateKind = CXXDecl->getTemplateSpecializationKind(); |
2594 | if (TemplateKind != TSK_Undeclared) { |
2595 | // Unfortunately getOwningModule() isn't accurate enough to find the |
2596 | // owning module of a ClassTemplateSpecializationDecl that is inside a |
2597 | // namespace spanning multiple modules. |
2598 | bool Explicit = false; |
2599 | if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(Val: CXXDecl)) |
2600 | Explicit = TD->isExplicitInstantiationOrSpecialization(); |
2601 | if (!Explicit && CXXDecl->getEnclosingNamespaceContext()) |
2602 | return false; |
2603 | // This is a template, check the origin of the first member. |
2604 | if (CXXDecl->field_begin() == CXXDecl->field_end()) |
2605 | return TemplateKind == TSK_ExplicitInstantiationDeclaration; |
2606 | if (!CXXDecl->field_begin()->isFromASTFile()) |
2607 | return false; |
2608 | } |
2609 | } |
2610 | return true; |
2611 | } |
2612 | |
2613 | void CGDebugInfo::completeClassData(const RecordDecl *RD) { |
2614 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) |
2615 | if (CXXRD->isDynamicClass() && |
2616 | CGM.getVTableLinkage(RD: CXXRD) == |
2617 | llvm::GlobalValue::AvailableExternallyLinkage && |
2618 | !isClassOrMethodDLLImport(RD: CXXRD)) |
2619 | return; |
2620 | |
2621 | if (DebugTypeExtRefs && isDefinedInClangModule(RD: RD->getDefinition())) |
2622 | return; |
2623 | |
2624 | completeClass(RD); |
2625 | } |
2626 | |
2627 | void CGDebugInfo::completeClass(const RecordDecl *RD) { |
2628 | if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly) |
2629 | return; |
2630 | QualType Ty = CGM.getContext().getRecordType(Decl: RD); |
2631 | void *TyPtr = Ty.getAsOpaquePtr(); |
2632 | auto I = TypeCache.find(Val: TyPtr); |
2633 | if (I != TypeCache.end() && !cast<llvm::DIType>(Val&: I->second)->isForwardDecl()) |
2634 | return; |
2635 | |
2636 | // We want the canonical definition of the structure to not |
2637 | // be the typedef. Since that would lead to circular typedef |
2638 | // metadata. |
2639 | auto [Res, PrefRes] = CreateTypeDefinition(Ty: Ty->castAs<RecordType>()); |
2640 | assert(!Res->isForwardDecl()); |
2641 | TypeCache[TyPtr].reset(MD: Res); |
2642 | } |
2643 | |
2644 | static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I, |
2645 | CXXRecordDecl::method_iterator End) { |
2646 | for (CXXMethodDecl *MD : llvm::make_range(x: I, y: End)) |
2647 | if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction()) |
2648 | if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() && |
2649 | !MD->getMemberSpecializationInfo()->isExplicitSpecialization()) |
2650 | return true; |
2651 | return false; |
2652 | } |
2653 | |
2654 | static bool canUseCtorHoming(const CXXRecordDecl *RD) { |
2655 | // Constructor homing can be used for classes that cannnot be constructed |
2656 | // without emitting code for one of their constructors. This is classes that |
2657 | // don't have trivial or constexpr constructors, or can be created from |
2658 | // aggregate initialization. Also skip lambda objects because they don't call |
2659 | // constructors. |
2660 | |
2661 | // Skip this optimization if the class or any of its methods are marked |
2662 | // dllimport. |
2663 | if (isClassOrMethodDLLImport(RD)) |
2664 | return false; |
2665 | |
2666 | if (RD->isLambda() || RD->isAggregate() || |
2667 | RD->hasTrivialDefaultConstructor() || |
2668 | RD->hasConstexprNonCopyMoveConstructor()) |
2669 | return false; |
2670 | |
2671 | for (const CXXConstructorDecl *Ctor : RD->ctors()) { |
2672 | if (Ctor->isCopyOrMoveConstructor()) |
2673 | continue; |
2674 | if (!Ctor->isDeleted()) |
2675 | return true; |
2676 | } |
2677 | return false; |
2678 | } |
2679 | |
2680 | static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind, |
2681 | bool DebugTypeExtRefs, const RecordDecl *RD, |
2682 | const LangOptions &LangOpts) { |
2683 | if (DebugTypeExtRefs && isDefinedInClangModule(RD: RD->getDefinition())) |
2684 | return true; |
2685 | |
2686 | if (auto *ES = RD->getASTContext().getExternalSource()) |
2687 | if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always) |
2688 | return true; |
2689 | |
2690 | // Only emit forward declarations in line tables only to keep debug info size |
2691 | // small. This only applies to CodeView, since we don't emit types in DWARF |
2692 | // line tables only. |
2693 | if (DebugKind == llvm::codegenoptions::DebugLineTablesOnly) |
2694 | return true; |
2695 | |
2696 | if (DebugKind > llvm::codegenoptions::LimitedDebugInfo || |
2697 | RD->hasAttr<StandaloneDebugAttr>()) |
2698 | return false; |
2699 | |
2700 | if (!LangOpts.CPlusPlus) |
2701 | return false; |
2702 | |
2703 | if (!RD->isCompleteDefinitionRequired()) |
2704 | return true; |
2705 | |
2706 | const auto *CXXDecl = dyn_cast<CXXRecordDecl>(Val: RD); |
2707 | |
2708 | if (!CXXDecl) |
2709 | return false; |
2710 | |
2711 | // Only emit complete debug info for a dynamic class when its vtable is |
2712 | // emitted. However, Microsoft debuggers don't resolve type information |
2713 | // across DLL boundaries, so skip this optimization if the class or any of its |
2714 | // methods are marked dllimport. This isn't a complete solution, since objects |
2715 | // without any dllimport methods can be used in one DLL and constructed in |
2716 | // another, but it is the current behavior of LimitedDebugInfo. |
2717 | if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() && |
2718 | !isClassOrMethodDLLImport(RD: CXXDecl)) |
2719 | return true; |
2720 | |
2721 | TemplateSpecializationKind Spec = TSK_Undeclared; |
2722 | if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD)) |
2723 | Spec = SD->getSpecializationKind(); |
2724 | |
2725 | if (Spec == TSK_ExplicitInstantiationDeclaration && |
2726 | hasExplicitMemberDefinition(I: CXXDecl->method_begin(), |
2727 | End: CXXDecl->method_end())) |
2728 | return true; |
2729 | |
2730 | // In constructor homing mode, only emit complete debug info for a class |
2731 | // when its constructor is emitted. |
2732 | if ((DebugKind == llvm::codegenoptions::DebugInfoConstructor) && |
2733 | canUseCtorHoming(RD: CXXDecl)) |
2734 | return true; |
2735 | |
2736 | return false; |
2737 | } |
2738 | |
2739 | void CGDebugInfo::completeRequiredType(const RecordDecl *RD) { |
2740 | if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, LangOpts: CGM.getLangOpts())) |
2741 | return; |
2742 | |
2743 | QualType Ty = CGM.getContext().getRecordType(Decl: RD); |
2744 | llvm::DIType *T = getTypeOrNull(Ty); |
2745 | if (T && T->isForwardDecl()) |
2746 | completeClassData(RD); |
2747 | } |
2748 | |
2749 | llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) { |
2750 | RecordDecl *RD = Ty->getDecl(); |
2751 | llvm::DIType *T = cast_or_null<llvm::DIType>(Val: getTypeOrNull(QualType(Ty, 0))); |
2752 | if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, |
2753 | LangOpts: CGM.getLangOpts())) { |
2754 | if (!T) |
2755 | T = getOrCreateRecordFwdDecl(Ty, Ctx: getDeclContextDescriptor(RD)); |
2756 | return T; |
2757 | } |
2758 | |
2759 | auto [Def, Pref] = CreateTypeDefinition(Ty); |
2760 | |
2761 | return Pref ? Pref : Def; |
2762 | } |
2763 | |
2764 | llvm::DIType *CGDebugInfo::GetPreferredNameType(const CXXRecordDecl *RD, |
2765 | llvm::DIFile *Unit) { |
2766 | if (!RD) |
2767 | return nullptr; |
2768 | |
2769 | auto const *PNA = RD->getAttr<PreferredNameAttr>(); |
2770 | if (!PNA) |
2771 | return nullptr; |
2772 | |
2773 | return getOrCreateType(Ty: PNA->getTypedefType(), Fg: Unit); |
2774 | } |
2775 | |
2776 | std::pair<llvm::DIType *, llvm::DIType *> |
2777 | CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) { |
2778 | RecordDecl *RD = Ty->getDecl(); |
2779 | |
2780 | // Get overall information about the record type for the debug info. |
2781 | llvm::DIFile *DefUnit = getOrCreateFile(Loc: RD->getLocation()); |
2782 | |
2783 | // Records and classes and unions can all be recursive. To handle them, we |
2784 | // first generate a debug descriptor for the struct as a forward declaration. |
2785 | // Then (if it is a definition) we go through and get debug info for all of |
2786 | // its members. Finally, we create a descriptor for the complete type (which |
2787 | // may refer to the forward decl if the struct is recursive) and replace all |
2788 | // uses of the forward declaration with the final definition. |
2789 | llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty); |
2790 | |
2791 | const RecordDecl *D = RD->getDefinition(); |
2792 | if (!D || !D->isCompleteDefinition()) |
2793 | return {FwdDecl, nullptr}; |
2794 | |
2795 | if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(Val: RD)) |
2796 | CollectContainingType(RD: CXXDecl, CT: FwdDecl); |
2797 | |
2798 | // Push the struct on region stack. |
2799 | LexicalBlockStack.emplace_back(args: &*FwdDecl); |
2800 | RegionMap[Ty->getDecl()].reset(FwdDecl); |
2801 | |
2802 | // Convert all the elements. |
2803 | SmallVector<llvm::Metadata *, 16> EltTys; |
2804 | // what about nested types? |
2805 | |
2806 | // Note: The split of CXXDecl information here is intentional, the |
2807 | // gdb tests will depend on a certain ordering at printout. The debug |
2808 | // information offsets are still correct if we merge them all together |
2809 | // though. |
2810 | const auto *CXXDecl = dyn_cast<CXXRecordDecl>(Val: RD); |
2811 | if (CXXDecl) { |
2812 | CollectCXXBases(RD: CXXDecl, Unit: DefUnit, EltTys, RecordTy: FwdDecl); |
2813 | CollectVTableInfo(RD: CXXDecl, Unit: DefUnit, EltTys); |
2814 | } |
2815 | |
2816 | // Collect data fields (including static variables and any initializers). |
2817 | CollectRecordFields(record: RD, tunit: DefUnit, elements&: EltTys, RecordTy: FwdDecl); |
2818 | if (CXXDecl) |
2819 | CollectCXXMemberFunctions(RD: CXXDecl, Unit: DefUnit, EltTys, RecordTy: FwdDecl); |
2820 | |
2821 | LexicalBlockStack.pop_back(); |
2822 | RegionMap.erase(Ty->getDecl()); |
2823 | |
2824 | llvm::DINodeArray Elements = DBuilder.getOrCreateArray(Elements: EltTys); |
2825 | DBuilder.replaceArrays(T&: FwdDecl, Elements); |
2826 | |
2827 | if (FwdDecl->isTemporary()) |
2828 | FwdDecl = |
2829 | llvm::MDNode::replaceWithPermanent(N: llvm::TempDICompositeType(FwdDecl)); |
2830 | |
2831 | RegionMap[Ty->getDecl()].reset(FwdDecl); |
2832 | |
2833 | if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) |
2834 | if (auto *PrefDI = GetPreferredNameType(CXXDecl, DefUnit)) |
2835 | return {FwdDecl, PrefDI}; |
2836 | |
2837 | return {FwdDecl, nullptr}; |
2838 | } |
2839 | |
2840 | llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty, |
2841 | llvm::DIFile *Unit) { |
2842 | // Ignore protocols. |
2843 | return getOrCreateType(Ty: Ty->getBaseType(), Fg: Unit); |
2844 | } |
2845 | |
2846 | llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty, |
2847 | llvm::DIFile *Unit) { |
2848 | // Ignore protocols. |
2849 | SourceLocation Loc = Ty->getDecl()->getLocation(); |
2850 | |
2851 | // Use Typedefs to represent ObjCTypeParamType. |
2852 | return DBuilder.createTypedef( |
2853 | Ty: getOrCreateType(Ty: Ty->getDecl()->getUnderlyingType(), Fg: Unit), |
2854 | Name: Ty->getDecl()->getName(), File: getOrCreateFile(Loc), LineNo: getLineNumber(Loc), |
2855 | Context: getDeclContextDescriptor(Ty->getDecl())); |
2856 | } |
2857 | |
2858 | /// \return true if Getter has the default name for the property PD. |
2859 | static bool hasDefaultGetterName(const ObjCPropertyDecl *PD, |
2860 | const ObjCMethodDecl *Getter) { |
2861 | assert(PD); |
2862 | if (!Getter) |
2863 | return true; |
2864 | |
2865 | assert(Getter->getDeclName().isObjCZeroArgSelector()); |
2866 | return PD->getName() == |
2867 | Getter->getDeclName().getObjCSelector().getNameForSlot(0); |
2868 | } |
2869 | |
2870 | /// \return true if Setter has the default name for the property PD. |
2871 | static bool hasDefaultSetterName(const ObjCPropertyDecl *PD, |
2872 | const ObjCMethodDecl *Setter) { |
2873 | assert(PD); |
2874 | if (!Setter) |
2875 | return true; |
2876 | |
2877 | assert(Setter->getDeclName().isObjCOneArgSelector()); |
2878 | return SelectorTable::constructSetterName(Name: PD->getName()) == |
2879 | Setter->getDeclName().getObjCSelector().getNameForSlot(0); |
2880 | } |
2881 | |
2882 | llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty, |
2883 | llvm::DIFile *Unit) { |
2884 | ObjCInterfaceDecl *ID = Ty->getDecl(); |
2885 | if (!ID) |
2886 | return nullptr; |
2887 | |
2888 | // Return a forward declaration if this type was imported from a clang module, |
2889 | // and this is not the compile unit with the implementation of the type (which |
2890 | // may contain hidden ivars). |
2891 | if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() && |
2892 | !ID->getImplementation()) |
2893 | return DBuilder.createForwardDecl(Tag: llvm::dwarf::DW_TAG_structure_type, |
2894 | Name: ID->getName(), |
2895 | Scope: getDeclContextDescriptor(ID), F: Unit, Line: 0); |
2896 | |
2897 | // Get overall information about the record type for the debug info. |
2898 | llvm::DIFile *DefUnit = getOrCreateFile(Loc: ID->getLocation()); |
2899 | unsigned Line = getLineNumber(Loc: ID->getLocation()); |
2900 | auto RuntimeLang = |
2901 | static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage()); |
2902 | |
2903 | // If this is just a forward declaration return a special forward-declaration |
2904 | // debug type since we won't be able to lay out the entire type. |
2905 | ObjCInterfaceDecl *Def = ID->getDefinition(); |
2906 | if (!Def || !Def->getImplementation()) { |
2907 | llvm::DIScope *Mod = getParentModuleOrNull(ID); |
2908 | llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType( |
2909 | Tag: llvm::dwarf::DW_TAG_structure_type, Name: ID->getName(), Scope: Mod ? Mod : TheCU, |
2910 | F: DefUnit, Line, RuntimeLang); |
2911 | ObjCInterfaceCache.push_back(Elt: ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit)); |
2912 | return FwdDecl; |
2913 | } |
2914 | |
2915 | return CreateTypeDefinition(Ty, F: Unit); |
2916 | } |
2917 | |
2918 | llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod, |
2919 | bool CreateSkeletonCU) { |
2920 | // Use the Module pointer as the key into the cache. This is a |
2921 | // nullptr if the "Module" is a PCH, which is safe because we don't |
2922 | // support chained PCH debug info, so there can only be a single PCH. |
2923 | const Module *M = Mod.getModuleOrNull(); |
2924 | auto ModRef = ModuleCache.find(Val: M); |
2925 | if (ModRef != ModuleCache.end()) |
2926 | return cast<llvm::DIModule>(Val&: ModRef->second); |
2927 | |
2928 | // Macro definitions that were defined with "-D" on the command line. |
2929 | SmallString<128> ConfigMacros; |
2930 | { |
2931 | llvm::raw_svector_ostream OS(ConfigMacros); |
2932 | const auto &PPOpts = CGM.getPreprocessorOpts(); |
2933 | unsigned I = 0; |
2934 | // Translate the macro definitions back into a command line. |
2935 | for (auto &M : PPOpts.Macros) { |
2936 | if (++I > 1) |
2937 | OS << " " ; |
2938 | const std::string &Macro = M.first; |
2939 | bool Undef = M.second; |
2940 | OS << "\"-" << (Undef ? 'U' : 'D'); |
2941 | for (char c : Macro) |
2942 | switch (c) { |
2943 | case '\\': |
2944 | OS << "\\\\" ; |
2945 | break; |
2946 | case '"': |
2947 | OS << "\\\"" ; |
2948 | break; |
2949 | default: |
2950 | OS << c; |
2951 | } |
2952 | OS << '\"'; |
2953 | } |
2954 | } |
2955 | |
2956 | bool IsRootModule = M ? !M->Parent : true; |
2957 | // When a module name is specified as -fmodule-name, that module gets a |
2958 | // clang::Module object, but it won't actually be built or imported; it will |
2959 | // be textual. |
2960 | if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M) |
2961 | assert(StringRef(M->Name).starts_with(CGM.getLangOpts().ModuleName) && |
2962 | "clang module without ASTFile must be specified by -fmodule-name" ); |
2963 | |
2964 | // Return a StringRef to the remapped Path. |
2965 | auto RemapPath = [this](StringRef Path) -> std::string { |
2966 | std::string Remapped = remapDIPath(Path); |
2967 | StringRef Relative(Remapped); |
2968 | StringRef CompDir = TheCU->getDirectory(); |
2969 | if (Relative.consume_front(Prefix: CompDir)) |
2970 | Relative.consume_front(Prefix: llvm::sys::path::get_separator()); |
2971 | |
2972 | return Relative.str(); |
2973 | }; |
2974 | |
2975 | if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) { |
2976 | // PCH files don't have a signature field in the control block, |
2977 | // but LLVM detects skeleton CUs by looking for a non-zero DWO id. |
2978 | // We use the lower 64 bits for debug info. |
2979 | |
2980 | uint64_t Signature = 0; |
2981 | if (const auto &ModSig = Mod.getSignature()) |
2982 | Signature = ModSig.truncatedValue(); |
2983 | else |
2984 | Signature = ~1ULL; |
2985 | |
2986 | llvm::DIBuilder DIB(CGM.getModule()); |
2987 | SmallString<0> PCM; |
2988 | if (!llvm::sys::path::is_absolute(path: Mod.getASTFile())) { |
2989 | if (CGM.getHeaderSearchOpts().ModuleFileHomeIsCwd) |
2990 | PCM = getCurrentDirname(); |
2991 | else |
2992 | PCM = Mod.getPath(); |
2993 | } |
2994 | llvm::sys::path::append(path&: PCM, a: Mod.getASTFile()); |
2995 | DIB.createCompileUnit( |
2996 | Lang: TheCU->getSourceLanguage(), |
2997 | // TODO: Support "Source" from external AST providers? |
2998 | File: DIB.createFile(Filename: Mod.getModuleName(), Directory: TheCU->getDirectory()), |
2999 | Producer: TheCU->getProducer(), isOptimized: false, Flags: StringRef(), RV: 0, SplitName: RemapPath(PCM), |
3000 | Kind: llvm::DICompileUnit::FullDebug, DWOId: Signature); |
3001 | DIB.finalize(); |
3002 | } |
3003 | |
3004 | llvm::DIModule *Parent = |
3005 | IsRootModule ? nullptr |
3006 | : getOrCreateModuleRef(Mod: ASTSourceDescriptor(*M->Parent), |
3007 | CreateSkeletonCU); |
3008 | std::string IncludePath = Mod.getPath().str(); |
3009 | llvm::DIModule *DIMod = |
3010 | DBuilder.createModule(Scope: Parent, Name: Mod.getModuleName(), ConfigurationMacros: ConfigMacros, |
3011 | IncludePath: RemapPath(IncludePath)); |
3012 | ModuleCache[M].reset(MD: DIMod); |
3013 | return DIMod; |
3014 | } |
3015 | |
3016 | llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty, |
3017 | llvm::DIFile *Unit) { |
3018 | ObjCInterfaceDecl *ID = Ty->getDecl(); |
3019 | llvm::DIFile *DefUnit = getOrCreateFile(Loc: ID->getLocation()); |
3020 | unsigned Line = getLineNumber(Loc: ID->getLocation()); |
3021 | unsigned RuntimeLang = TheCU->getSourceLanguage(); |
3022 | |
3023 | // Bit size, align and offset of the type. |
3024 | uint64_t Size = CGM.getContext().getTypeSize(Ty); |
3025 | auto Align = getTypeAlignIfRequired(Ty, CGM.getContext()); |
3026 | |
3027 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
3028 | if (ID->getImplementation()) |
3029 | Flags |= llvm::DINode::FlagObjcClassComplete; |
3030 | |
3031 | llvm::DIScope *Mod = getParentModuleOrNull(ID); |
3032 | llvm::DICompositeType *RealDecl = DBuilder.createStructType( |
3033 | Scope: Mod ? Mod : Unit, Name: ID->getName(), File: DefUnit, LineNumber: Line, SizeInBits: Size, AlignInBits: Align, Flags, |
3034 | DerivedFrom: nullptr, Elements: llvm::DINodeArray(), RunTimeLang: RuntimeLang); |
3035 | |
3036 | QualType QTy(Ty, 0); |
3037 | TypeCache[QTy.getAsOpaquePtr()].reset(MD: RealDecl); |
3038 | |
3039 | // Push the struct on region stack. |
3040 | LexicalBlockStack.emplace_back(args&: RealDecl); |
3041 | RegionMap[Ty->getDecl()].reset(RealDecl); |
3042 | |
3043 | // Convert all the elements. |
3044 | SmallVector<llvm::Metadata *, 16> EltTys; |
3045 | |
3046 | ObjCInterfaceDecl *SClass = ID->getSuperClass(); |
3047 | if (SClass) { |
3048 | llvm::DIType *SClassTy = |
3049 | getOrCreateType(Ty: CGM.getContext().getObjCInterfaceType(Decl: SClass), Fg: Unit); |
3050 | if (!SClassTy) |
3051 | return nullptr; |
3052 | |
3053 | llvm::DIType *InhTag = DBuilder.createInheritance(Ty: RealDecl, BaseTy: SClassTy, BaseOffset: 0, VBPtrOffset: 0, |
3054 | Flags: llvm::DINode::FlagZero); |
3055 | EltTys.push_back(Elt: InhTag); |
3056 | } |
3057 | |
3058 | // Create entries for all of the properties. |
3059 | auto AddProperty = [&](const ObjCPropertyDecl *PD) { |
3060 | SourceLocation Loc = PD->getLocation(); |
3061 | llvm::DIFile *PUnit = getOrCreateFile(Loc); |
3062 | unsigned PLine = getLineNumber(Loc); |
3063 | ObjCMethodDecl *Getter = PD->getGetterMethodDecl(); |
3064 | ObjCMethodDecl *Setter = PD->getSetterMethodDecl(); |
3065 | llvm::MDNode *PropertyNode = DBuilder.createObjCProperty( |
3066 | Name: PD->getName(), File: PUnit, LineNumber: PLine, |
3067 | GetterName: hasDefaultGetterName(PD, Getter) ? "" |
3068 | : getSelectorName(S: PD->getGetterName()), |
3069 | SetterName: hasDefaultSetterName(PD, Setter) ? "" |
3070 | : getSelectorName(S: PD->getSetterName()), |
3071 | PropertyAttributes: PD->getPropertyAttributes(), Ty: getOrCreateType(Ty: PD->getType(), Fg: PUnit)); |
3072 | EltTys.push_back(Elt: PropertyNode); |
3073 | }; |
3074 | { |
3075 | // Use 'char' for the isClassProperty bit as DenseSet requires space for |
3076 | // empty/tombstone keys in the data type (and bool is too small for that). |
3077 | typedef std::pair<char, const IdentifierInfo *> IsClassAndIdent; |
3078 | /// List of already emitted properties. Two distinct class and instance |
3079 | /// properties can share the same identifier (but not two instance |
3080 | /// properties or two class properties). |
3081 | llvm::DenseSet<IsClassAndIdent> PropertySet; |
3082 | /// Returns the IsClassAndIdent key for the given property. |
3083 | auto GetIsClassAndIdent = [](const ObjCPropertyDecl *PD) { |
3084 | return std::make_pair(PD->isClassProperty(), PD->getIdentifier()); |
3085 | }; |
3086 | for (const ObjCCategoryDecl *ClassExt : ID->known_extensions()) |
3087 | for (auto *PD : ClassExt->properties()) { |
3088 | PropertySet.insert(GetIsClassAndIdent(PD)); |
3089 | AddProperty(PD); |
3090 | } |
3091 | for (const auto *PD : ID->properties()) { |
3092 | // Don't emit duplicate metadata for properties that were already in a |
3093 | // class extension. |
3094 | if (!PropertySet.insert(GetIsClassAndIdent(PD)).second) |
3095 | continue; |
3096 | AddProperty(PD); |
3097 | } |
3098 | } |
3099 | |
3100 | const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(D: ID); |
3101 | unsigned FieldNo = 0; |
3102 | for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field; |
3103 | Field = Field->getNextIvar(), ++FieldNo) { |
3104 | llvm::DIType *FieldTy = getOrCreateType(Ty: Field->getType(), Fg: Unit); |
3105 | if (!FieldTy) |
3106 | return nullptr; |
3107 | |
3108 | StringRef FieldName = Field->getName(); |
3109 | |
3110 | // Ignore unnamed fields. |
3111 | if (FieldName.empty()) |
3112 | continue; |
3113 | |
3114 | // Get the location for the field. |
3115 | llvm::DIFile *FieldDefUnit = getOrCreateFile(Loc: Field->getLocation()); |
3116 | unsigned FieldLine = getLineNumber(Loc: Field->getLocation()); |
3117 | QualType FType = Field->getType(); |
3118 | uint64_t FieldSize = 0; |
3119 | uint32_t FieldAlign = 0; |
3120 | |
3121 | if (!FType->isIncompleteArrayType()) { |
3122 | |
3123 | // Bit size, align and offset of the type. |
3124 | FieldSize = Field->isBitField() |
3125 | ? Field->getBitWidthValue(CGM.getContext()) |
3126 | : CGM.getContext().getTypeSize(T: FType); |
3127 | FieldAlign = getTypeAlignIfRequired(Ty: FType, Ctx: CGM.getContext()); |
3128 | } |
3129 | |
3130 | uint64_t FieldOffset; |
3131 | if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) { |
3132 | // We don't know the runtime offset of an ivar if we're using the |
3133 | // non-fragile ABI. For bitfields, use the bit offset into the first |
3134 | // byte of storage of the bitfield. For other fields, use zero. |
3135 | if (Field->isBitField()) { |
3136 | FieldOffset = |
3137 | CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Ivar: Field); |
3138 | FieldOffset %= CGM.getContext().getCharWidth(); |
3139 | } else { |
3140 | FieldOffset = 0; |
3141 | } |
3142 | } else { |
3143 | FieldOffset = RL.getFieldOffset(FieldNo); |
3144 | } |
3145 | |
3146 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
3147 | if (Field->getAccessControl() == ObjCIvarDecl::Protected) |
3148 | Flags = llvm::DINode::FlagProtected; |
3149 | else if (Field->getAccessControl() == ObjCIvarDecl::Private) |
3150 | Flags = llvm::DINode::FlagPrivate; |
3151 | else if (Field->getAccessControl() == ObjCIvarDecl::Public) |
3152 | Flags = llvm::DINode::FlagPublic; |
3153 | |
3154 | if (Field->isBitField()) |
3155 | Flags |= llvm::DINode::FlagBitField; |
3156 | |
3157 | llvm::MDNode *PropertyNode = nullptr; |
3158 | if (ObjCImplementationDecl *ImpD = ID->getImplementation()) { |
3159 | if (ObjCPropertyImplDecl *PImpD = |
3160 | ImpD->FindPropertyImplIvarDecl(ivarId: Field->getIdentifier())) { |
3161 | if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) { |
3162 | SourceLocation Loc = PD->getLocation(); |
3163 | llvm::DIFile *PUnit = getOrCreateFile(Loc); |
3164 | unsigned PLine = getLineNumber(Loc); |
3165 | ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl(); |
3166 | ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl(); |
3167 | PropertyNode = DBuilder.createObjCProperty( |
3168 | Name: PD->getName(), File: PUnit, LineNumber: PLine, |
3169 | GetterName: hasDefaultGetterName(PD, Getter) |
3170 | ? "" |
3171 | : getSelectorName(S: PD->getGetterName()), |
3172 | SetterName: hasDefaultSetterName(PD, Setter) |
3173 | ? "" |
3174 | : getSelectorName(S: PD->getSetterName()), |
3175 | PropertyAttributes: PD->getPropertyAttributes(), |
3176 | Ty: getOrCreateType(Ty: PD->getType(), Fg: PUnit)); |
3177 | } |
3178 | } |
3179 | } |
3180 | FieldTy = DBuilder.createObjCIVar(Name: FieldName, File: FieldDefUnit, LineNo: FieldLine, |
3181 | SizeInBits: FieldSize, AlignInBits: FieldAlign, OffsetInBits: FieldOffset, Flags, |
3182 | Ty: FieldTy, PropertyNode); |
3183 | EltTys.push_back(Elt: FieldTy); |
3184 | } |
3185 | |
3186 | llvm::DINodeArray Elements = DBuilder.getOrCreateArray(Elements: EltTys); |
3187 | DBuilder.replaceArrays(T&: RealDecl, Elements); |
3188 | |
3189 | LexicalBlockStack.pop_back(); |
3190 | return RealDecl; |
3191 | } |
3192 | |
3193 | llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty, |
3194 | llvm::DIFile *Unit) { |
3195 | if (Ty->isExtVectorBoolType()) { |
3196 | // Boolean ext_vector_type(N) are special because their real element type |
3197 | // (bits of bit size) is not their Clang element type (_Bool of size byte). |
3198 | // For now, we pretend the boolean vector were actually a vector of bytes |
3199 | // (where each byte represents 8 bits of the actual vector). |
3200 | // FIXME Debug info should actually represent this proper as a vector mask |
3201 | // type. |
3202 | auto &Ctx = CGM.getContext(); |
3203 | uint64_t Size = CGM.getContext().getTypeSize(Ty); |
3204 | uint64_t NumVectorBytes = Size / Ctx.getCharWidth(); |
3205 | |
3206 | // Construct the vector of 'char' type. |
3207 | QualType CharVecTy = |
3208 | Ctx.getVectorType(VectorType: Ctx.CharTy, NumElts: NumVectorBytes, VecKind: VectorKind::Generic); |
3209 | return CreateType(Ty: CharVecTy->getAs<VectorType>(), Unit); |
3210 | } |
3211 | |
3212 | llvm::DIType *ElementTy = getOrCreateType(Ty: Ty->getElementType(), Fg: Unit); |
3213 | int64_t Count = Ty->getNumElements(); |
3214 | |
3215 | llvm::Metadata *Subscript; |
3216 | QualType QTy(Ty, 0); |
3217 | auto SizeExpr = SizeExprCache.find(QTy); |
3218 | if (SizeExpr != SizeExprCache.end()) |
3219 | Subscript = DBuilder.getOrCreateSubrange( |
3220 | SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/, |
3221 | nullptr /*upperBound*/, nullptr /*stride*/); |
3222 | else { |
3223 | auto *CountNode = |
3224 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::getSigned( |
3225 | Ty: llvm::Type::getInt64Ty(C&: CGM.getLLVMContext()), V: Count ? Count : -1)); |
3226 | Subscript = DBuilder.getOrCreateSubrange( |
3227 | Count: CountNode /*count*/, LowerBound: nullptr /*lowerBound*/, UpperBound: nullptr /*upperBound*/, |
3228 | Stride: nullptr /*stride*/); |
3229 | } |
3230 | llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Elements: Subscript); |
3231 | |
3232 | uint64_t Size = CGM.getContext().getTypeSize(Ty); |
3233 | auto Align = getTypeAlignIfRequired(Ty, CGM.getContext()); |
3234 | |
3235 | return DBuilder.createVectorType(Size, AlignInBits: Align, Ty: ElementTy, Subscripts: SubscriptArray); |
3236 | } |
3237 | |
3238 | llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty, |
3239 | llvm::DIFile *Unit) { |
3240 | // FIXME: Create another debug type for matrices |
3241 | // For the time being, it treats it like a nested ArrayType. |
3242 | |
3243 | llvm::DIType *ElementTy = getOrCreateType(Ty: Ty->getElementType(), Fg: Unit); |
3244 | uint64_t Size = CGM.getContext().getTypeSize(Ty); |
3245 | uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext()); |
3246 | |
3247 | // Create ranges for both dimensions. |
3248 | llvm::SmallVector<llvm::Metadata *, 2> Subscripts; |
3249 | auto *ColumnCountNode = |
3250 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::getSigned( |
3251 | Ty: llvm::Type::getInt64Ty(C&: CGM.getLLVMContext()), V: Ty->getNumColumns())); |
3252 | auto *RowCountNode = |
3253 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::getSigned( |
3254 | Ty: llvm::Type::getInt64Ty(C&: CGM.getLLVMContext()), V: Ty->getNumRows())); |
3255 | Subscripts.push_back(Elt: DBuilder.getOrCreateSubrange( |
3256 | Count: ColumnCountNode /*count*/, LowerBound: nullptr /*lowerBound*/, UpperBound: nullptr /*upperBound*/, |
3257 | Stride: nullptr /*stride*/)); |
3258 | Subscripts.push_back(Elt: DBuilder.getOrCreateSubrange( |
3259 | Count: RowCountNode /*count*/, LowerBound: nullptr /*lowerBound*/, UpperBound: nullptr /*upperBound*/, |
3260 | Stride: nullptr /*stride*/)); |
3261 | llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Elements: Subscripts); |
3262 | return DBuilder.createArrayType(Size, AlignInBits: Align, Ty: ElementTy, Subscripts: SubscriptArray); |
3263 | } |
3264 | |
3265 | llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) { |
3266 | uint64_t Size; |
3267 | uint32_t Align; |
3268 | |
3269 | // FIXME: make getTypeAlign() aware of VLAs and incomplete array types |
3270 | if (const auto *VAT = dyn_cast<VariableArrayType>(Val: Ty)) { |
3271 | Size = 0; |
3272 | Align = getTypeAlignIfRequired(Ty: CGM.getContext().getBaseElementType(VAT), |
3273 | Ctx: CGM.getContext()); |
3274 | } else if (Ty->isIncompleteArrayType()) { |
3275 | Size = 0; |
3276 | if (Ty->getElementType()->isIncompleteType()) |
3277 | Align = 0; |
3278 | else |
3279 | Align = getTypeAlignIfRequired(Ty: Ty->getElementType(), Ctx: CGM.getContext()); |
3280 | } else if (Ty->isIncompleteType()) { |
3281 | Size = 0; |
3282 | Align = 0; |
3283 | } else { |
3284 | // Size and align of the whole array, not the element type. |
3285 | Size = CGM.getContext().getTypeSize(Ty); |
3286 | Align = getTypeAlignIfRequired(Ty, CGM.getContext()); |
3287 | } |
3288 | |
3289 | // Add the dimensions of the array. FIXME: This loses CV qualifiers from |
3290 | // interior arrays, do we care? Why aren't nested arrays represented the |
3291 | // obvious/recursive way? |
3292 | SmallVector<llvm::Metadata *, 8> Subscripts; |
3293 | QualType EltTy(Ty, 0); |
3294 | while ((Ty = dyn_cast<ArrayType>(Val&: EltTy))) { |
3295 | // If the number of elements is known, then count is that number. Otherwise, |
3296 | // it's -1. This allows us to represent a subrange with an array of 0 |
3297 | // elements, like this: |
3298 | // |
3299 | // struct foo { |
3300 | // int x[0]; |
3301 | // }; |
3302 | int64_t Count = -1; // Count == -1 is an unbounded array. |
3303 | if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: Ty)) |
3304 | Count = CAT->getZExtSize(); |
3305 | else if (const auto *VAT = dyn_cast<VariableArrayType>(Val: Ty)) { |
3306 | if (Expr *Size = VAT->getSizeExpr()) { |
3307 | Expr::EvalResult Result; |
3308 | if (Size->EvaluateAsInt(Result, Ctx: CGM.getContext())) |
3309 | Count = Result.Val.getInt().getExtValue(); |
3310 | } |
3311 | } |
3312 | |
3313 | auto SizeNode = SizeExprCache.find(EltTy); |
3314 | if (SizeNode != SizeExprCache.end()) |
3315 | Subscripts.push_back(Elt: DBuilder.getOrCreateSubrange( |
3316 | SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/, |
3317 | nullptr /*upperBound*/, nullptr /*stride*/)); |
3318 | else { |
3319 | auto *CountNode = |
3320 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::getSigned( |
3321 | Ty: llvm::Type::getInt64Ty(C&: CGM.getLLVMContext()), V: Count)); |
3322 | Subscripts.push_back(Elt: DBuilder.getOrCreateSubrange( |
3323 | Count: CountNode /*count*/, LowerBound: nullptr /*lowerBound*/, UpperBound: nullptr /*upperBound*/, |
3324 | Stride: nullptr /*stride*/)); |
3325 | } |
3326 | EltTy = Ty->getElementType(); |
3327 | } |
3328 | |
3329 | llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Elements: Subscripts); |
3330 | |
3331 | return DBuilder.createArrayType(Size, AlignInBits: Align, Ty: getOrCreateType(Ty: EltTy, Fg: Unit), |
3332 | Subscripts: SubscriptArray); |
3333 | } |
3334 | |
3335 | llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty, |
3336 | llvm::DIFile *Unit) { |
3337 | return CreatePointerLikeType(Tag: llvm::dwarf::DW_TAG_reference_type, Ty, |
3338 | PointeeTy: Ty->getPointeeType(), Unit); |
3339 | } |
3340 | |
3341 | llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty, |
3342 | llvm::DIFile *Unit) { |
3343 | llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type; |
3344 | // DW_TAG_rvalue_reference_type was introduced in DWARF 4. |
3345 | if (CGM.getCodeGenOpts().DebugStrictDwarf && |
3346 | CGM.getCodeGenOpts().DwarfVersion < 4) |
3347 | Tag = llvm::dwarf::DW_TAG_reference_type; |
3348 | |
3349 | return CreatePointerLikeType(Tag, Ty, PointeeTy: Ty->getPointeeType(), Unit); |
3350 | } |
3351 | |
3352 | llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty, |
3353 | llvm::DIFile *U) { |
3354 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
3355 | uint64_t Size = 0; |
3356 | |
3357 | if (!Ty->isIncompleteType()) { |
3358 | Size = CGM.getContext().getTypeSize(Ty); |
3359 | |
3360 | // Set the MS inheritance model. There is no flag for the unspecified model. |
3361 | if (CGM.getTarget().getCXXABI().isMicrosoft()) { |
3362 | switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) { |
3363 | case MSInheritanceModel::Single: |
3364 | Flags |= llvm::DINode::FlagSingleInheritance; |
3365 | break; |
3366 | case MSInheritanceModel::Multiple: |
3367 | Flags |= llvm::DINode::FlagMultipleInheritance; |
3368 | break; |
3369 | case MSInheritanceModel::Virtual: |
3370 | Flags |= llvm::DINode::FlagVirtualInheritance; |
3371 | break; |
3372 | case MSInheritanceModel::Unspecified: |
3373 | break; |
3374 | } |
3375 | } |
3376 | } |
3377 | |
3378 | llvm::DIType *ClassType = getOrCreateType(Ty: QualType(Ty->getClass(), 0), Fg: U); |
3379 | if (Ty->isMemberDataPointerType()) |
3380 | return DBuilder.createMemberPointerType( |
3381 | PointeeTy: getOrCreateType(Ty: Ty->getPointeeType(), Fg: U), Class: ClassType, SizeInBits: Size, /*Align=*/AlignInBits: 0, |
3382 | Flags); |
3383 | |
3384 | const FunctionProtoType *FPT = |
3385 | Ty->getPointeeType()->castAs<FunctionProtoType>(); |
3386 | return DBuilder.createMemberPointerType( |
3387 | PointeeTy: getOrCreateInstanceMethodType( |
3388 | ThisPtr: CXXMethodDecl::getThisType(FPT, Decl: Ty->getMostRecentCXXRecordDecl()), |
3389 | Func: FPT, Unit: U), |
3390 | Class: ClassType, SizeInBits: Size, /*Align=*/AlignInBits: 0, Flags); |
3391 | } |
3392 | |
3393 | llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) { |
3394 | auto *FromTy = getOrCreateType(Ty: Ty->getValueType(), Fg: U); |
3395 | return DBuilder.createQualifiedType(Tag: llvm::dwarf::DW_TAG_atomic_type, FromTy); |
3396 | } |
3397 | |
3398 | llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) { |
3399 | return getOrCreateType(Ty: Ty->getElementType(), Fg: U); |
3400 | } |
3401 | |
3402 | llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) { |
3403 | const EnumDecl *ED = Ty->getDecl(); |
3404 | |
3405 | uint64_t Size = 0; |
3406 | uint32_t Align = 0; |
3407 | if (!ED->getTypeForDecl()->isIncompleteType()) { |
3408 | Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); |
3409 | Align = getDeclAlignIfRequired(ED, CGM.getContext()); |
3410 | } |
3411 | |
3412 | SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); |
3413 | |
3414 | bool isImportedFromModule = |
3415 | DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition(); |
3416 | |
3417 | // If this is just a forward declaration, construct an appropriately |
3418 | // marked node and just return it. |
3419 | if (isImportedFromModule || !ED->getDefinition()) { |
3420 | // Note that it is possible for enums to be created as part of |
3421 | // their own declcontext. In this case a FwdDecl will be created |
3422 | // twice. This doesn't cause a problem because both FwdDecls are |
3423 | // entered into the ReplaceMap: finalize() will replace the first |
3424 | // FwdDecl with the second and then replace the second with |
3425 | // complete type. |
3426 | llvm::DIScope *EDContext = getDeclContextDescriptor(ED); |
3427 | llvm::DIFile *DefUnit = getOrCreateFile(Loc: ED->getLocation()); |
3428 | llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType( |
3429 | Tag: llvm::dwarf::DW_TAG_enumeration_type, Name: "" , Scope: TheCU, F: DefUnit, Line: 0)); |
3430 | |
3431 | unsigned Line = getLineNumber(Loc: ED->getLocation()); |
3432 | StringRef EDName = ED->getName(); |
3433 | llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType( |
3434 | Tag: llvm::dwarf::DW_TAG_enumeration_type, Name: EDName, Scope: EDContext, F: DefUnit, Line, |
3435 | RuntimeLang: 0, SizeInBits: Size, AlignInBits: Align, Flags: llvm::DINode::FlagFwdDecl, UniqueIdentifier: Identifier); |
3436 | |
3437 | ReplaceMap.emplace_back( |
3438 | args: std::piecewise_construct, args: std::make_tuple(args&: Ty), |
3439 | args: std::make_tuple(args: static_cast<llvm::Metadata *>(RetTy))); |
3440 | return RetTy; |
3441 | } |
3442 | |
3443 | return CreateTypeDefinition(Ty); |
3444 | } |
3445 | |
3446 | llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) { |
3447 | const EnumDecl *ED = Ty->getDecl(); |
3448 | uint64_t Size = 0; |
3449 | uint32_t Align = 0; |
3450 | if (!ED->getTypeForDecl()->isIncompleteType()) { |
3451 | Size = CGM.getContext().getTypeSize(ED->getTypeForDecl()); |
3452 | Align = getDeclAlignIfRequired(ED, CGM.getContext()); |
3453 | } |
3454 | |
3455 | SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); |
3456 | |
3457 | SmallVector<llvm::Metadata *, 16> Enumerators; |
3458 | ED = ED->getDefinition(); |
3459 | for (const auto *Enum : ED->enumerators()) { |
3460 | Enumerators.push_back( |
3461 | Elt: DBuilder.createEnumerator(Enum->getName(), Enum->getInitVal())); |
3462 | } |
3463 | |
3464 | // Return a CompositeType for the enum itself. |
3465 | llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Elements: Enumerators); |
3466 | |
3467 | llvm::DIFile *DefUnit = getOrCreateFile(Loc: ED->getLocation()); |
3468 | unsigned Line = getLineNumber(Loc: ED->getLocation()); |
3469 | llvm::DIScope *EnumContext = getDeclContextDescriptor(ED); |
3470 | llvm::DIType *ClassTy = getOrCreateType(Ty: ED->getIntegerType(), Fg: DefUnit); |
3471 | return DBuilder.createEnumerationType( |
3472 | Scope: EnumContext, Name: ED->getName(), File: DefUnit, LineNumber: Line, SizeInBits: Size, AlignInBits: Align, Elements: EltArray, UnderlyingType: ClassTy, |
3473 | /*RunTimeLang=*/0, UniqueIdentifier: Identifier, IsScoped: ED->isScoped()); |
3474 | } |
3475 | |
3476 | llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent, |
3477 | unsigned MType, SourceLocation LineLoc, |
3478 | StringRef Name, StringRef Value) { |
3479 | unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(Loc: LineLoc); |
3480 | return DBuilder.createMacro(Parent, Line, MacroType: MType, Name, Value); |
3481 | } |
3482 | |
3483 | llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent, |
3484 | SourceLocation LineLoc, |
3485 | SourceLocation FileLoc) { |
3486 | llvm::DIFile *FName = getOrCreateFile(Loc: FileLoc); |
3487 | unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(Loc: LineLoc); |
3488 | return DBuilder.createTempMacroFile(Parent, Line, File: FName); |
3489 | } |
3490 | |
3491 | static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) { |
3492 | Qualifiers Quals; |
3493 | do { |
3494 | Qualifiers InnerQuals = T.getLocalQualifiers(); |
3495 | // Qualifiers::operator+() doesn't like it if you add a Qualifier |
3496 | // that is already there. |
3497 | Quals += Qualifiers::removeCommonQualifiers(L&: Quals, R&: InnerQuals); |
3498 | Quals += InnerQuals; |
3499 | QualType LastT = T; |
3500 | switch (T->getTypeClass()) { |
3501 | default: |
3502 | return C.getQualifiedType(T: T.getTypePtr(), Qs: Quals); |
3503 | case Type::TemplateSpecialization: { |
3504 | const auto *Spec = cast<TemplateSpecializationType>(Val&: T); |
3505 | if (Spec->isTypeAlias()) |
3506 | return C.getQualifiedType(T: T.getTypePtr(), Qs: Quals); |
3507 | T = Spec->desugar(); |
3508 | break; |
3509 | } |
3510 | case Type::TypeOfExpr: |
3511 | T = cast<TypeOfExprType>(Val&: T)->getUnderlyingExpr()->getType(); |
3512 | break; |
3513 | case Type::TypeOf: |
3514 | T = cast<TypeOfType>(Val&: T)->getUnmodifiedType(); |
3515 | break; |
3516 | case Type::Decltype: |
3517 | T = cast<DecltypeType>(Val&: T)->getUnderlyingType(); |
3518 | break; |
3519 | case Type::UnaryTransform: |
3520 | T = cast<UnaryTransformType>(Val&: T)->getUnderlyingType(); |
3521 | break; |
3522 | case Type::Attributed: |
3523 | T = cast<AttributedType>(Val&: T)->getEquivalentType(); |
3524 | break; |
3525 | case Type::BTFTagAttributed: |
3526 | T = cast<BTFTagAttributedType>(Val&: T)->getWrappedType(); |
3527 | break; |
3528 | case Type::CountAttributed: |
3529 | T = cast<CountAttributedType>(Val&: T)->desugar(); |
3530 | break; |
3531 | case Type::Elaborated: |
3532 | T = cast<ElaboratedType>(Val&: T)->getNamedType(); |
3533 | break; |
3534 | case Type::Using: |
3535 | T = cast<UsingType>(Val&: T)->getUnderlyingType(); |
3536 | break; |
3537 | case Type::Paren: |
3538 | T = cast<ParenType>(Val&: T)->getInnerType(); |
3539 | break; |
3540 | case Type::MacroQualified: |
3541 | T = cast<MacroQualifiedType>(Val&: T)->getUnderlyingType(); |
3542 | break; |
3543 | case Type::SubstTemplateTypeParm: |
3544 | T = cast<SubstTemplateTypeParmType>(Val&: T)->getReplacementType(); |
3545 | break; |
3546 | case Type::Auto: |
3547 | case Type::DeducedTemplateSpecialization: { |
3548 | QualType DT = cast<DeducedType>(Val&: T)->getDeducedType(); |
3549 | assert(!DT.isNull() && "Undeduced types shouldn't reach here." ); |
3550 | T = DT; |
3551 | break; |
3552 | } |
3553 | case Type::PackIndexing: { |
3554 | T = cast<PackIndexingType>(Val&: T)->getSelectedType(); |
3555 | break; |
3556 | } |
3557 | case Type::Adjusted: |
3558 | case Type::Decayed: |
3559 | // Decayed and adjusted types use the adjusted type in LLVM and DWARF. |
3560 | T = cast<AdjustedType>(Val&: T)->getAdjustedType(); |
3561 | break; |
3562 | } |
3563 | |
3564 | assert(T != LastT && "Type unwrapping failed to unwrap!" ); |
3565 | (void)LastT; |
3566 | } while (true); |
3567 | } |
3568 | |
3569 | llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) { |
3570 | assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext())); |
3571 | auto It = TypeCache.find(Val: Ty.getAsOpaquePtr()); |
3572 | if (It != TypeCache.end()) { |
3573 | // Verify that the debug info still exists. |
3574 | if (llvm::Metadata *V = It->second) |
3575 | return cast<llvm::DIType>(Val: V); |
3576 | } |
3577 | |
3578 | return nullptr; |
3579 | } |
3580 | |
3581 | void CGDebugInfo::completeTemplateDefinition( |
3582 | const ClassTemplateSpecializationDecl &SD) { |
3583 | completeUnusedClass(SD); |
3584 | } |
3585 | |
3586 | void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) { |
3587 | if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly || |
3588 | D.isDynamicClass()) |
3589 | return; |
3590 | |
3591 | completeClassData(&D); |
3592 | // In case this type has no member function definitions being emitted, ensure |
3593 | // it is retained |
3594 | RetainedTypes.push_back(x: CGM.getContext().getRecordType(&D).getAsOpaquePtr()); |
3595 | } |
3596 | |
3597 | llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) { |
3598 | if (Ty.isNull()) |
3599 | return nullptr; |
3600 | |
3601 | llvm::TimeTraceScope TimeScope("DebugType" , [&]() { |
3602 | std::string Name; |
3603 | llvm::raw_string_ostream OS(Name); |
3604 | Ty.print(OS, Policy: getPrintingPolicy()); |
3605 | return Name; |
3606 | }); |
3607 | |
3608 | // Unwrap the type as needed for debug information. |
3609 | Ty = UnwrapTypeForDebugInfo(T: Ty, C: CGM.getContext()); |
3610 | |
3611 | if (auto *T = getTypeOrNull(Ty)) |
3612 | return T; |
3613 | |
3614 | llvm::DIType *Res = CreateTypeNode(Ty, Fg: Unit); |
3615 | void *TyPtr = Ty.getAsOpaquePtr(); |
3616 | |
3617 | // And update the type cache. |
3618 | TypeCache[TyPtr].reset(MD: Res); |
3619 | |
3620 | return Res; |
3621 | } |
3622 | |
3623 | llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) { |
3624 | // A forward declaration inside a module header does not belong to the module. |
3625 | if (isa<RecordDecl>(Val: D) && !cast<RecordDecl>(Val: D)->getDefinition()) |
3626 | return nullptr; |
3627 | if (DebugTypeExtRefs && D->isFromASTFile()) { |
3628 | // Record a reference to an imported clang module or precompiled header. |
3629 | auto *Reader = CGM.getContext().getExternalSource(); |
3630 | auto Idx = D->getOwningModuleID(); |
3631 | auto Info = Reader->getSourceDescriptor(ID: Idx); |
3632 | if (Info) |
3633 | return getOrCreateModuleRef(Mod: *Info, /*SkeletonCU=*/CreateSkeletonCU: true); |
3634 | } else if (ClangModuleMap) { |
3635 | // We are building a clang module or a precompiled header. |
3636 | // |
3637 | // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies |
3638 | // and it wouldn't be necessary to specify the parent scope |
3639 | // because the type is already unique by definition (it would look |
3640 | // like the output of -fno-standalone-debug). On the other hand, |
3641 | // the parent scope helps a consumer to quickly locate the object |
3642 | // file where the type's definition is located, so it might be |
3643 | // best to make this behavior a command line or debugger tuning |
3644 | // option. |
3645 | if (Module *M = D->getOwningModule()) { |
3646 | // This is a (sub-)module. |
3647 | auto Info = ASTSourceDescriptor(*M); |
3648 | return getOrCreateModuleRef(Mod: Info, /*SkeletonCU=*/CreateSkeletonCU: false); |
3649 | } else { |
3650 | // This the precompiled header being built. |
3651 | return getOrCreateModuleRef(Mod: PCHDescriptor, /*SkeletonCU=*/CreateSkeletonCU: false); |
3652 | } |
3653 | } |
3654 | |
3655 | return nullptr; |
3656 | } |
3657 | |
3658 | llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) { |
3659 | // Handle qualifiers, which recursively handles what they refer to. |
3660 | if (Ty.hasLocalQualifiers()) |
3661 | return CreateQualifiedType(Ty, Unit); |
3662 | |
3663 | // Work out details of type. |
3664 | switch (Ty->getTypeClass()) { |
3665 | #define TYPE(Class, Base) |
3666 | #define ABSTRACT_TYPE(Class, Base) |
3667 | #define NON_CANONICAL_TYPE(Class, Base) |
3668 | #define DEPENDENT_TYPE(Class, Base) case Type::Class: |
3669 | #include "clang/AST/TypeNodes.inc" |
3670 | llvm_unreachable("Dependent types cannot show up in debug information" ); |
3671 | |
3672 | case Type::ExtVector: |
3673 | case Type::Vector: |
3674 | return CreateType(cast<VectorType>(Ty), Unit); |
3675 | case Type::ConstantMatrix: |
3676 | return CreateType(cast<ConstantMatrixType>(Ty), Unit); |
3677 | case Type::ObjCObjectPointer: |
3678 | return CreateType(cast<ObjCObjectPointerType>(Ty), Unit); |
3679 | case Type::ObjCObject: |
3680 | return CreateType(cast<ObjCObjectType>(Ty), Unit); |
3681 | case Type::ObjCTypeParam: |
3682 | return CreateType(cast<ObjCTypeParamType>(Ty), Unit); |
3683 | case Type::ObjCInterface: |
3684 | return CreateType(cast<ObjCInterfaceType>(Ty), Unit); |
3685 | case Type::Builtin: |
3686 | return CreateType(cast<BuiltinType>(Ty)); |
3687 | case Type::Complex: |
3688 | return CreateType(cast<ComplexType>(Ty)); |
3689 | case Type::Pointer: |
3690 | return CreateType(cast<PointerType>(Ty), Unit); |
3691 | case Type::BlockPointer: |
3692 | return CreateType(cast<BlockPointerType>(Ty), Unit); |
3693 | case Type::Typedef: |
3694 | return CreateType(cast<TypedefType>(Ty), Unit); |
3695 | case Type::Record: |
3696 | return CreateType(cast<RecordType>(Ty)); |
3697 | case Type::Enum: |
3698 | return CreateEnumType(Ty: cast<EnumType>(Ty)); |
3699 | case Type::FunctionProto: |
3700 | case Type::FunctionNoProto: |
3701 | return CreateType(cast<FunctionType>(Ty), Unit); |
3702 | case Type::ConstantArray: |
3703 | case Type::VariableArray: |
3704 | case Type::IncompleteArray: |
3705 | case Type::ArrayParameter: |
3706 | return CreateType(cast<ArrayType>(Ty), Unit); |
3707 | |
3708 | case Type::LValueReference: |
3709 | return CreateType(cast<LValueReferenceType>(Ty), Unit); |
3710 | case Type::RValueReference: |
3711 | return CreateType(cast<RValueReferenceType>(Ty), Unit); |
3712 | |
3713 | case Type::MemberPointer: |
3714 | return CreateType(cast<MemberPointerType>(Ty), Unit); |
3715 | |
3716 | case Type::Atomic: |
3717 | return CreateType(cast<AtomicType>(Ty), Unit); |
3718 | |
3719 | case Type::BitInt: |
3720 | return CreateType(cast<BitIntType>(Ty)); |
3721 | case Type::Pipe: |
3722 | return CreateType(cast<PipeType>(Ty), Unit); |
3723 | |
3724 | case Type::TemplateSpecialization: |
3725 | return CreateType(cast<TemplateSpecializationType>(Ty), Unit); |
3726 | |
3727 | case Type::CountAttributed: |
3728 | case Type::Auto: |
3729 | case Type::Attributed: |
3730 | case Type::BTFTagAttributed: |
3731 | case Type::Adjusted: |
3732 | case Type::Decayed: |
3733 | case Type::DeducedTemplateSpecialization: |
3734 | case Type::Elaborated: |
3735 | case Type::Using: |
3736 | case Type::Paren: |
3737 | case Type::MacroQualified: |
3738 | case Type::SubstTemplateTypeParm: |
3739 | case Type::TypeOfExpr: |
3740 | case Type::TypeOf: |
3741 | case Type::Decltype: |
3742 | case Type::PackIndexing: |
3743 | case Type::UnaryTransform: |
3744 | break; |
3745 | } |
3746 | |
3747 | llvm_unreachable("type should have been unwrapped!" ); |
3748 | } |
3749 | |
3750 | llvm::DICompositeType * |
3751 | CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) { |
3752 | QualType QTy(Ty, 0); |
3753 | |
3754 | auto *T = cast_or_null<llvm::DICompositeType>(Val: getTypeOrNull(Ty: QTy)); |
3755 | |
3756 | // We may have cached a forward decl when we could have created |
3757 | // a non-forward decl. Go ahead and create a non-forward decl |
3758 | // now. |
3759 | if (T && !T->isForwardDecl()) |
3760 | return T; |
3761 | |
3762 | // Otherwise create the type. |
3763 | llvm::DICompositeType *Res = CreateLimitedType(Ty); |
3764 | |
3765 | // Propagate members from the declaration to the definition |
3766 | // CreateType(const RecordType*) will overwrite this with the members in the |
3767 | // correct order if the full type is needed. |
3768 | DBuilder.replaceArrays(T&: Res, Elements: T ? T->getElements() : llvm::DINodeArray()); |
3769 | |
3770 | // And update the type cache. |
3771 | TypeCache[QTy.getAsOpaquePtr()].reset(MD: Res); |
3772 | return Res; |
3773 | } |
3774 | |
3775 | // TODO: Currently used for context chains when limiting debug info. |
3776 | llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) { |
3777 | RecordDecl *RD = Ty->getDecl(); |
3778 | |
3779 | // Get overall information about the record type for the debug info. |
3780 | StringRef RDName = getClassName(RD); |
3781 | const SourceLocation Loc = RD->getLocation(); |
3782 | llvm::DIFile *DefUnit = nullptr; |
3783 | unsigned Line = 0; |
3784 | if (Loc.isValid()) { |
3785 | DefUnit = getOrCreateFile(Loc); |
3786 | Line = getLineNumber(Loc); |
3787 | } |
3788 | |
3789 | llvm::DIScope *RDContext = getDeclContextDescriptor(RD); |
3790 | |
3791 | // If we ended up creating the type during the context chain construction, |
3792 | // just return that. |
3793 | auto *T = cast_or_null<llvm::DICompositeType>( |
3794 | Val: getTypeOrNull(Ty: CGM.getContext().getRecordType(Decl: RD))); |
3795 | if (T && (!T->isForwardDecl() || !RD->getDefinition())) |
3796 | return T; |
3797 | |
3798 | // If this is just a forward or incomplete declaration, construct an |
3799 | // appropriately marked node and just return it. |
3800 | const RecordDecl *D = RD->getDefinition(); |
3801 | if (!D || !D->isCompleteDefinition()) |
3802 | return getOrCreateRecordFwdDecl(Ty, Ctx: RDContext); |
3803 | |
3804 | uint64_t Size = CGM.getContext().getTypeSize(Ty); |
3805 | // __attribute__((aligned)) can increase or decrease alignment *except* on a |
3806 | // struct or struct member, where it only increases alignment unless 'packed' |
3807 | // is also specified. To handle this case, the `getTypeAlignIfRequired` needs |
3808 | // to be used. |
3809 | auto Align = getTypeAlignIfRequired(Ty, CGM.getContext()); |
3810 | |
3811 | SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU); |
3812 | |
3813 | // Explicitly record the calling convention and export symbols for C++ |
3814 | // records. |
3815 | auto Flags = llvm::DINode::FlagZero; |
3816 | if (auto CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) { |
3817 | if (CGM.getCXXABI().getRecordArgABI(RD: CXXRD) == CGCXXABI::RAA_Indirect) |
3818 | Flags |= llvm::DINode::FlagTypePassByReference; |
3819 | else |
3820 | Flags |= llvm::DINode::FlagTypePassByValue; |
3821 | |
3822 | // Record if a C++ record is non-trivial type. |
3823 | if (!CXXRD->isTrivial()) |
3824 | Flags |= llvm::DINode::FlagNonTrivial; |
3825 | |
3826 | // Record exports it symbols to the containing structure. |
3827 | if (CXXRD->isAnonymousStructOrUnion()) |
3828 | Flags |= llvm::DINode::FlagExportSymbols; |
3829 | |
3830 | Flags |= getAccessFlag(CXXRD->getAccess(), |
3831 | dyn_cast<CXXRecordDecl>(CXXRD->getDeclContext())); |
3832 | } |
3833 | |
3834 | llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D); |
3835 | llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType( |
3836 | Tag: getTagForRecord(RD), Name: RDName, Scope: RDContext, F: DefUnit, Line, RuntimeLang: 0, SizeInBits: Size, AlignInBits: Align, |
3837 | Flags, UniqueIdentifier: Identifier, Annotations); |
3838 | |
3839 | // Elements of composite types usually have back to the type, creating |
3840 | // uniquing cycles. Distinct nodes are more efficient. |
3841 | switch (RealDecl->getTag()) { |
3842 | default: |
3843 | llvm_unreachable("invalid composite type tag" ); |
3844 | |
3845 | case llvm::dwarf::DW_TAG_array_type: |
3846 | case llvm::dwarf::DW_TAG_enumeration_type: |
3847 | // Array elements and most enumeration elements don't have back references, |
3848 | // so they don't tend to be involved in uniquing cycles and there is some |
3849 | // chance of merging them when linking together two modules. Only make |
3850 | // them distinct if they are ODR-uniqued. |
3851 | if (Identifier.empty()) |
3852 | break; |
3853 | [[fallthrough]]; |
3854 | |
3855 | case llvm::dwarf::DW_TAG_structure_type: |
3856 | case llvm::dwarf::DW_TAG_union_type: |
3857 | case llvm::dwarf::DW_TAG_class_type: |
3858 | // Immediately resolve to a distinct node. |
3859 | RealDecl = |
3860 | llvm::MDNode::replaceWithDistinct(N: llvm::TempDICompositeType(RealDecl)); |
3861 | break; |
3862 | } |
3863 | |
3864 | RegionMap[Ty->getDecl()].reset(RealDecl); |
3865 | TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(MD: RealDecl); |
3866 | |
3867 | if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD)) |
3868 | DBuilder.replaceArrays(T&: RealDecl, Elements: llvm::DINodeArray(), |
3869 | TParams: CollectCXXTemplateParams(TSpecial, DefUnit)); |
3870 | return RealDecl; |
3871 | } |
3872 | |
3873 | void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD, |
3874 | llvm::DICompositeType *RealDecl) { |
3875 | // A class's primary base or the class itself contains the vtable. |
3876 | llvm::DIType *ContainingType = nullptr; |
3877 | const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD); |
3878 | if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) { |
3879 | // Seek non-virtual primary base root. |
3880 | while (true) { |
3881 | const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase); |
3882 | const CXXRecordDecl *PBT = BRL.getPrimaryBase(); |
3883 | if (PBT && !BRL.isPrimaryBaseVirtual()) |
3884 | PBase = PBT; |
3885 | else |
3886 | break; |
3887 | } |
3888 | ContainingType = getOrCreateType(Ty: QualType(PBase->getTypeForDecl(), 0), |
3889 | Unit: getOrCreateFile(Loc: RD->getLocation())); |
3890 | } else if (RD->isDynamicClass()) |
3891 | ContainingType = RealDecl; |
3892 | |
3893 | DBuilder.replaceVTableHolder(T&: RealDecl, VTableHolder: ContainingType); |
3894 | } |
3895 | |
3896 | llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType, |
3897 | StringRef Name, uint64_t *Offset) { |
3898 | llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(Ty: FType, Unit); |
3899 | uint64_t FieldSize = CGM.getContext().getTypeSize(T: FType); |
3900 | auto FieldAlign = getTypeAlignIfRequired(Ty: FType, Ctx: CGM.getContext()); |
3901 | llvm::DIType *Ty = |
3902 | DBuilder.createMemberType(Scope: Unit, Name, File: Unit, LineNo: 0, SizeInBits: FieldSize, AlignInBits: FieldAlign, |
3903 | OffsetInBits: *Offset, Flags: llvm::DINode::FlagZero, Ty: FieldTy); |
3904 | *Offset += FieldSize; |
3905 | return Ty; |
3906 | } |
3907 | |
3908 | void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit, |
3909 | StringRef &Name, |
3910 | StringRef &LinkageName, |
3911 | llvm::DIScope *&FDContext, |
3912 | llvm::DINodeArray &TParamsArray, |
3913 | llvm::DINode::DIFlags &Flags) { |
3914 | const auto *FD = cast<FunctionDecl>(Val: GD.getCanonicalDecl().getDecl()); |
3915 | Name = getFunctionName(FD); |
3916 | // Use mangled name as linkage name for C/C++ functions. |
3917 | if (FD->getType()->getAs<FunctionProtoType>()) |
3918 | LinkageName = CGM.getMangledName(GD); |
3919 | if (FD->hasPrototype()) |
3920 | Flags |= llvm::DINode::FlagPrototyped; |
3921 | // No need to replicate the linkage name if it isn't different from the |
3922 | // subprogram name, no need to have it at all unless coverage is enabled or |
3923 | // debug is set to more than just line tables or extra debug info is needed. |
3924 | if (LinkageName == Name || |
3925 | (CGM.getCodeGenOpts().CoverageNotesFile.empty() && |
3926 | CGM.getCodeGenOpts().CoverageDataFile.empty() && |
3927 | !CGM.getCodeGenOpts().DebugInfoForProfiling && |
3928 | !CGM.getCodeGenOpts().PseudoProbeForProfiling && |
3929 | DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)) |
3930 | LinkageName = StringRef(); |
3931 | |
3932 | // Emit the function scope in line tables only mode (if CodeView) to |
3933 | // differentiate between function names. |
3934 | if (CGM.getCodeGenOpts().hasReducedDebugInfo() || |
3935 | (DebugKind == llvm::codegenoptions::DebugLineTablesOnly && |
3936 | CGM.getCodeGenOpts().EmitCodeView)) { |
3937 | if (const NamespaceDecl *NSDecl = |
3938 | dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext())) |
3939 | FDContext = getOrCreateNamespace(N: NSDecl); |
3940 | else if (const RecordDecl *RDecl = |
3941 | dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) { |
3942 | llvm::DIScope *Mod = getParentModuleOrNull(RDecl); |
3943 | FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU); |
3944 | } |
3945 | } |
3946 | if (CGM.getCodeGenOpts().hasReducedDebugInfo()) { |
3947 | // Check if it is a noreturn-marked function |
3948 | if (FD->isNoReturn()) |
3949 | Flags |= llvm::DINode::FlagNoReturn; |
3950 | // Collect template parameters. |
3951 | TParamsArray = CollectFunctionTemplateParams(FD, Unit); |
3952 | } |
3953 | } |
3954 | |
3955 | void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit, |
3956 | unsigned &LineNo, QualType &T, |
3957 | StringRef &Name, StringRef &LinkageName, |
3958 | llvm::MDTuple *&TemplateParameters, |
3959 | llvm::DIScope *&VDContext) { |
3960 | Unit = getOrCreateFile(Loc: VD->getLocation()); |
3961 | LineNo = getLineNumber(Loc: VD->getLocation()); |
3962 | |
3963 | setLocation(VD->getLocation()); |
3964 | |
3965 | T = VD->getType(); |
3966 | if (T->isIncompleteArrayType()) { |
3967 | // CodeGen turns int[] into int[1] so we'll do the same here. |
3968 | llvm::APInt ConstVal(32, 1); |
3969 | QualType ET = CGM.getContext().getAsArrayType(T)->getElementType(); |
3970 | |
3971 | T = CGM.getContext().getConstantArrayType(EltTy: ET, ArySize: ConstVal, SizeExpr: nullptr, |
3972 | ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
3973 | } |
3974 | |
3975 | Name = VD->getName(); |
3976 | if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) && |
3977 | !isa<ObjCMethodDecl>(VD->getDeclContext())) |
3978 | LinkageName = CGM.getMangledName(GD: VD); |
3979 | if (LinkageName == Name) |
3980 | LinkageName = StringRef(); |
3981 | |
3982 | if (isa<VarTemplateSpecializationDecl>(Val: VD)) { |
3983 | llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VL: VD, Unit: &*Unit); |
3984 | TemplateParameters = parameterNodes.get(); |
3985 | } else { |
3986 | TemplateParameters = nullptr; |
3987 | } |
3988 | |
3989 | // Since we emit declarations (DW_AT_members) for static members, place the |
3990 | // definition of those static members in the namespace they were declared in |
3991 | // in the source code (the lexical decl context). |
3992 | // FIXME: Generalize this for even non-member global variables where the |
3993 | // declaration and definition may have different lexical decl contexts, once |
3994 | // we have support for emitting declarations of (non-member) global variables. |
3995 | const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext() |
3996 | : VD->getDeclContext(); |
3997 | // When a record type contains an in-line initialization of a static data |
3998 | // member, and the record type is marked as __declspec(dllexport), an implicit |
3999 | // definition of the member will be created in the record context. DWARF |
4000 | // doesn't seem to have a nice way to describe this in a form that consumers |
4001 | // are likely to understand, so fake the "normal" situation of a definition |
4002 | // outside the class by putting it in the global scope. |
4003 | if (DC->isRecord()) |
4004 | DC = CGM.getContext().getTranslationUnitDecl(); |
4005 | |
4006 | llvm::DIScope *Mod = getParentModuleOrNull(VD); |
4007 | VDContext = getContextDescriptor(Context: cast<Decl>(Val: DC), Default: Mod ? Mod : TheCU); |
4008 | } |
4009 | |
4010 | llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD, |
4011 | bool Stub) { |
4012 | llvm::DINodeArray TParamsArray; |
4013 | StringRef Name, LinkageName; |
4014 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
4015 | llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; |
4016 | SourceLocation Loc = GD.getDecl()->getLocation(); |
4017 | llvm::DIFile *Unit = getOrCreateFile(Loc); |
4018 | llvm::DIScope *DContext = Unit; |
4019 | unsigned Line = getLineNumber(Loc); |
4020 | collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext&: DContext, TParamsArray, |
4021 | Flags); |
4022 | auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
4023 | |
4024 | // Build function type. |
4025 | SmallVector<QualType, 16> ArgTypes; |
4026 | for (const ParmVarDecl *Parm : FD->parameters()) |
4027 | ArgTypes.push_back(Elt: Parm->getType()); |
4028 | |
4029 | CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); |
4030 | QualType FnType = CGM.getContext().getFunctionType( |
4031 | ResultTy: FD->getReturnType(), Args: ArgTypes, EPI: FunctionProtoType::ExtProtoInfo(CC)); |
4032 | if (!FD->isExternallyVisible()) |
4033 | SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit; |
4034 | if (CGM.getLangOpts().Optimize) |
4035 | SPFlags |= llvm::DISubprogram::SPFlagOptimized; |
4036 | |
4037 | if (Stub) { |
4038 | Flags |= getCallSiteRelatedAttrs(); |
4039 | SPFlags |= llvm::DISubprogram::SPFlagDefinition; |
4040 | return DBuilder.createFunction( |
4041 | Scope: DContext, Name, LinkageName, File: Unit, LineNo: Line, |
4042 | Ty: getOrCreateFunctionType(D: GD.getDecl(), FnType, F: Unit), ScopeLine: 0, Flags, SPFlags, |
4043 | TParams: TParamsArray.get(), Decl: getFunctionDeclaration(FD)); |
4044 | } |
4045 | |
4046 | llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl( |
4047 | Scope: DContext, Name, LinkageName, File: Unit, LineNo: Line, |
4048 | Ty: getOrCreateFunctionType(D: GD.getDecl(), FnType, F: Unit), ScopeLine: 0, Flags, SPFlags, |
4049 | TParams: TParamsArray.get(), Decl: getFunctionDeclaration(FD)); |
4050 | const FunctionDecl *CanonDecl = FD->getCanonicalDecl(); |
4051 | FwdDeclReplaceMap.emplace_back(args: std::piecewise_construct, |
4052 | args: std::make_tuple(args&: CanonDecl), |
4053 | args: std::make_tuple(args&: SP)); |
4054 | return SP; |
4055 | } |
4056 | |
4057 | llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) { |
4058 | return getFunctionFwdDeclOrStub(GD, /* Stub = */ false); |
4059 | } |
4060 | |
4061 | llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) { |
4062 | return getFunctionFwdDeclOrStub(GD, /* Stub = */ true); |
4063 | } |
4064 | |
4065 | llvm::DIGlobalVariable * |
4066 | CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) { |
4067 | QualType T; |
4068 | StringRef Name, LinkageName; |
4069 | SourceLocation Loc = VD->getLocation(); |
4070 | llvm::DIFile *Unit = getOrCreateFile(Loc); |
4071 | llvm::DIScope *DContext = Unit; |
4072 | unsigned Line = getLineNumber(Loc); |
4073 | llvm::MDTuple *TemplateParameters = nullptr; |
4074 | |
4075 | collectVarDeclProps(VD, Unit, LineNo&: Line, T, Name, LinkageName, TemplateParameters, |
4076 | VDContext&: DContext); |
4077 | auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); |
4078 | auto *GV = DBuilder.createTempGlobalVariableFwdDecl( |
4079 | Context: DContext, Name, LinkageName, File: Unit, LineNo: Line, Ty: getOrCreateType(Ty: T, Unit), |
4080 | IsLocalToUnit: !VD->isExternallyVisible(), Decl: nullptr, TemplateParams: TemplateParameters, AlignInBits: Align); |
4081 | FwdDeclReplaceMap.emplace_back( |
4082 | args: std::piecewise_construct, |
4083 | args: std::make_tuple(args: cast<VarDecl>(Val: VD->getCanonicalDecl())), |
4084 | args: std::make_tuple(args: static_cast<llvm::Metadata *>(GV))); |
4085 | return GV; |
4086 | } |
4087 | |
4088 | llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) { |
4089 | // We only need a declaration (not a definition) of the type - so use whatever |
4090 | // we would otherwise do to get a type for a pointee. (forward declarations in |
4091 | // limited debug info, full definitions (if the type definition is available) |
4092 | // in unlimited debug info) |
4093 | if (const auto *TD = dyn_cast<TypeDecl>(Val: D)) |
4094 | return getOrCreateType(Ty: CGM.getContext().getTypeDeclType(Decl: TD), |
4095 | Unit: getOrCreateFile(Loc: TD->getLocation())); |
4096 | auto I = DeclCache.find(Val: D->getCanonicalDecl()); |
4097 | |
4098 | if (I != DeclCache.end()) { |
4099 | auto N = I->second; |
4100 | if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Val&: N)) |
4101 | return GVE->getVariable(); |
4102 | return cast<llvm::DINode>(Val&: N); |
4103 | } |
4104 | |
4105 | // Search imported declaration cache if it is already defined |
4106 | // as imported declaration. |
4107 | auto IE = ImportedDeclCache.find(Val: D->getCanonicalDecl()); |
4108 | |
4109 | if (IE != ImportedDeclCache.end()) { |
4110 | auto N = IE->second; |
4111 | if (auto *GVE = dyn_cast_or_null<llvm::DIImportedEntity>(Val&: N)) |
4112 | return cast<llvm::DINode>(Val: GVE); |
4113 | return dyn_cast_or_null<llvm::DINode>(Val&: N); |
4114 | } |
4115 | |
4116 | // No definition for now. Emit a forward definition that might be |
4117 | // merged with a potential upcoming definition. |
4118 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) |
4119 | return getFunctionForwardDeclaration(GD: FD); |
4120 | else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) |
4121 | return getGlobalVariableForwardDeclaration(VD); |
4122 | |
4123 | return nullptr; |
4124 | } |
4125 | |
4126 | llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) { |
4127 | if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly) |
4128 | return nullptr; |
4129 | |
4130 | const auto *FD = dyn_cast<FunctionDecl>(Val: D); |
4131 | if (!FD) |
4132 | return nullptr; |
4133 | |
4134 | // Setup context. |
4135 | auto *S = getDeclContextDescriptor(D); |
4136 | |
4137 | auto MI = SPCache.find(Val: FD->getCanonicalDecl()); |
4138 | if (MI == SPCache.end()) { |
4139 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD->getCanonicalDecl())) { |
4140 | return CreateCXXMemberFunction(Method: MD, Unit: getOrCreateFile(Loc: MD->getLocation()), |
4141 | RecordTy: cast<llvm::DICompositeType>(Val: S)); |
4142 | } |
4143 | } |
4144 | if (MI != SPCache.end()) { |
4145 | auto *SP = dyn_cast_or_null<llvm::DISubprogram>(Val&: MI->second); |
4146 | if (SP && !SP->isDefinition()) |
4147 | return SP; |
4148 | } |
4149 | |
4150 | for (auto *NextFD : FD->redecls()) { |
4151 | auto MI = SPCache.find(NextFD->getCanonicalDecl()); |
4152 | if (MI != SPCache.end()) { |
4153 | auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second); |
4154 | if (SP && !SP->isDefinition()) |
4155 | return SP; |
4156 | } |
4157 | } |
4158 | return nullptr; |
4159 | } |
4160 | |
4161 | llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration( |
4162 | const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo, |
4163 | llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) { |
4164 | if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly) |
4165 | return nullptr; |
4166 | |
4167 | const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D); |
4168 | if (!OMD) |
4169 | return nullptr; |
4170 | |
4171 | if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod()) |
4172 | return nullptr; |
4173 | |
4174 | if (OMD->isDirectMethod()) |
4175 | SPFlags |= llvm::DISubprogram::SPFlagObjCDirect; |
4176 | |
4177 | // Starting with DWARF V5 method declarations are emitted as children of |
4178 | // the interface type. |
4179 | auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(Val: D->getDeclContext()); |
4180 | if (!ID) |
4181 | ID = OMD->getClassInterface(); |
4182 | if (!ID) |
4183 | return nullptr; |
4184 | QualType QTy(ID->getTypeForDecl(), 0); |
4185 | auto It = TypeCache.find(Val: QTy.getAsOpaquePtr()); |
4186 | if (It == TypeCache.end()) |
4187 | return nullptr; |
4188 | auto *InterfaceType = cast<llvm::DICompositeType>(Val&: It->second); |
4189 | llvm::DISubprogram *FD = DBuilder.createFunction( |
4190 | Scope: InterfaceType, Name: getObjCMethodName(OMD), LinkageName: StringRef(), |
4191 | File: InterfaceType->getFile(), LineNo, Ty: FnType, ScopeLine: LineNo, Flags, SPFlags); |
4192 | DBuilder.finalizeSubprogram(SP: FD); |
4193 | ObjCMethodCache[ID].push_back(x: {FD, OMD->isDirectMethod()}); |
4194 | return FD; |
4195 | } |
4196 | |
4197 | // getOrCreateFunctionType - Construct type. If it is a c++ method, include |
4198 | // implicit parameter "this". |
4199 | llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D, |
4200 | QualType FnType, |
4201 | llvm::DIFile *F) { |
4202 | // In CodeView, we emit the function types in line tables only because the |
4203 | // only way to distinguish between functions is by display name and type. |
4204 | if (!D || (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly && |
4205 | !CGM.getCodeGenOpts().EmitCodeView)) |
4206 | // Create fake but valid subroutine type. Otherwise -verify would fail, and |
4207 | // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields. |
4208 | return DBuilder.createSubroutineType( |
4209 | ParameterTypes: DBuilder.getOrCreateTypeArray(Elements: std::nullopt)); |
4210 | |
4211 | if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: D)) |
4212 | return getOrCreateMethodType(Method, Unit: F); |
4213 | |
4214 | const auto *FTy = FnType->getAs<FunctionType>(); |
4215 | CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C; |
4216 | |
4217 | if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(Val: D)) { |
4218 | // Add "self" and "_cmd" |
4219 | SmallVector<llvm::Metadata *, 16> Elts; |
4220 | |
4221 | // First element is always return type. For 'void' functions it is NULL. |
4222 | QualType ResultTy = OMethod->getReturnType(); |
4223 | |
4224 | // Replace the instancetype keyword with the actual type. |
4225 | if (ResultTy == CGM.getContext().getObjCInstanceType()) |
4226 | ResultTy = CGM.getContext().getPointerType( |
4227 | T: QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)); |
4228 | |
4229 | Elts.push_back(Elt: getOrCreateType(Ty: ResultTy, Unit: F)); |
4230 | // "self" pointer is always first argument. |
4231 | QualType SelfDeclTy; |
4232 | if (auto *SelfDecl = OMethod->getSelfDecl()) |
4233 | SelfDeclTy = SelfDecl->getType(); |
4234 | else if (auto *FPT = dyn_cast<FunctionProtoType>(Val&: FnType)) |
4235 | if (FPT->getNumParams() > 1) |
4236 | SelfDeclTy = FPT->getParamType(i: 0); |
4237 | if (!SelfDeclTy.isNull()) |
4238 | Elts.push_back( |
4239 | Elt: CreateSelfType(QualTy: SelfDeclTy, Ty: getOrCreateType(Ty: SelfDeclTy, Unit: F))); |
4240 | // "_cmd" pointer is always second argument. |
4241 | Elts.push_back(Elt: DBuilder.createArtificialType( |
4242 | Ty: getOrCreateType(Ty: CGM.getContext().getObjCSelType(), Unit: F))); |
4243 | // Get rest of the arguments. |
4244 | for (const auto *PI : OMethod->parameters()) |
4245 | Elts.push_back(Elt: getOrCreateType(Ty: PI->getType(), Unit: F)); |
4246 | // Variadic methods need a special marker at the end of the type list. |
4247 | if (OMethod->isVariadic()) |
4248 | Elts.push_back(Elt: DBuilder.createUnspecifiedParameter()); |
4249 | |
4250 | llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elements: Elts); |
4251 | return DBuilder.createSubroutineType(ParameterTypes: EltTypeArray, Flags: llvm::DINode::FlagZero, |
4252 | CC: getDwarfCC(CC)); |
4253 | } |
4254 | |
4255 | // Handle variadic function types; they need an additional |
4256 | // unspecified parameter. |
4257 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) |
4258 | if (FD->isVariadic()) { |
4259 | SmallVector<llvm::Metadata *, 16> EltTys; |
4260 | EltTys.push_back(Elt: getOrCreateType(Ty: FD->getReturnType(), Unit: F)); |
4261 | if (const auto *FPT = dyn_cast<FunctionProtoType>(Val&: FnType)) |
4262 | for (QualType ParamType : FPT->param_types()) |
4263 | EltTys.push_back(Elt: getOrCreateType(Ty: ParamType, Unit: F)); |
4264 | EltTys.push_back(Elt: DBuilder.createUnspecifiedParameter()); |
4265 | llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elements: EltTys); |
4266 | return DBuilder.createSubroutineType(ParameterTypes: EltTypeArray, Flags: llvm::DINode::FlagZero, |
4267 | CC: getDwarfCC(CC)); |
4268 | } |
4269 | |
4270 | return cast<llvm::DISubroutineType>(Val: getOrCreateType(Ty: FnType, Unit: F)); |
4271 | } |
4272 | |
4273 | QualType |
4274 | CGDebugInfo::getFunctionType(const FunctionDecl *FD, QualType RetTy, |
4275 | const SmallVectorImpl<const VarDecl *> &Args) { |
4276 | CallingConv CC = CallingConv::CC_C; |
4277 | if (FD) |
4278 | if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>()) |
4279 | CC = SrcFnTy->getCallConv(); |
4280 | SmallVector<QualType, 16> ArgTypes; |
4281 | for (const VarDecl *VD : Args) |
4282 | ArgTypes.push_back(Elt: VD->getType()); |
4283 | return CGM.getContext().getFunctionType(ResultTy: RetTy, Args: ArgTypes, |
4284 | EPI: FunctionProtoType::ExtProtoInfo(CC)); |
4285 | } |
4286 | |
4287 | void CGDebugInfo::emitFunctionStart(GlobalDecl GD, SourceLocation Loc, |
4288 | SourceLocation ScopeLoc, QualType FnType, |
4289 | llvm::Function *Fn, bool CurFuncIsThunk) { |
4290 | StringRef Name; |
4291 | StringRef LinkageName; |
4292 | |
4293 | FnBeginRegionCount.push_back(x: LexicalBlockStack.size()); |
4294 | |
4295 | const Decl *D = GD.getDecl(); |
4296 | bool HasDecl = (D != nullptr); |
4297 | |
4298 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
4299 | llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; |
4300 | llvm::DIFile *Unit = getOrCreateFile(Loc); |
4301 | llvm::DIScope *FDContext = Unit; |
4302 | llvm::DINodeArray TParamsArray; |
4303 | if (!HasDecl) { |
4304 | // Use llvm function name. |
4305 | LinkageName = Fn->getName(); |
4306 | } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
4307 | // If there is a subprogram for this function available then use it. |
4308 | auto FI = SPCache.find(Val: FD->getCanonicalDecl()); |
4309 | if (FI != SPCache.end()) { |
4310 | auto *SP = dyn_cast_or_null<llvm::DISubprogram>(Val&: FI->second); |
4311 | if (SP && SP->isDefinition()) { |
4312 | LexicalBlockStack.emplace_back(args&: SP); |
4313 | RegionMap[D].reset(MD: SP); |
4314 | return; |
4315 | } |
4316 | } |
4317 | collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, |
4318 | TParamsArray, Flags); |
4319 | } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D)) { |
4320 | Name = getObjCMethodName(OMD); |
4321 | Flags |= llvm::DINode::FlagPrototyped; |
4322 | } else if (isa<VarDecl>(Val: D) && |
4323 | GD.getDynamicInitKind() != DynamicInitKind::NoStub) { |
4324 | // This is a global initializer or atexit destructor for a global variable. |
4325 | Name = getDynamicInitializerName(VD: cast<VarDecl>(Val: D), StubKind: GD.getDynamicInitKind(), |
4326 | InitFn: Fn); |
4327 | } else { |
4328 | Name = Fn->getName(); |
4329 | |
4330 | if (isa<BlockDecl>(Val: D)) |
4331 | LinkageName = Name; |
4332 | |
4333 | Flags |= llvm::DINode::FlagPrototyped; |
4334 | } |
4335 | if (Name.starts_with(Prefix: "\01" )) |
4336 | Name = Name.substr(Start: 1); |
4337 | |
4338 | assert((!D || !isa<VarDecl>(D) || |
4339 | GD.getDynamicInitKind() != DynamicInitKind::NoStub) && |
4340 | "Unexpected DynamicInitKind !" ); |
4341 | |
4342 | if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() || |
4343 | isa<VarDecl>(D) || isa<CapturedDecl>(D)) { |
4344 | Flags |= llvm::DINode::FlagArtificial; |
4345 | // Artificial functions should not silently reuse CurLoc. |
4346 | CurLoc = SourceLocation(); |
4347 | } |
4348 | |
4349 | if (CurFuncIsThunk) |
4350 | Flags |= llvm::DINode::FlagThunk; |
4351 | |
4352 | if (Fn->hasLocalLinkage()) |
4353 | SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit; |
4354 | if (CGM.getLangOpts().Optimize) |
4355 | SPFlags |= llvm::DISubprogram::SPFlagOptimized; |
4356 | |
4357 | llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs(); |
4358 | llvm::DISubprogram::DISPFlags SPFlagsForDef = |
4359 | SPFlags | llvm::DISubprogram::SPFlagDefinition; |
4360 | |
4361 | const unsigned LineNo = getLineNumber(Loc: Loc.isValid() ? Loc : CurLoc); |
4362 | unsigned ScopeLine = getLineNumber(Loc: ScopeLoc); |
4363 | llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, F: Unit); |
4364 | llvm::DISubprogram *Decl = nullptr; |
4365 | llvm::DINodeArray Annotations = nullptr; |
4366 | if (D) { |
4367 | Decl = isa<ObjCMethodDecl>(Val: D) |
4368 | ? getObjCMethodDeclaration(D, FnType: DIFnType, LineNo, Flags, SPFlags) |
4369 | : getFunctionDeclaration(D); |
4370 | Annotations = CollectBTFDeclTagAnnotations(D); |
4371 | } |
4372 | |
4373 | // FIXME: The function declaration we're constructing here is mostly reusing |
4374 | // declarations from CXXMethodDecl and not constructing new ones for arbitrary |
4375 | // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for |
4376 | // all subprograms instead of the actual context since subprogram definitions |
4377 | // are emitted as CU level entities by the backend. |
4378 | llvm::DISubprogram *SP = DBuilder.createFunction( |
4379 | Scope: FDContext, Name, LinkageName, File: Unit, LineNo, Ty: DIFnType, ScopeLine, |
4380 | Flags: FlagsForDef, SPFlags: SPFlagsForDef, TParams: TParamsArray.get(), Decl, ThrownTypes: nullptr, |
4381 | Annotations); |
4382 | Fn->setSubprogram(SP); |
4383 | // We might get here with a VarDecl in the case we're generating |
4384 | // code for the initialization of globals. Do not record these decls |
4385 | // as they will overwrite the actual VarDecl Decl in the cache. |
4386 | if (HasDecl && isa<FunctionDecl>(Val: D)) |
4387 | DeclCache[D->getCanonicalDecl()].reset(MD: SP); |
4388 | |
4389 | // Push the function onto the lexical block stack. |
4390 | LexicalBlockStack.emplace_back(args&: SP); |
4391 | |
4392 | if (HasDecl) |
4393 | RegionMap[D].reset(MD: SP); |
4394 | } |
4395 | |
4396 | void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, |
4397 | QualType FnType, llvm::Function *Fn) { |
4398 | StringRef Name; |
4399 | StringRef LinkageName; |
4400 | |
4401 | const Decl *D = GD.getDecl(); |
4402 | if (!D) |
4403 | return; |
4404 | |
4405 | llvm::TimeTraceScope TimeScope("DebugFunction" , [&]() { |
4406 | return GetName(D, Qualified: true); |
4407 | }); |
4408 | |
4409 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
4410 | llvm::DIFile *Unit = getOrCreateFile(Loc); |
4411 | bool IsDeclForCallSite = Fn ? true : false; |
4412 | llvm::DIScope *FDContext = |
4413 | IsDeclForCallSite ? Unit : getDeclContextDescriptor(D); |
4414 | llvm::DINodeArray TParamsArray; |
4415 | if (isa<FunctionDecl>(Val: D)) { |
4416 | // If there is a DISubprogram for this function available then use it. |
4417 | collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext, |
4418 | TParamsArray, Flags); |
4419 | } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D)) { |
4420 | Name = getObjCMethodName(OMD); |
4421 | Flags |= llvm::DINode::FlagPrototyped; |
4422 | } else { |
4423 | llvm_unreachable("not a function or ObjC method" ); |
4424 | } |
4425 | if (!Name.empty() && Name[0] == '\01') |
4426 | Name = Name.substr(Start: 1); |
4427 | |
4428 | if (D->isImplicit()) { |
4429 | Flags |= llvm::DINode::FlagArtificial; |
4430 | // Artificial functions without a location should not silently reuse CurLoc. |
4431 | if (Loc.isInvalid()) |
4432 | CurLoc = SourceLocation(); |
4433 | } |
4434 | unsigned LineNo = getLineNumber(Loc); |
4435 | unsigned ScopeLine = 0; |
4436 | llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero; |
4437 | if (CGM.getLangOpts().Optimize) |
4438 | SPFlags |= llvm::DISubprogram::SPFlagOptimized; |
4439 | |
4440 | llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D); |
4441 | llvm::DISubroutineType *STy = getOrCreateFunctionType(D, FnType, F: Unit); |
4442 | llvm::DISubprogram *SP = DBuilder.createFunction( |
4443 | Scope: FDContext, Name, LinkageName, File: Unit, LineNo, Ty: STy, ScopeLine, Flags, |
4444 | SPFlags, TParams: TParamsArray.get(), Decl: nullptr, ThrownTypes: nullptr, Annotations); |
4445 | |
4446 | // Preserve btf_decl_tag attributes for parameters of extern functions |
4447 | // for BPF target. The parameters created in this loop are attached as |
4448 | // DISubprogram's retainedNodes in the subsequent finalizeSubprogram call. |
4449 | if (IsDeclForCallSite && CGM.getTarget().getTriple().isBPF()) { |
4450 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
4451 | llvm::DITypeRefArray ParamTypes = STy->getTypeArray(); |
4452 | unsigned ArgNo = 1; |
4453 | for (ParmVarDecl *PD : FD->parameters()) { |
4454 | llvm::DINodeArray ParamAnnotations = CollectBTFDeclTagAnnotations(PD); |
4455 | DBuilder.createParameterVariable( |
4456 | Scope: SP, Name: PD->getName(), ArgNo, File: Unit, LineNo, Ty: ParamTypes[ArgNo], AlwaysPreserve: true, |
4457 | Flags: llvm::DINode::FlagZero, Annotations: ParamAnnotations); |
4458 | ++ArgNo; |
4459 | } |
4460 | } |
4461 | } |
4462 | |
4463 | if (IsDeclForCallSite) |
4464 | Fn->setSubprogram(SP); |
4465 | |
4466 | DBuilder.finalizeSubprogram(SP); |
4467 | } |
4468 | |
4469 | void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke, |
4470 | QualType CalleeType, |
4471 | const FunctionDecl *CalleeDecl) { |
4472 | if (!CallOrInvoke) |
4473 | return; |
4474 | auto *Func = CallOrInvoke->getCalledFunction(); |
4475 | if (!Func) |
4476 | return; |
4477 | if (Func->getSubprogram()) |
4478 | return; |
4479 | |
4480 | // Do not emit a declaration subprogram for a function with nodebug |
4481 | // attribute, or if call site info isn't required. |
4482 | if (CalleeDecl->hasAttr<NoDebugAttr>() || |
4483 | getCallSiteRelatedAttrs() == llvm::DINode::FlagZero) |
4484 | return; |
4485 | |
4486 | // If there is no DISubprogram attached to the function being called, |
4487 | // create the one describing the function in order to have complete |
4488 | // call site debug info. |
4489 | if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined()) |
4490 | EmitFunctionDecl(GD: CalleeDecl, Loc: CalleeDecl->getLocation(), FnType: CalleeType, Fn: Func); |
4491 | } |
4492 | |
4493 | void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) { |
4494 | const auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
4495 | // If there is a subprogram for this function available then use it. |
4496 | auto FI = SPCache.find(Val: FD->getCanonicalDecl()); |
4497 | llvm::DISubprogram *SP = nullptr; |
4498 | if (FI != SPCache.end()) |
4499 | SP = dyn_cast_or_null<llvm::DISubprogram>(Val&: FI->second); |
4500 | if (!SP || !SP->isDefinition()) |
4501 | SP = getFunctionStub(GD); |
4502 | FnBeginRegionCount.push_back(x: LexicalBlockStack.size()); |
4503 | LexicalBlockStack.emplace_back(args&: SP); |
4504 | setInlinedAt(Builder.getCurrentDebugLocation()); |
4505 | EmitLocation(Builder, Loc: FD->getLocation()); |
4506 | } |
4507 | |
4508 | void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) { |
4509 | assert(CurInlinedAt && "unbalanced inline scope stack" ); |
4510 | EmitFunctionEnd(Builder, Fn: nullptr); |
4511 | setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt()); |
4512 | } |
4513 | |
4514 | void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) { |
4515 | // Update our current location |
4516 | setLocation(Loc); |
4517 | |
4518 | if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty()) |
4519 | return; |
4520 | |
4521 | llvm::MDNode *Scope = LexicalBlockStack.back(); |
4522 | Builder.SetCurrentDebugLocation( |
4523 | llvm::DILocation::get(Context&: CGM.getLLVMContext(), Line: getLineNumber(Loc: CurLoc), |
4524 | Column: getColumnNumber(Loc: CurLoc), Scope, InlinedAt: CurInlinedAt)); |
4525 | } |
4526 | |
4527 | void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) { |
4528 | llvm::MDNode *Back = nullptr; |
4529 | if (!LexicalBlockStack.empty()) |
4530 | Back = LexicalBlockStack.back().get(); |
4531 | LexicalBlockStack.emplace_back(args: DBuilder.createLexicalBlock( |
4532 | Scope: cast<llvm::DIScope>(Val: Back), File: getOrCreateFile(Loc: CurLoc), Line: getLineNumber(Loc: CurLoc), |
4533 | Col: getColumnNumber(Loc: CurLoc))); |
4534 | } |
4535 | |
4536 | void CGDebugInfo::AppendAddressSpaceXDeref( |
4537 | unsigned AddressSpace, SmallVectorImpl<uint64_t> &Expr) const { |
4538 | std::optional<unsigned> DWARFAddressSpace = |
4539 | CGM.getTarget().getDWARFAddressSpace(AddressSpace); |
4540 | if (!DWARFAddressSpace) |
4541 | return; |
4542 | |
4543 | Expr.push_back(Elt: llvm::dwarf::DW_OP_constu); |
4544 | Expr.push_back(Elt: *DWARFAddressSpace); |
4545 | Expr.push_back(Elt: llvm::dwarf::DW_OP_swap); |
4546 | Expr.push_back(Elt: llvm::dwarf::DW_OP_xderef); |
4547 | } |
4548 | |
4549 | void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, |
4550 | SourceLocation Loc) { |
4551 | // Set our current location. |
4552 | setLocation(Loc); |
4553 | |
4554 | // Emit a line table change for the current location inside the new scope. |
4555 | Builder.SetCurrentDebugLocation(llvm::DILocation::get( |
4556 | Context&: CGM.getLLVMContext(), Line: getLineNumber(Loc), Column: getColumnNumber(Loc), |
4557 | Scope: LexicalBlockStack.back(), InlinedAt: CurInlinedAt)); |
4558 | |
4559 | if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly) |
4560 | return; |
4561 | |
4562 | // Create a new lexical block and push it on the stack. |
4563 | CreateLexicalBlock(Loc); |
4564 | } |
4565 | |
4566 | void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, |
4567 | SourceLocation Loc) { |
4568 | assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!" ); |
4569 | |
4570 | // Provide an entry in the line table for the end of the block. |
4571 | EmitLocation(Builder, Loc); |
4572 | |
4573 | if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly) |
4574 | return; |
4575 | |
4576 | LexicalBlockStack.pop_back(); |
4577 | } |
4578 | |
4579 | void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) { |
4580 | assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!" ); |
4581 | unsigned RCount = FnBeginRegionCount.back(); |
4582 | assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch" ); |
4583 | |
4584 | // Pop all regions for this function. |
4585 | while (LexicalBlockStack.size() != RCount) { |
4586 | // Provide an entry in the line table for the end of the block. |
4587 | EmitLocation(Builder, Loc: CurLoc); |
4588 | LexicalBlockStack.pop_back(); |
4589 | } |
4590 | FnBeginRegionCount.pop_back(); |
4591 | |
4592 | if (Fn && Fn->getSubprogram()) |
4593 | DBuilder.finalizeSubprogram(SP: Fn->getSubprogram()); |
4594 | } |
4595 | |
4596 | CGDebugInfo::BlockByRefType |
4597 | CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD, |
4598 | uint64_t *XOffset) { |
4599 | SmallVector<llvm::Metadata *, 5> EltTys; |
4600 | QualType FType; |
4601 | uint64_t FieldSize, FieldOffset; |
4602 | uint32_t FieldAlign; |
4603 | |
4604 | llvm::DIFile *Unit = getOrCreateFile(Loc: VD->getLocation()); |
4605 | QualType Type = VD->getType(); |
4606 | |
4607 | FieldOffset = 0; |
4608 | FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); |
4609 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__isa" , Offset: &FieldOffset)); |
4610 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__forwarding" , Offset: &FieldOffset)); |
4611 | FType = CGM.getContext().IntTy; |
4612 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__flags" , Offset: &FieldOffset)); |
4613 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "__size" , Offset: &FieldOffset)); |
4614 | |
4615 | bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Ty: Type, D: VD); |
4616 | if (HasCopyAndDispose) { |
4617 | FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); |
4618 | EltTys.push_back( |
4619 | Elt: CreateMemberType(Unit, FType, Name: "__copy_helper" , Offset: &FieldOffset)); |
4620 | EltTys.push_back( |
4621 | Elt: CreateMemberType(Unit, FType, Name: "__destroy_helper" , Offset: &FieldOffset)); |
4622 | } |
4623 | bool HasByrefExtendedLayout; |
4624 | Qualifiers::ObjCLifetime Lifetime; |
4625 | if (CGM.getContext().getByrefLifetime(Ty: Type, Lifetime, |
4626 | HasByrefExtendedLayout) && |
4627 | HasByrefExtendedLayout) { |
4628 | FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy); |
4629 | EltTys.push_back( |
4630 | Elt: CreateMemberType(Unit, FType, Name: "__byref_variable_layout" , Offset: &FieldOffset)); |
4631 | } |
4632 | |
4633 | CharUnits Align = CGM.getContext().getDeclAlign(VD); |
4634 | if (Align > CGM.getContext().toCharUnitsFromBits( |
4635 | BitSize: CGM.getTarget().getPointerAlign(AddrSpace: LangAS::Default))) { |
4636 | CharUnits FieldOffsetInBytes = |
4637 | CGM.getContext().toCharUnitsFromBits(BitSize: FieldOffset); |
4638 | CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align); |
4639 | CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes; |
4640 | |
4641 | if (NumPaddingBytes.isPositive()) { |
4642 | llvm::APInt pad(32, NumPaddingBytes.getQuantity()); |
4643 | FType = CGM.getContext().getConstantArrayType( |
4644 | EltTy: CGM.getContext().CharTy, ArySize: pad, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
4645 | EltTys.push_back(Elt: CreateMemberType(Unit, FType, Name: "" , Offset: &FieldOffset)); |
4646 | } |
4647 | } |
4648 | |
4649 | FType = Type; |
4650 | llvm::DIType *WrappedTy = getOrCreateType(Ty: FType, Unit); |
4651 | FieldSize = CGM.getContext().getTypeSize(T: FType); |
4652 | FieldAlign = CGM.getContext().toBits(CharSize: Align); |
4653 | |
4654 | *XOffset = FieldOffset; |
4655 | llvm::DIType *FieldTy = DBuilder.createMemberType( |
4656 | Scope: Unit, Name: VD->getName(), File: Unit, LineNo: 0, SizeInBits: FieldSize, AlignInBits: FieldAlign, OffsetInBits: FieldOffset, |
4657 | Flags: llvm::DINode::FlagZero, Ty: WrappedTy); |
4658 | EltTys.push_back(Elt: FieldTy); |
4659 | FieldOffset += FieldSize; |
4660 | |
4661 | llvm::DINodeArray Elements = DBuilder.getOrCreateArray(Elements: EltTys); |
4662 | return {.BlockByRefWrapper: DBuilder.createStructType(Scope: Unit, Name: "" , File: Unit, LineNumber: 0, SizeInBits: FieldOffset, AlignInBits: 0, |
4663 | Flags: llvm::DINode::FlagZero, DerivedFrom: nullptr, Elements), |
4664 | .WrappedType: WrappedTy}; |
4665 | } |
4666 | |
4667 | llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD, |
4668 | llvm::Value *Storage, |
4669 | std::optional<unsigned> ArgNo, |
4670 | CGBuilderTy &Builder, |
4671 | const bool UsePointerValue) { |
4672 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
4673 | assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!" ); |
4674 | if (VD->hasAttr<NoDebugAttr>()) |
4675 | return nullptr; |
4676 | |
4677 | bool Unwritten = |
4678 | VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) && |
4679 | cast<Decl>(VD->getDeclContext())->isImplicit()); |
4680 | llvm::DIFile *Unit = nullptr; |
4681 | if (!Unwritten) |
4682 | Unit = getOrCreateFile(Loc: VD->getLocation()); |
4683 | llvm::DIType *Ty; |
4684 | uint64_t XOffset = 0; |
4685 | if (VD->hasAttr<BlocksAttr>()) |
4686 | Ty = EmitTypeForVarWithBlocksAttr(VD, XOffset: &XOffset).WrappedType; |
4687 | else |
4688 | Ty = getOrCreateType(Ty: VD->getType(), Unit); |
4689 | |
4690 | // If there is no debug info for this type then do not emit debug info |
4691 | // for this variable. |
4692 | if (!Ty) |
4693 | return nullptr; |
4694 | |
4695 | // Get location information. |
4696 | unsigned Line = 0; |
4697 | unsigned Column = 0; |
4698 | if (!Unwritten) { |
4699 | Line = getLineNumber(Loc: VD->getLocation()); |
4700 | Column = getColumnNumber(Loc: VD->getLocation()); |
4701 | } |
4702 | SmallVector<uint64_t, 13> Expr; |
4703 | llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero; |
4704 | if (VD->isImplicit()) |
4705 | Flags |= llvm::DINode::FlagArtificial; |
4706 | |
4707 | auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); |
4708 | |
4709 | unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(T: VD->getType()); |
4710 | AppendAddressSpaceXDeref(AddressSpace, Expr); |
4711 | |
4712 | // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an |
4713 | // object pointer flag. |
4714 | if (const auto *IPD = dyn_cast<ImplicitParamDecl>(Val: VD)) { |
4715 | if (IPD->getParameterKind() == ImplicitParamKind::CXXThis || |
4716 | IPD->getParameterKind() == ImplicitParamKind::ObjCSelf) |
4717 | Flags |= llvm::DINode::FlagObjectPointer; |
4718 | } |
4719 | |
4720 | // Note: Older versions of clang used to emit byval references with an extra |
4721 | // DW_OP_deref, because they referenced the IR arg directly instead of |
4722 | // referencing an alloca. Newer versions of LLVM don't treat allocas |
4723 | // differently from other function arguments when used in a dbg.declare. |
4724 | auto *Scope = cast<llvm::DIScope>(Val&: LexicalBlockStack.back()); |
4725 | StringRef Name = VD->getName(); |
4726 | if (!Name.empty()) { |
4727 | // __block vars are stored on the heap if they are captured by a block that |
4728 | // can escape the local scope. |
4729 | if (VD->isEscapingByref()) { |
4730 | // Here, we need an offset *into* the alloca. |
4731 | CharUnits offset = CharUnits::fromQuantity(Quantity: 32); |
4732 | Expr.push_back(Elt: llvm::dwarf::DW_OP_plus_uconst); |
4733 | // offset of __forwarding field |
4734 | offset = CGM.getContext().toCharUnitsFromBits( |
4735 | BitSize: CGM.getTarget().getPointerWidth(AddrSpace: LangAS::Default)); |
4736 | Expr.push_back(Elt: offset.getQuantity()); |
4737 | Expr.push_back(Elt: llvm::dwarf::DW_OP_deref); |
4738 | Expr.push_back(Elt: llvm::dwarf::DW_OP_plus_uconst); |
4739 | // offset of x field |
4740 | offset = CGM.getContext().toCharUnitsFromBits(BitSize: XOffset); |
4741 | Expr.push_back(Elt: offset.getQuantity()); |
4742 | } |
4743 | } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) { |
4744 | // If VD is an anonymous union then Storage represents value for |
4745 | // all union fields. |
4746 | const RecordDecl *RD = RT->getDecl(); |
4747 | if (RD->isUnion() && RD->isAnonymousStructOrUnion()) { |
4748 | // GDB has trouble finding local variables in anonymous unions, so we emit |
4749 | // artificial local variables for each of the members. |
4750 | // |
4751 | // FIXME: Remove this code as soon as GDB supports this. |
4752 | // The debug info verifier in LLVM operates based on the assumption that a |
4753 | // variable has the same size as its storage and we had to disable the |
4754 | // check for artificial variables. |
4755 | for (const auto *Field : RD->fields()) { |
4756 | llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit); |
4757 | StringRef FieldName = Field->getName(); |
4758 | |
4759 | // Ignore unnamed fields. Do not ignore unnamed records. |
4760 | if (FieldName.empty() && !isa<RecordType>(Field->getType())) |
4761 | continue; |
4762 | |
4763 | // Use VarDecl's Tag, Scope and Line number. |
4764 | auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext()); |
4765 | auto *D = DBuilder.createAutoVariable( |
4766 | Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize, |
4767 | Flags | llvm::DINode::FlagArtificial, FieldAlign); |
4768 | |
4769 | // Insert an llvm.dbg.declare into the current block. |
4770 | DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr), |
4771 | llvm::DILocation::get(CGM.getLLVMContext(), Line, |
4772 | Column, Scope, |
4773 | CurInlinedAt), |
4774 | Builder.GetInsertBlock()); |
4775 | } |
4776 | } |
4777 | } |
4778 | |
4779 | // Clang stores the sret pointer provided by the caller in a static alloca. |
4780 | // Use DW_OP_deref to tell the debugger to load the pointer and treat it as |
4781 | // the address of the variable. |
4782 | if (UsePointerValue) { |
4783 | assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) && |
4784 | "Debug info already contains DW_OP_deref." ); |
4785 | Expr.push_back(Elt: llvm::dwarf::DW_OP_deref); |
4786 | } |
4787 | |
4788 | // Create the descriptor for the variable. |
4789 | llvm::DILocalVariable *D = nullptr; |
4790 | if (ArgNo) { |
4791 | llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD); |
4792 | D = DBuilder.createParameterVariable(Scope, Name, ArgNo: *ArgNo, File: Unit, LineNo: Line, Ty, |
4793 | AlwaysPreserve: CGM.getLangOpts().Optimize, Flags, |
4794 | Annotations); |
4795 | } else { |
4796 | // For normal local variable, we will try to find out whether 'VD' is the |
4797 | // copy parameter of coroutine. |
4798 | // If yes, we are going to use DIVariable of the origin parameter instead |
4799 | // of creating the new one. |
4800 | // If no, it might be a normal alloc, we just create a new one for it. |
4801 | |
4802 | // Check whether the VD is move parameters. |
4803 | auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * { |
4804 | // The scope of parameter and move-parameter should be distinct |
4805 | // DISubprogram. |
4806 | if (!isa<llvm::DISubprogram>(Val: Scope) || !Scope->isDistinct()) |
4807 | return nullptr; |
4808 | |
4809 | auto Iter = llvm::find_if(Range&: CoroutineParameterMappings, P: [&](auto &Pair) { |
4810 | Stmt *StmtPtr = const_cast<Stmt *>(Pair.second); |
4811 | if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(Val: StmtPtr)) { |
4812 | DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup(); |
4813 | Decl *Decl = DeclGroup.getSingleDecl(); |
4814 | if (VD == dyn_cast_or_null<VarDecl>(Val: Decl)) |
4815 | return true; |
4816 | } |
4817 | return false; |
4818 | }); |
4819 | |
4820 | if (Iter != CoroutineParameterMappings.end()) { |
4821 | ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first); |
4822 | auto Iter2 = llvm::find_if(Range&: ParamDbgMappings, P: [&](auto &DbgPair) { |
4823 | return DbgPair.first == PD && DbgPair.second->getScope() == Scope; |
4824 | }); |
4825 | if (Iter2 != ParamDbgMappings.end()) |
4826 | return const_cast<llvm::DILocalVariable *>(Iter2->second); |
4827 | } |
4828 | return nullptr; |
4829 | }; |
4830 | |
4831 | // If we couldn't find a move param DIVariable, create a new one. |
4832 | D = RemapCoroArgToLocalVar(); |
4833 | // Or we will create a new DIVariable for this Decl if D dose not exists. |
4834 | if (!D) |
4835 | D = DBuilder.createAutoVariable(Scope, Name, File: Unit, LineNo: Line, Ty, |
4836 | AlwaysPreserve: CGM.getLangOpts().Optimize, Flags, AlignInBits: Align); |
4837 | } |
4838 | // Insert an llvm.dbg.declare into the current block. |
4839 | DBuilder.insertDeclare(Storage, VarInfo: D, Expr: DBuilder.createExpression(Addr: Expr), |
4840 | DL: llvm::DILocation::get(Context&: CGM.getLLVMContext(), Line, |
4841 | Column, Scope, InlinedAt: CurInlinedAt), |
4842 | InsertAtEnd: Builder.GetInsertBlock()); |
4843 | |
4844 | return D; |
4845 | } |
4846 | |
4847 | llvm::DIType *CGDebugInfo::CreateBindingDeclType(const BindingDecl *BD) { |
4848 | llvm::DIFile *Unit = getOrCreateFile(Loc: BD->getLocation()); |
4849 | |
4850 | // If the declaration is bound to a bitfield struct field, its type may have a |
4851 | // size that is different from its deduced declaration type's. |
4852 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: BD->getBinding())) { |
4853 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl())) { |
4854 | if (FD->isBitField()) { |
4855 | ASTContext &Context = CGM.getContext(); |
4856 | const CGRecordLayout &RL = |
4857 | CGM.getTypes().getCGRecordLayout(FD->getParent()); |
4858 | const CGBitFieldInfo &Info = RL.getBitFieldInfo(FD); |
4859 | |
4860 | // Find an integer type with the same bitwidth as the bitfield size. If |
4861 | // no suitable type is present in the target, give up on producing debug |
4862 | // information as it would be wrong. It is certainly possible to produce |
4863 | // correct debug info, but the logic isn't currently implemented. |
4864 | uint64_t BitfieldSizeInBits = Info.Size; |
4865 | QualType IntTy = |
4866 | Context.getIntTypeForBitwidth(DestWidth: BitfieldSizeInBits, Signed: Info.IsSigned); |
4867 | if (IntTy.isNull()) |
4868 | return nullptr; |
4869 | Qualifiers Quals = BD->getType().getQualifiers(); |
4870 | QualType FinalTy = Context.getQualifiedType(T: IntTy, Qs: Quals); |
4871 | llvm::DIType *Ty = getOrCreateType(Ty: FinalTy, Unit); |
4872 | assert(Ty); |
4873 | return Ty; |
4874 | } |
4875 | } |
4876 | } |
4877 | |
4878 | return getOrCreateType(Ty: BD->getType(), Unit); |
4879 | } |
4880 | |
4881 | llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD, |
4882 | llvm::Value *Storage, |
4883 | std::optional<unsigned> ArgNo, |
4884 | CGBuilderTy &Builder, |
4885 | const bool UsePointerValue) { |
4886 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
4887 | assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!" ); |
4888 | if (BD->hasAttr<NoDebugAttr>()) |
4889 | return nullptr; |
4890 | |
4891 | // Skip the tuple like case, we don't handle that here |
4892 | if (isa<DeclRefExpr>(Val: BD->getBinding())) |
4893 | return nullptr; |
4894 | |
4895 | llvm::DIType *Ty = CreateBindingDeclType(BD); |
4896 | |
4897 | // If there is no debug info for this type then do not emit debug info |
4898 | // for this variable. |
4899 | if (!Ty) |
4900 | return nullptr; |
4901 | |
4902 | auto Align = getDeclAlignIfRequired(BD, CGM.getContext()); |
4903 | unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(T: BD->getType()); |
4904 | |
4905 | SmallVector<uint64_t, 3> Expr; |
4906 | AppendAddressSpaceXDeref(AddressSpace, Expr); |
4907 | |
4908 | // Clang stores the sret pointer provided by the caller in a static alloca. |
4909 | // Use DW_OP_deref to tell the debugger to load the pointer and treat it as |
4910 | // the address of the variable. |
4911 | if (UsePointerValue) { |
4912 | assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) && |
4913 | "Debug info already contains DW_OP_deref." ); |
4914 | Expr.push_back(Elt: llvm::dwarf::DW_OP_deref); |
4915 | } |
4916 | |
4917 | unsigned Line = getLineNumber(Loc: BD->getLocation()); |
4918 | unsigned Column = getColumnNumber(Loc: BD->getLocation()); |
4919 | StringRef Name = BD->getName(); |
4920 | auto *Scope = cast<llvm::DIScope>(Val&: LexicalBlockStack.back()); |
4921 | llvm::DIFile *Unit = getOrCreateFile(Loc: BD->getLocation()); |
4922 | // Create the descriptor for the variable. |
4923 | llvm::DILocalVariable *D = DBuilder.createAutoVariable( |
4924 | Scope, Name, File: Unit, LineNo: Line, Ty, AlwaysPreserve: CGM.getLangOpts().Optimize, |
4925 | Flags: llvm::DINode::FlagZero, AlignInBits: Align); |
4926 | |
4927 | if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: BD->getBinding())) { |
4928 | if (const FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl())) { |
4929 | const unsigned fieldIndex = FD->getFieldIndex(); |
4930 | const clang::CXXRecordDecl *parent = |
4931 | (const CXXRecordDecl *)FD->getParent(); |
4932 | const ASTRecordLayout &layout = |
4933 | CGM.getContext().getASTRecordLayout(parent); |
4934 | const uint64_t fieldOffset = layout.getFieldOffset(FieldNo: fieldIndex); |
4935 | |
4936 | if (fieldOffset != 0) { |
4937 | // Currently if the field offset is not a multiple of byte, the produced |
4938 | // location would not be accurate. Therefore give up. |
4939 | if (fieldOffset % CGM.getContext().getCharWidth() != 0) |
4940 | return nullptr; |
4941 | |
4942 | Expr.push_back(Elt: llvm::dwarf::DW_OP_plus_uconst); |
4943 | Expr.push_back( |
4944 | Elt: CGM.getContext().toCharUnitsFromBits(BitSize: fieldOffset).getQuantity()); |
4945 | } |
4946 | } |
4947 | } else if (const ArraySubscriptExpr *ASE = |
4948 | dyn_cast<ArraySubscriptExpr>(Val: BD->getBinding())) { |
4949 | if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: ASE->getIdx())) { |
4950 | const uint64_t value = IL->getValue().getZExtValue(); |
4951 | const uint64_t typeSize = CGM.getContext().getTypeSize(BD->getType()); |
4952 | |
4953 | if (value != 0) { |
4954 | Expr.push_back(Elt: llvm::dwarf::DW_OP_plus_uconst); |
4955 | Expr.push_back(Elt: CGM.getContext() |
4956 | .toCharUnitsFromBits(BitSize: value * typeSize) |
4957 | .getQuantity()); |
4958 | } |
4959 | } |
4960 | } |
4961 | |
4962 | // Insert an llvm.dbg.declare into the current block. |
4963 | DBuilder.insertDeclare(Storage, VarInfo: D, Expr: DBuilder.createExpression(Addr: Expr), |
4964 | DL: llvm::DILocation::get(Context&: CGM.getLLVMContext(), Line, |
4965 | Column, Scope, InlinedAt: CurInlinedAt), |
4966 | InsertAtEnd: Builder.GetInsertBlock()); |
4967 | |
4968 | return D; |
4969 | } |
4970 | |
4971 | llvm::DILocalVariable * |
4972 | CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage, |
4973 | CGBuilderTy &Builder, |
4974 | const bool UsePointerValue) { |
4975 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
4976 | |
4977 | if (auto *DD = dyn_cast<DecompositionDecl>(Val: VD)) { |
4978 | for (auto *B : DD->bindings()) { |
4979 | EmitDeclare(B, Storage, std::nullopt, Builder, |
4980 | VD->getType()->isReferenceType()); |
4981 | } |
4982 | // Don't emit an llvm.dbg.declare for the composite storage as it doesn't |
4983 | // correspond to a user variable. |
4984 | return nullptr; |
4985 | } |
4986 | |
4987 | return EmitDeclare(VD, Storage, ArgNo: std::nullopt, Builder, UsePointerValue); |
4988 | } |
4989 | |
4990 | void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) { |
4991 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
4992 | assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!" ); |
4993 | |
4994 | if (D->hasAttr<NoDebugAttr>()) |
4995 | return; |
4996 | |
4997 | auto *Scope = cast<llvm::DIScope>(Val&: LexicalBlockStack.back()); |
4998 | llvm::DIFile *Unit = getOrCreateFile(Loc: D->getLocation()); |
4999 | |
5000 | // Get location information. |
5001 | unsigned Line = getLineNumber(Loc: D->getLocation()); |
5002 | unsigned Column = getColumnNumber(Loc: D->getLocation()); |
5003 | |
5004 | StringRef Name = D->getName(); |
5005 | |
5006 | // Create the descriptor for the label. |
5007 | auto *L = |
5008 | DBuilder.createLabel(Scope, Name, File: Unit, LineNo: Line, AlwaysPreserve: CGM.getLangOpts().Optimize); |
5009 | |
5010 | // Insert an llvm.dbg.label into the current block. |
5011 | DBuilder.insertLabel(L, |
5012 | llvm::DILocation::get(Context&: CGM.getLLVMContext(), Line, Column, |
5013 | Scope, InlinedAt: CurInlinedAt), |
5014 | Builder.GetInsertBlock()); |
5015 | } |
5016 | |
5017 | llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy, |
5018 | llvm::DIType *Ty) { |
5019 | llvm::DIType *CachedTy = getTypeOrNull(Ty: QualTy); |
5020 | if (CachedTy) |
5021 | Ty = CachedTy; |
5022 | return DBuilder.createObjectPointerType(Ty); |
5023 | } |
5024 | |
5025 | void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable( |
5026 | const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder, |
5027 | const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) { |
5028 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
5029 | assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!" ); |
5030 | |
5031 | if (Builder.GetInsertBlock() == nullptr) |
5032 | return; |
5033 | if (VD->hasAttr<NoDebugAttr>()) |
5034 | return; |
5035 | |
5036 | bool isByRef = VD->hasAttr<BlocksAttr>(); |
5037 | |
5038 | uint64_t XOffset = 0; |
5039 | llvm::DIFile *Unit = getOrCreateFile(Loc: VD->getLocation()); |
5040 | llvm::DIType *Ty; |
5041 | if (isByRef) |
5042 | Ty = EmitTypeForVarWithBlocksAttr(VD, XOffset: &XOffset).WrappedType; |
5043 | else |
5044 | Ty = getOrCreateType(Ty: VD->getType(), Unit); |
5045 | |
5046 | // Self is passed along as an implicit non-arg variable in a |
5047 | // block. Mark it as the object pointer. |
5048 | if (const auto *IPD = dyn_cast<ImplicitParamDecl>(Val: VD)) |
5049 | if (IPD->getParameterKind() == ImplicitParamKind::ObjCSelf) |
5050 | Ty = CreateSelfType(QualTy: VD->getType(), Ty); |
5051 | |
5052 | // Get location information. |
5053 | const unsigned Line = |
5054 | getLineNumber(Loc: VD->getLocation().isValid() ? VD->getLocation() : CurLoc); |
5055 | unsigned Column = getColumnNumber(Loc: VD->getLocation()); |
5056 | |
5057 | const llvm::DataLayout &target = CGM.getDataLayout(); |
5058 | |
5059 | CharUnits offset = CharUnits::fromQuantity( |
5060 | Quantity: target.getStructLayout(Ty: blockInfo.StructureType) |
5061 | ->getElementOffset(Idx: blockInfo.getCapture(var: VD).getIndex())); |
5062 | |
5063 | SmallVector<uint64_t, 9> addr; |
5064 | addr.push_back(Elt: llvm::dwarf::DW_OP_deref); |
5065 | addr.push_back(Elt: llvm::dwarf::DW_OP_plus_uconst); |
5066 | addr.push_back(Elt: offset.getQuantity()); |
5067 | if (isByRef) { |
5068 | addr.push_back(Elt: llvm::dwarf::DW_OP_deref); |
5069 | addr.push_back(Elt: llvm::dwarf::DW_OP_plus_uconst); |
5070 | // offset of __forwarding field |
5071 | offset = |
5072 | CGM.getContext().toCharUnitsFromBits(BitSize: target.getPointerSizeInBits(AS: 0)); |
5073 | addr.push_back(Elt: offset.getQuantity()); |
5074 | addr.push_back(Elt: llvm::dwarf::DW_OP_deref); |
5075 | addr.push_back(Elt: llvm::dwarf::DW_OP_plus_uconst); |
5076 | // offset of x field |
5077 | offset = CGM.getContext().toCharUnitsFromBits(BitSize: XOffset); |
5078 | addr.push_back(Elt: offset.getQuantity()); |
5079 | } |
5080 | |
5081 | // Create the descriptor for the variable. |
5082 | auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); |
5083 | auto *D = DBuilder.createAutoVariable( |
5084 | Scope: cast<llvm::DILocalScope>(Val&: LexicalBlockStack.back()), Name: VD->getName(), File: Unit, |
5085 | LineNo: Line, Ty, AlwaysPreserve: false, Flags: llvm::DINode::FlagZero, AlignInBits: Align); |
5086 | |
5087 | // Insert an llvm.dbg.declare into the current block. |
5088 | auto DL = llvm::DILocation::get(Context&: CGM.getLLVMContext(), Line, Column, |
5089 | Scope: LexicalBlockStack.back(), InlinedAt: CurInlinedAt); |
5090 | auto *Expr = DBuilder.createExpression(Addr: addr); |
5091 | if (InsertPoint) |
5092 | DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint); |
5093 | else |
5094 | DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock()); |
5095 | } |
5096 | |
5097 | llvm::DILocalVariable * |
5098 | CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI, |
5099 | unsigned ArgNo, CGBuilderTy &Builder, |
5100 | bool UsePointerValue) { |
5101 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
5102 | return EmitDeclare(VD, Storage: AI, ArgNo, Builder, UsePointerValue); |
5103 | } |
5104 | |
5105 | namespace { |
5106 | struct BlockLayoutChunk { |
5107 | uint64_t OffsetInBits; |
5108 | const BlockDecl::Capture *Capture; |
5109 | }; |
5110 | bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) { |
5111 | return l.OffsetInBits < r.OffsetInBits; |
5112 | } |
5113 | } // namespace |
5114 | |
5115 | void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare( |
5116 | const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc, |
5117 | const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit, |
5118 | SmallVectorImpl<llvm::Metadata *> &Fields) { |
5119 | // Blocks in OpenCL have unique constraints which make the standard fields |
5120 | // redundant while requiring size and align fields for enqueue_kernel. See |
5121 | // initializeForBlockHeader in CGBlocks.cpp |
5122 | if (CGM.getLangOpts().OpenCL) { |
5123 | Fields.push_back(Elt: createFieldType("__size" , Context.IntTy, Loc, AS_public, |
5124 | BlockLayout.getElementOffsetInBits(Idx: 0), |
5125 | Unit, Unit)); |
5126 | Fields.push_back(Elt: createFieldType("__align" , Context.IntTy, Loc, AS_public, |
5127 | BlockLayout.getElementOffsetInBits(Idx: 1), |
5128 | Unit, Unit)); |
5129 | } else { |
5130 | Fields.push_back(Elt: createFieldType("__isa" , Context.VoidPtrTy, Loc, AS_public, |
5131 | BlockLayout.getElementOffsetInBits(Idx: 0), |
5132 | Unit, Unit)); |
5133 | Fields.push_back(Elt: createFieldType("__flags" , Context.IntTy, Loc, AS_public, |
5134 | BlockLayout.getElementOffsetInBits(Idx: 1), |
5135 | Unit, Unit)); |
5136 | Fields.push_back( |
5137 | Elt: createFieldType("__reserved" , Context.IntTy, Loc, AS_public, |
5138 | BlockLayout.getElementOffsetInBits(Idx: 2), Unit, Unit)); |
5139 | auto *FnTy = Block.getBlockExpr()->getFunctionType(); |
5140 | auto FnPtrType = CGM.getContext().getPointerType(T: FnTy->desugar()); |
5141 | Fields.push_back(Elt: createFieldType(name: "__FuncPtr" , type: FnPtrType, loc: Loc, AS: AS_public, |
5142 | offsetInBits: BlockLayout.getElementOffsetInBits(Idx: 3), |
5143 | tunit: Unit, scope: Unit)); |
5144 | Fields.push_back(Elt: createFieldType( |
5145 | name: "__descriptor" , |
5146 | type: Context.getPointerType(T: Block.NeedsCopyDispose |
5147 | ? Context.getBlockDescriptorExtendedType() |
5148 | : Context.getBlockDescriptorType()), |
5149 | loc: Loc, AS: AS_public, offsetInBits: BlockLayout.getElementOffsetInBits(Idx: 4), tunit: Unit, scope: Unit)); |
5150 | } |
5151 | } |
5152 | |
5153 | void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, |
5154 | StringRef Name, |
5155 | unsigned ArgNo, |
5156 | llvm::AllocaInst *Alloca, |
5157 | CGBuilderTy &Builder) { |
5158 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
5159 | ASTContext &C = CGM.getContext(); |
5160 | const BlockDecl *blockDecl = block.getBlockDecl(); |
5161 | |
5162 | // Collect some general information about the block's location. |
5163 | SourceLocation loc = blockDecl->getCaretLocation(); |
5164 | llvm::DIFile *tunit = getOrCreateFile(Loc: loc); |
5165 | unsigned line = getLineNumber(Loc: loc); |
5166 | unsigned column = getColumnNumber(Loc: loc); |
5167 | |
5168 | // Build the debug-info type for the block literal. |
5169 | getDeclContextDescriptor(blockDecl); |
5170 | |
5171 | const llvm::StructLayout *blockLayout = |
5172 | CGM.getDataLayout().getStructLayout(Ty: block.StructureType); |
5173 | |
5174 | SmallVector<llvm::Metadata *, 16> fields; |
5175 | collectDefaultFieldsForBlockLiteralDeclare(Block: block, Context: C, Loc: loc, BlockLayout: *blockLayout, Unit: tunit, |
5176 | Fields&: fields); |
5177 | |
5178 | // We want to sort the captures by offset, not because DWARF |
5179 | // requires this, but because we're paranoid about debuggers. |
5180 | SmallVector<BlockLayoutChunk, 8> chunks; |
5181 | |
5182 | // 'this' capture. |
5183 | if (blockDecl->capturesCXXThis()) { |
5184 | BlockLayoutChunk chunk; |
5185 | chunk.OffsetInBits = |
5186 | blockLayout->getElementOffsetInBits(Idx: block.CXXThisIndex); |
5187 | chunk.Capture = nullptr; |
5188 | chunks.push_back(Elt: chunk); |
5189 | } |
5190 | |
5191 | // Variable captures. |
5192 | for (const auto &capture : blockDecl->captures()) { |
5193 | const VarDecl *variable = capture.getVariable(); |
5194 | const CGBlockInfo::Capture &captureInfo = block.getCapture(var: variable); |
5195 | |
5196 | // Ignore constant captures. |
5197 | if (captureInfo.isConstant()) |
5198 | continue; |
5199 | |
5200 | BlockLayoutChunk chunk; |
5201 | chunk.OffsetInBits = |
5202 | blockLayout->getElementOffsetInBits(Idx: captureInfo.getIndex()); |
5203 | chunk.Capture = &capture; |
5204 | chunks.push_back(Elt: chunk); |
5205 | } |
5206 | |
5207 | // Sort by offset. |
5208 | llvm::array_pod_sort(Start: chunks.begin(), End: chunks.end()); |
5209 | |
5210 | for (const BlockLayoutChunk &Chunk : chunks) { |
5211 | uint64_t offsetInBits = Chunk.OffsetInBits; |
5212 | const BlockDecl::Capture *capture = Chunk.Capture; |
5213 | |
5214 | // If we have a null capture, this must be the C++ 'this' capture. |
5215 | if (!capture) { |
5216 | QualType type; |
5217 | if (auto *Method = |
5218 | cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext())) |
5219 | type = Method->getThisType(); |
5220 | else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent())) |
5221 | type = QualType(RDecl->getTypeForDecl(), 0); |
5222 | else |
5223 | llvm_unreachable("unexpected block declcontext" ); |
5224 | |
5225 | fields.push_back(Elt: createFieldType(name: "this" , type, loc, AS: AS_public, |
5226 | offsetInBits, tunit, scope: tunit)); |
5227 | continue; |
5228 | } |
5229 | |
5230 | const VarDecl *variable = capture->getVariable(); |
5231 | StringRef name = variable->getName(); |
5232 | |
5233 | llvm::DIType *fieldType; |
5234 | if (capture->isByRef()) { |
5235 | TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy); |
5236 | auto Align = PtrInfo.isAlignRequired() ? PtrInfo.Align : 0; |
5237 | // FIXME: This recomputes the layout of the BlockByRefWrapper. |
5238 | uint64_t xoffset; |
5239 | fieldType = |
5240 | EmitTypeForVarWithBlocksAttr(VD: variable, XOffset: &xoffset).BlockByRefWrapper; |
5241 | fieldType = DBuilder.createPointerType(PointeeTy: fieldType, SizeInBits: PtrInfo.Width); |
5242 | fieldType = DBuilder.createMemberType(Scope: tunit, Name: name, File: tunit, LineNo: line, |
5243 | SizeInBits: PtrInfo.Width, AlignInBits: Align, OffsetInBits: offsetInBits, |
5244 | Flags: llvm::DINode::FlagZero, Ty: fieldType); |
5245 | } else { |
5246 | auto Align = getDeclAlignIfRequired(variable, CGM.getContext()); |
5247 | fieldType = createFieldType(name, variable->getType(), loc, AS_public, |
5248 | offsetInBits, Align, tunit, tunit); |
5249 | } |
5250 | fields.push_back(Elt: fieldType); |
5251 | } |
5252 | |
5253 | SmallString<36> typeName; |
5254 | llvm::raw_svector_ostream(typeName) |
5255 | << "__block_literal_" << CGM.getUniqueBlockCount(); |
5256 | |
5257 | llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(Elements: fields); |
5258 | |
5259 | llvm::DIType *type = |
5260 | DBuilder.createStructType(Scope: tunit, Name: typeName.str(), File: tunit, LineNumber: line, |
5261 | SizeInBits: CGM.getContext().toBits(CharSize: block.BlockSize), AlignInBits: 0, |
5262 | Flags: llvm::DINode::FlagZero, DerivedFrom: nullptr, Elements: fieldsArray); |
5263 | type = DBuilder.createPointerType(PointeeTy: type, SizeInBits: CGM.PointerWidthInBits); |
5264 | |
5265 | // Get overall information about the block. |
5266 | llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial; |
5267 | auto *scope = cast<llvm::DILocalScope>(Val&: LexicalBlockStack.back()); |
5268 | |
5269 | // Create the descriptor for the parameter. |
5270 | auto *debugVar = DBuilder.createParameterVariable( |
5271 | Scope: scope, Name, ArgNo, File: tunit, LineNo: line, Ty: type, AlwaysPreserve: CGM.getLangOpts().Optimize, Flags: flags); |
5272 | |
5273 | // Insert an llvm.dbg.declare into the current block. |
5274 | DBuilder.insertDeclare(Storage: Alloca, VarInfo: debugVar, Expr: DBuilder.createExpression(), |
5275 | DL: llvm::DILocation::get(Context&: CGM.getLLVMContext(), Line: line, |
5276 | Column: column, Scope: scope, InlinedAt: CurInlinedAt), |
5277 | InsertAtEnd: Builder.GetInsertBlock()); |
5278 | } |
5279 | |
5280 | llvm::DIDerivedType * |
5281 | CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) { |
5282 | if (!D || !D->isStaticDataMember()) |
5283 | return nullptr; |
5284 | |
5285 | auto MI = StaticDataMemberCache.find(D->getCanonicalDecl()); |
5286 | if (MI != StaticDataMemberCache.end()) { |
5287 | assert(MI->second && "Static data member declaration should still exist" ); |
5288 | return MI->second; |
5289 | } |
5290 | |
5291 | // If the member wasn't found in the cache, lazily construct and add it to the |
5292 | // type (used when a limited form of the type is emitted). |
5293 | auto DC = D->getDeclContext(); |
5294 | auto *Ctxt = cast<llvm::DICompositeType>(Val: getDeclContextDescriptor(D)); |
5295 | return CreateRecordStaticField(Var: D, RecordTy: Ctxt, RD: cast<RecordDecl>(DC)); |
5296 | } |
5297 | |
5298 | llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls( |
5299 | const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo, |
5300 | StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) { |
5301 | llvm::DIGlobalVariableExpression *GVE = nullptr; |
5302 | |
5303 | for (const auto *Field : RD->fields()) { |
5304 | llvm::DIType *FieldTy = getOrCreateType(Ty: Field->getType(), Unit); |
5305 | StringRef FieldName = Field->getName(); |
5306 | |
5307 | // Ignore unnamed fields, but recurse into anonymous records. |
5308 | if (FieldName.empty()) { |
5309 | if (const auto *RT = dyn_cast<RecordType>(Field->getType())) |
5310 | GVE = CollectAnonRecordDecls(RD: RT->getDecl(), Unit, LineNo, LinkageName, |
5311 | Var, DContext); |
5312 | continue; |
5313 | } |
5314 | // Use VarDecl's Tag, Scope and Line number. |
5315 | GVE = DBuilder.createGlobalVariableExpression( |
5316 | Context: DContext, Name: FieldName, LinkageName, File: Unit, LineNo, Ty: FieldTy, |
5317 | IsLocalToUnit: Var->hasLocalLinkage()); |
5318 | Var->addDebugInfo(GV: GVE); |
5319 | } |
5320 | return GVE; |
5321 | } |
5322 | |
5323 | static bool ReferencesAnonymousEntity(ArrayRef<TemplateArgument> Args); |
5324 | static bool ReferencesAnonymousEntity(RecordType *RT) { |
5325 | // Unnamed classes/lambdas can't be reconstituted due to a lack of column |
5326 | // info we produce in the DWARF, so we can't get Clang's full name back. |
5327 | // But so long as it's not one of those, it doesn't matter if some sub-type |
5328 | // of the record (a template parameter) can't be reconstituted - because the |
5329 | // un-reconstitutable type itself will carry its own name. |
5330 | const auto *RD = dyn_cast<CXXRecordDecl>(Val: RT->getDecl()); |
5331 | if (!RD) |
5332 | return false; |
5333 | if (!RD->getIdentifier()) |
5334 | return true; |
5335 | auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD); |
5336 | if (!TSpecial) |
5337 | return false; |
5338 | return ReferencesAnonymousEntity(Args: TSpecial->getTemplateArgs().asArray()); |
5339 | } |
5340 | static bool ReferencesAnonymousEntity(ArrayRef<TemplateArgument> Args) { |
5341 | return llvm::any_of(Range&: Args, P: [&](const TemplateArgument &TA) { |
5342 | switch (TA.getKind()) { |
5343 | case TemplateArgument::Pack: |
5344 | return ReferencesAnonymousEntity(Args: TA.getPackAsArray()); |
5345 | case TemplateArgument::Type: { |
5346 | struct ReferencesAnonymous |
5347 | : public RecursiveASTVisitor<ReferencesAnonymous> { |
5348 | bool RefAnon = false; |
5349 | bool VisitRecordType(RecordType *RT) { |
5350 | if (ReferencesAnonymousEntity(RT)) { |
5351 | RefAnon = true; |
5352 | return false; |
5353 | } |
5354 | return true; |
5355 | } |
5356 | }; |
5357 | ReferencesAnonymous RT; |
5358 | RT.TraverseType(T: TA.getAsType()); |
5359 | if (RT.RefAnon) |
5360 | return true; |
5361 | break; |
5362 | } |
5363 | default: |
5364 | break; |
5365 | } |
5366 | return false; |
5367 | }); |
5368 | } |
5369 | namespace { |
5370 | struct ReconstitutableType : public RecursiveASTVisitor<ReconstitutableType> { |
5371 | bool Reconstitutable = true; |
5372 | bool VisitVectorType(VectorType *FT) { |
5373 | Reconstitutable = false; |
5374 | return false; |
5375 | } |
5376 | bool VisitAtomicType(AtomicType *FT) { |
5377 | Reconstitutable = false; |
5378 | return false; |
5379 | } |
5380 | bool VisitType(Type *T) { |
5381 | // _BitInt(N) isn't reconstitutable because the bit width isn't encoded in |
5382 | // the DWARF, only the byte width. |
5383 | if (T->isBitIntType()) { |
5384 | Reconstitutable = false; |
5385 | return false; |
5386 | } |
5387 | return true; |
5388 | } |
5389 | bool TraverseEnumType(EnumType *ET) { |
5390 | // Unnamed enums can't be reconstituted due to a lack of column info we |
5391 | // produce in the DWARF, so we can't get Clang's full name back. |
5392 | if (const auto *ED = dyn_cast<EnumDecl>(Val: ET->getDecl())) { |
5393 | if (!ED->getIdentifier()) { |
5394 | Reconstitutable = false; |
5395 | return false; |
5396 | } |
5397 | if (!ED->isExternallyVisible()) { |
5398 | Reconstitutable = false; |
5399 | return false; |
5400 | } |
5401 | } |
5402 | return true; |
5403 | } |
5404 | bool VisitFunctionProtoType(FunctionProtoType *FT) { |
5405 | // noexcept is not encoded in DWARF, so the reversi |
5406 | Reconstitutable &= !isNoexceptExceptionSpec(ESpecType: FT->getExceptionSpecType()); |
5407 | Reconstitutable &= !FT->getNoReturnAttr(); |
5408 | return Reconstitutable; |
5409 | } |
5410 | bool VisitRecordType(RecordType *RT) { |
5411 | if (ReferencesAnonymousEntity(RT)) { |
5412 | Reconstitutable = false; |
5413 | return false; |
5414 | } |
5415 | return true; |
5416 | } |
5417 | }; |
5418 | } // anonymous namespace |
5419 | |
5420 | // Test whether a type name could be rebuilt from emitted debug info. |
5421 | static bool IsReconstitutableType(QualType QT) { |
5422 | ReconstitutableType T; |
5423 | T.TraverseType(T: QT); |
5424 | return T.Reconstitutable; |
5425 | } |
5426 | |
5427 | bool CGDebugInfo::HasReconstitutableArgs( |
5428 | ArrayRef<TemplateArgument> Args) const { |
5429 | return llvm::all_of(Range&: Args, P: [&](const TemplateArgument &TA) { |
5430 | switch (TA.getKind()) { |
5431 | case TemplateArgument::Template: |
5432 | // Easy to reconstitute - the value of the parameter in the debug |
5433 | // info is the string name of the template. The template name |
5434 | // itself won't benefit from any name rebuilding, but that's a |
5435 | // representational limitation - maybe DWARF could be |
5436 | // changed/improved to use some more structural representation. |
5437 | return true; |
5438 | case TemplateArgument::Declaration: |
5439 | // Reference and pointer non-type template parameters point to |
5440 | // variables, functions, etc and their value is, at best (for |
5441 | // variables) represented as an address - not a reference to the |
5442 | // DWARF describing the variable/function/etc. This makes it hard, |
5443 | // possibly impossible to rebuild the original name - looking up |
5444 | // the address in the executable file's symbol table would be |
5445 | // needed. |
5446 | return false; |
5447 | case TemplateArgument::NullPtr: |
5448 | // These could be rebuilt, but figured they're close enough to the |
5449 | // declaration case, and not worth rebuilding. |
5450 | return false; |
5451 | case TemplateArgument::Pack: |
5452 | // A pack is invalid if any of the elements of the pack are |
5453 | // invalid. |
5454 | return HasReconstitutableArgs(Args: TA.getPackAsArray()); |
5455 | case TemplateArgument::Integral: |
5456 | // Larger integers get encoded as DWARF blocks which are a bit |
5457 | // harder to parse back into a large integer, etc - so punting on |
5458 | // this for now. Re-parsing the integers back into APInt is |
5459 | // probably feasible some day. |
5460 | return TA.getAsIntegral().getBitWidth() <= 64 && |
5461 | IsReconstitutableType(QT: TA.getIntegralType()); |
5462 | case TemplateArgument::StructuralValue: |
5463 | return false; |
5464 | case TemplateArgument::Type: |
5465 | return IsReconstitutableType(QT: TA.getAsType()); |
5466 | case TemplateArgument::Expression: |
5467 | return IsReconstitutableType(QT: TA.getAsExpr()->getType()); |
5468 | default: |
5469 | llvm_unreachable("Other, unresolved, template arguments should " |
5470 | "not be seen here" ); |
5471 | } |
5472 | }); |
5473 | } |
5474 | |
5475 | std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const { |
5476 | std::string Name; |
5477 | llvm::raw_string_ostream OS(Name); |
5478 | const NamedDecl *ND = dyn_cast<NamedDecl>(Val: D); |
5479 | if (!ND) |
5480 | return Name; |
5481 | llvm::codegenoptions::DebugTemplateNamesKind TemplateNamesKind = |
5482 | CGM.getCodeGenOpts().getDebugSimpleTemplateNames(); |
5483 | |
5484 | if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) |
5485 | TemplateNamesKind = llvm::codegenoptions::DebugTemplateNamesKind::Full; |
5486 | |
5487 | std::optional<TemplateArgs> Args; |
5488 | |
5489 | bool IsOperatorOverload = false; // isa<CXXConversionDecl>(ND); |
5490 | if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND)) { |
5491 | Args = GetTemplateArgs(RD); |
5492 | } else if (auto *FD = dyn_cast<FunctionDecl>(Val: ND)) { |
5493 | Args = GetTemplateArgs(FD); |
5494 | auto NameKind = ND->getDeclName().getNameKind(); |
5495 | IsOperatorOverload |= |
5496 | NameKind == DeclarationName::CXXOperatorName || |
5497 | NameKind == DeclarationName::CXXConversionFunctionName; |
5498 | } else if (auto *VD = dyn_cast<VarDecl>(Val: ND)) { |
5499 | Args = GetTemplateArgs(VD); |
5500 | } |
5501 | |
5502 | // A conversion operator presents complications/ambiguity if there's a |
5503 | // conversion to class template that is itself a template, eg: |
5504 | // template<typename T> |
5505 | // operator ns::t1<T, int>(); |
5506 | // This should be named, eg: "operator ns::t1<float, int><float>" |
5507 | // (ignoring clang bug that means this is currently "operator t1<float>") |
5508 | // but if the arguments were stripped, the consumer couldn't differentiate |
5509 | // whether the template argument list for the conversion type was the |
5510 | // function's argument list (& no reconstitution was needed) or not. |
5511 | // This could be handled if reconstitutable names had a separate attribute |
5512 | // annotating them as such - this would remove the ambiguity. |
5513 | // |
5514 | // Alternatively the template argument list could be parsed enough to check |
5515 | // whether there's one list or two, then compare that with the DWARF |
5516 | // description of the return type and the template argument lists to determine |
5517 | // how many lists there should be and if one is missing it could be assumed(?) |
5518 | // to be the function's template argument list & then be rebuilt. |
5519 | // |
5520 | // Other operator overloads that aren't conversion operators could be |
5521 | // reconstituted but would require a bit more nuance about detecting the |
5522 | // difference between these different operators during that rebuilding. |
5523 | bool Reconstitutable = |
5524 | Args && HasReconstitutableArgs(Args: Args->Args) && !IsOperatorOverload; |
5525 | |
5526 | PrintingPolicy PP = getPrintingPolicy(); |
5527 | |
5528 | if (TemplateNamesKind == llvm::codegenoptions::DebugTemplateNamesKind::Full || |
5529 | !Reconstitutable) { |
5530 | ND->getNameForDiagnostic(OS, Policy: PP, Qualified); |
5531 | } else { |
5532 | bool Mangled = TemplateNamesKind == |
5533 | llvm::codegenoptions::DebugTemplateNamesKind::Mangled; |
5534 | // check if it's a template |
5535 | if (Mangled) |
5536 | OS << "_STN|" ; |
5537 | |
5538 | OS << ND->getDeclName(); |
5539 | std::string EncodedOriginalName; |
5540 | llvm::raw_string_ostream EncodedOriginalNameOS(EncodedOriginalName); |
5541 | EncodedOriginalNameOS << ND->getDeclName(); |
5542 | |
5543 | if (Mangled) { |
5544 | OS << "|" ; |
5545 | printTemplateArgumentList(OS, Args: Args->Args, Policy: PP); |
5546 | printTemplateArgumentList(OS&: EncodedOriginalNameOS, Args: Args->Args, Policy: PP); |
5547 | #ifndef NDEBUG |
5548 | std::string CanonicalOriginalName; |
5549 | llvm::raw_string_ostream OriginalOS(CanonicalOriginalName); |
5550 | ND->getNameForDiagnostic(OS&: OriginalOS, Policy: PP, Qualified); |
5551 | assert(EncodedOriginalNameOS.str() == OriginalOS.str()); |
5552 | #endif |
5553 | } |
5554 | } |
5555 | return Name; |
5556 | } |
5557 | |
5558 | void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var, |
5559 | const VarDecl *D) { |
5560 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
5561 | if (D->hasAttr<NoDebugAttr>()) |
5562 | return; |
5563 | |
5564 | llvm::TimeTraceScope TimeScope("DebugGlobalVariable" , [&]() { |
5565 | return GetName(D, true); |
5566 | }); |
5567 | |
5568 | // If we already created a DIGlobalVariable for this declaration, just attach |
5569 | // it to the llvm::GlobalVariable. |
5570 | auto Cached = DeclCache.find(D->getCanonicalDecl()); |
5571 | if (Cached != DeclCache.end()) |
5572 | return Var->addDebugInfo( |
5573 | GV: cast<llvm::DIGlobalVariableExpression>(Cached->second)); |
5574 | |
5575 | // Create global variable debug descriptor. |
5576 | llvm::DIFile *Unit = nullptr; |
5577 | llvm::DIScope *DContext = nullptr; |
5578 | unsigned LineNo; |
5579 | StringRef DeclName, LinkageName; |
5580 | QualType T; |
5581 | llvm::MDTuple *TemplateParameters = nullptr; |
5582 | collectVarDeclProps(VD: D, Unit, LineNo, T, Name&: DeclName, LinkageName, |
5583 | TemplateParameters, VDContext&: DContext); |
5584 | |
5585 | // Attempt to store one global variable for the declaration - even if we |
5586 | // emit a lot of fields. |
5587 | llvm::DIGlobalVariableExpression *GVE = nullptr; |
5588 | |
5589 | // If this is an anonymous union then we'll want to emit a global |
5590 | // variable for each member of the anonymous union so that it's possible |
5591 | // to find the name of any field in the union. |
5592 | if (T->isUnionType() && DeclName.empty()) { |
5593 | const RecordDecl *RD = T->castAs<RecordType>()->getDecl(); |
5594 | assert(RD->isAnonymousStructOrUnion() && |
5595 | "unnamed non-anonymous struct or union?" ); |
5596 | GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext); |
5597 | } else { |
5598 | auto Align = getDeclAlignIfRequired(D, CGM.getContext()); |
5599 | |
5600 | SmallVector<uint64_t, 4> Expr; |
5601 | unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(T: D->getType()); |
5602 | if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) { |
5603 | if (D->hasAttr<CUDASharedAttr>()) |
5604 | AddressSpace = |
5605 | CGM.getContext().getTargetAddressSpace(AS: LangAS::cuda_shared); |
5606 | else if (D->hasAttr<CUDAConstantAttr>()) |
5607 | AddressSpace = |
5608 | CGM.getContext().getTargetAddressSpace(AS: LangAS::cuda_constant); |
5609 | } |
5610 | AppendAddressSpaceXDeref(AddressSpace, Expr); |
5611 | |
5612 | llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D); |
5613 | GVE = DBuilder.createGlobalVariableExpression( |
5614 | Context: DContext, Name: DeclName, LinkageName, File: Unit, LineNo, Ty: getOrCreateType(Ty: T, Unit), |
5615 | IsLocalToUnit: Var->hasLocalLinkage(), isDefined: true, |
5616 | Expr: Expr.empty() ? nullptr : DBuilder.createExpression(Addr: Expr), |
5617 | Decl: getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParams: TemplateParameters, |
5618 | AlignInBits: Align, Annotations); |
5619 | Var->addDebugInfo(GV: GVE); |
5620 | } |
5621 | DeclCache[D->getCanonicalDecl()].reset(GVE); |
5622 | } |
5623 | |
5624 | void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) { |
5625 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
5626 | if (VD->hasAttr<NoDebugAttr>()) |
5627 | return; |
5628 | llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable" , [&]() { |
5629 | return GetName(VD, true); |
5630 | }); |
5631 | |
5632 | auto Align = getDeclAlignIfRequired(VD, CGM.getContext()); |
5633 | // Create the descriptor for the variable. |
5634 | llvm::DIFile *Unit = getOrCreateFile(Loc: VD->getLocation()); |
5635 | StringRef Name = VD->getName(); |
5636 | llvm::DIType *Ty = getOrCreateType(Ty: VD->getType(), Unit); |
5637 | |
5638 | if (const auto *ECD = dyn_cast<EnumConstantDecl>(Val: VD)) { |
5639 | const auto *ED = cast<EnumDecl>(ECD->getDeclContext()); |
5640 | assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?" ); |
5641 | |
5642 | if (CGM.getCodeGenOpts().EmitCodeView) { |
5643 | // If CodeView, emit enums as global variables, unless they are defined |
5644 | // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for |
5645 | // enums in classes, and because it is difficult to attach this scope |
5646 | // information to the global variable. |
5647 | if (isa<RecordDecl>(ED->getDeclContext())) |
5648 | return; |
5649 | } else { |
5650 | // If not CodeView, emit DW_TAG_enumeration_type if necessary. For |
5651 | // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the |
5652 | // first time `ZERO` is referenced in a function. |
5653 | llvm::DIType *EDTy = |
5654 | getOrCreateType(Ty: QualType(ED->getTypeForDecl(), 0), Unit); |
5655 | assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type); |
5656 | (void)EDTy; |
5657 | return; |
5658 | } |
5659 | } |
5660 | |
5661 | // Do not emit separate definitions for function local consts. |
5662 | if (isa<FunctionDecl>(VD->getDeclContext())) |
5663 | return; |
5664 | |
5665 | VD = cast<ValueDecl>(VD->getCanonicalDecl()); |
5666 | auto *VarD = dyn_cast<VarDecl>(Val: VD); |
5667 | if (VarD && VarD->isStaticDataMember()) { |
5668 | auto *RD = cast<RecordDecl>(VarD->getDeclContext()); |
5669 | getDeclContextDescriptor(VarD); |
5670 | // Ensure that the type is retained even though it's otherwise unreferenced. |
5671 | // |
5672 | // FIXME: This is probably unnecessary, since Ty should reference RD |
5673 | // through its scope. |
5674 | RetainedTypes.push_back( |
5675 | CGM.getContext().getRecordType(Decl: RD).getAsOpaquePtr()); |
5676 | |
5677 | return; |
5678 | } |
5679 | llvm::DIScope *DContext = getDeclContextDescriptor(VD); |
5680 | |
5681 | auto &GV = DeclCache[VD]; |
5682 | if (GV) |
5683 | return; |
5684 | |
5685 | llvm::DIExpression *InitExpr = createConstantValueExpression(VD, Val: Init); |
5686 | llvm::MDTuple *TemplateParameters = nullptr; |
5687 | |
5688 | if (isa<VarTemplateSpecializationDecl>(Val: VD)) |
5689 | if (VarD) { |
5690 | llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VL: VarD, Unit: &*Unit); |
5691 | TemplateParameters = parameterNodes.get(); |
5692 | } |
5693 | |
5694 | GV.reset(DBuilder.createGlobalVariableExpression( |
5695 | Context: DContext, Name, LinkageName: StringRef(), File: Unit, LineNo: getLineNumber(Loc: VD->getLocation()), Ty, |
5696 | IsLocalToUnit: true, isDefined: true, Expr: InitExpr, Decl: getOrCreateStaticDataMemberDeclarationOrNull(D: VarD), |
5697 | TemplateParams: TemplateParameters, AlignInBits: Align)); |
5698 | } |
5699 | |
5700 | void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var, |
5701 | const VarDecl *D) { |
5702 | assert(CGM.getCodeGenOpts().hasReducedDebugInfo()); |
5703 | if (D->hasAttr<NoDebugAttr>()) |
5704 | return; |
5705 | |
5706 | auto Align = getDeclAlignIfRequired(D, CGM.getContext()); |
5707 | llvm::DIFile *Unit = getOrCreateFile(Loc: D->getLocation()); |
5708 | StringRef Name = D->getName(); |
5709 | llvm::DIType *Ty = getOrCreateType(Ty: D->getType(), Unit); |
5710 | |
5711 | llvm::DIScope *DContext = getDeclContextDescriptor(D); |
5712 | llvm::DIGlobalVariableExpression *GVE = |
5713 | DBuilder.createGlobalVariableExpression( |
5714 | Context: DContext, Name, LinkageName: StringRef(), File: Unit, LineNo: getLineNumber(Loc: D->getLocation()), |
5715 | Ty, IsLocalToUnit: false, isDefined: false, Expr: nullptr, Decl: nullptr, TemplateParams: nullptr, AlignInBits: Align); |
5716 | Var->addDebugInfo(GV: GVE); |
5717 | } |
5718 | |
5719 | void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV, |
5720 | const GlobalDecl GD) { |
5721 | |
5722 | assert(GV); |
5723 | |
5724 | if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) |
5725 | return; |
5726 | |
5727 | const auto *D = cast<ValueDecl>(Val: GD.getDecl()); |
5728 | if (D->hasAttr<NoDebugAttr>()) |
5729 | return; |
5730 | |
5731 | auto AliaseeDecl = CGM.getMangledNameDecl(GV->getName()); |
5732 | llvm::DINode *DI; |
5733 | |
5734 | if (!AliaseeDecl) |
5735 | // FIXME: Aliasee not declared yet - possibly declared later |
5736 | // For example, |
5737 | // |
5738 | // 1 extern int newname __attribute__((alias("oldname"))); |
5739 | // 2 int oldname = 1; |
5740 | // |
5741 | // No debug info would be generated for 'newname' in this case. |
5742 | // |
5743 | // Fix compiler to generate "newname" as imported_declaration |
5744 | // pointing to the DIE of "oldname". |
5745 | return; |
5746 | if (!(DI = getDeclarationOrDefinition( |
5747 | D: AliaseeDecl.getCanonicalDecl().getDecl()))) |
5748 | return; |
5749 | |
5750 | llvm::DIScope *DContext = getDeclContextDescriptor(D); |
5751 | auto Loc = D->getLocation(); |
5752 | |
5753 | llvm::DIImportedEntity *ImportDI = DBuilder.createImportedDeclaration( |
5754 | Context: DContext, Decl: DI, File: getOrCreateFile(Loc: Loc), Line: getLineNumber(Loc: Loc), Name: D->getName()); |
5755 | |
5756 | // Record this DIE in the cache for nested declaration reference. |
5757 | ImportedDeclCache[GD.getCanonicalDecl().getDecl()].reset(MD: ImportDI); |
5758 | } |
5759 | |
5760 | void CGDebugInfo::AddStringLiteralDebugInfo(llvm::GlobalVariable *GV, |
5761 | const StringLiteral *S) { |
5762 | SourceLocation Loc = S->getStrTokenLoc(TokNum: 0); |
5763 | PresumedLoc PLoc = CGM.getContext().getSourceManager().getPresumedLoc(Loc); |
5764 | if (!PLoc.isValid()) |
5765 | return; |
5766 | |
5767 | llvm::DIFile *File = getOrCreateFile(Loc); |
5768 | llvm::DIGlobalVariableExpression *Debug = |
5769 | DBuilder.createGlobalVariableExpression( |
5770 | Context: nullptr, Name: StringRef(), LinkageName: StringRef(), File: getOrCreateFile(Loc), |
5771 | LineNo: getLineNumber(Loc), Ty: getOrCreateType(Ty: S->getType(), Unit: File), IsLocalToUnit: true); |
5772 | GV->addDebugInfo(GV: Debug); |
5773 | } |
5774 | |
5775 | llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) { |
5776 | if (!LexicalBlockStack.empty()) |
5777 | return LexicalBlockStack.back(); |
5778 | llvm::DIScope *Mod = getParentModuleOrNull(D); |
5779 | return getContextDescriptor(Context: D, Default: Mod ? Mod : TheCU); |
5780 | } |
5781 | |
5782 | void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) { |
5783 | if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) |
5784 | return; |
5785 | const NamespaceDecl *NSDecl = UD.getNominatedNamespace(); |
5786 | if (!NSDecl->isAnonymousNamespace() || |
5787 | CGM.getCodeGenOpts().DebugExplicitImport) { |
5788 | auto Loc = UD.getLocation(); |
5789 | if (!Loc.isValid()) |
5790 | Loc = CurLoc; |
5791 | DBuilder.createImportedModule( |
5792 | getCurrentContextDescriptor(D: cast<Decl>(UD.getDeclContext())), |
5793 | getOrCreateNamespace(N: NSDecl), getOrCreateFile(Loc: Loc), getLineNumber(Loc: Loc)); |
5794 | } |
5795 | } |
5796 | |
5797 | void CGDebugInfo::EmitUsingShadowDecl(const UsingShadowDecl &USD) { |
5798 | if (llvm::DINode *Target = |
5799 | getDeclarationOrDefinition(D: USD.getUnderlyingDecl())) { |
5800 | auto Loc = USD.getLocation(); |
5801 | DBuilder.createImportedDeclaration( |
5802 | Context: getCurrentContextDescriptor(D: cast<Decl>(USD.getDeclContext())), Decl: Target, |
5803 | File: getOrCreateFile(Loc: Loc), Line: getLineNumber(Loc: Loc)); |
5804 | } |
5805 | } |
5806 | |
5807 | void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) { |
5808 | if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) |
5809 | return; |
5810 | assert(UD.shadow_size() && |
5811 | "We shouldn't be codegening an invalid UsingDecl containing no decls" ); |
5812 | |
5813 | for (const auto *USD : UD.shadows()) { |
5814 | // FIXME: Skip functions with undeduced auto return type for now since we |
5815 | // don't currently have the plumbing for separate declarations & definitions |
5816 | // of free functions and mismatched types (auto in the declaration, concrete |
5817 | // return type in the definition) |
5818 | if (const auto *FD = dyn_cast<FunctionDecl>(USD->getUnderlyingDecl())) |
5819 | if (const auto *AT = FD->getType() |
5820 | ->castAs<FunctionProtoType>() |
5821 | ->getContainedAutoType()) |
5822 | if (AT->getDeducedType().isNull()) |
5823 | continue; |
5824 | |
5825 | EmitUsingShadowDecl(*USD); |
5826 | // Emitting one decl is sufficient - debuggers can detect that this is an |
5827 | // overloaded name & provide lookup for all the overloads. |
5828 | break; |
5829 | } |
5830 | } |
5831 | |
5832 | void CGDebugInfo::EmitUsingEnumDecl(const UsingEnumDecl &UD) { |
5833 | if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) |
5834 | return; |
5835 | assert(UD.shadow_size() && |
5836 | "We shouldn't be codegening an invalid UsingEnumDecl" |
5837 | " containing no decls" ); |
5838 | |
5839 | for (const auto *USD : UD.shadows()) |
5840 | EmitUsingShadowDecl(*USD); |
5841 | } |
5842 | |
5843 | void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) { |
5844 | if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB) |
5845 | return; |
5846 | if (Module *M = ID.getImportedModule()) { |
5847 | auto Info = ASTSourceDescriptor(*M); |
5848 | auto Loc = ID.getLocation(); |
5849 | DBuilder.createImportedDeclaration( |
5850 | Context: getCurrentContextDescriptor(D: cast<Decl>(ID.getDeclContext())), |
5851 | Decl: getOrCreateModuleRef(Mod: Info, CreateSkeletonCU: DebugTypeExtRefs), File: getOrCreateFile(Loc: Loc), |
5852 | Line: getLineNumber(Loc: Loc)); |
5853 | } |
5854 | } |
5855 | |
5856 | llvm::DIImportedEntity * |
5857 | CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) { |
5858 | if (!CGM.getCodeGenOpts().hasReducedDebugInfo()) |
5859 | return nullptr; |
5860 | auto &VH = NamespaceAliasCache[&NA]; |
5861 | if (VH) |
5862 | return cast<llvm::DIImportedEntity>(Val&: VH); |
5863 | llvm::DIImportedEntity *R; |
5864 | auto Loc = NA.getLocation(); |
5865 | if (const auto *Underlying = |
5866 | dyn_cast<NamespaceAliasDecl>(Val: NA.getAliasedNamespace())) |
5867 | // This could cache & dedup here rather than relying on metadata deduping. |
5868 | R = DBuilder.createImportedDeclaration( |
5869 | Context: getCurrentContextDescriptor(D: cast<Decl>(NA.getDeclContext())), |
5870 | Decl: EmitNamespaceAlias(NA: *Underlying), File: getOrCreateFile(Loc: Loc), |
5871 | Line: getLineNumber(Loc: Loc), Name: NA.getName()); |
5872 | else |
5873 | R = DBuilder.createImportedDeclaration( |
5874 | Context: getCurrentContextDescriptor(D: cast<Decl>(NA.getDeclContext())), |
5875 | Decl: getOrCreateNamespace(N: cast<NamespaceDecl>(Val: NA.getAliasedNamespace())), |
5876 | File: getOrCreateFile(Loc: Loc), Line: getLineNumber(Loc: Loc), Name: NA.getName()); |
5877 | VH.reset(MD: R); |
5878 | return R; |
5879 | } |
5880 | |
5881 | llvm::DINamespace * |
5882 | CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) { |
5883 | // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued |
5884 | // if necessary, and this way multiple declarations of the same namespace in |
5885 | // different parent modules stay distinct. |
5886 | auto I = NamespaceCache.find(Val: NSDecl); |
5887 | if (I != NamespaceCache.end()) |
5888 | return cast<llvm::DINamespace>(Val&: I->second); |
5889 | |
5890 | llvm::DIScope *Context = getDeclContextDescriptor(NSDecl); |
5891 | // Don't trust the context if it is a DIModule (see comment above). |
5892 | llvm::DINamespace *NS = |
5893 | DBuilder.createNameSpace(Scope: Context, Name: NSDecl->getName(), ExportSymbols: NSDecl->isInline()); |
5894 | NamespaceCache[NSDecl].reset(MD: NS); |
5895 | return NS; |
5896 | } |
5897 | |
5898 | void CGDebugInfo::setDwoId(uint64_t Signature) { |
5899 | assert(TheCU && "no main compile unit" ); |
5900 | TheCU->setDWOId(Signature); |
5901 | } |
5902 | |
5903 | void CGDebugInfo::finalize() { |
5904 | // Creating types might create further types - invalidating the current |
5905 | // element and the size(), so don't cache/reference them. |
5906 | for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) { |
5907 | ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i]; |
5908 | llvm::DIType *Ty = E.Type->getDecl()->getDefinition() |
5909 | ? CreateTypeDefinition(Ty: E.Type, Unit: E.Unit) |
5910 | : E.Decl; |
5911 | DBuilder.replaceTemporary(N: llvm::TempDIType(E.Decl), Replacement: Ty); |
5912 | } |
5913 | |
5914 | // Add methods to interface. |
5915 | for (const auto &P : ObjCMethodCache) { |
5916 | if (P.second.empty()) |
5917 | continue; |
5918 | |
5919 | QualType QTy(P.first->getTypeForDecl(), 0); |
5920 | auto It = TypeCache.find(Val: QTy.getAsOpaquePtr()); |
5921 | assert(It != TypeCache.end()); |
5922 | |
5923 | llvm::DICompositeType *InterfaceDecl = |
5924 | cast<llvm::DICompositeType>(Val&: It->second); |
5925 | |
5926 | auto CurElts = InterfaceDecl->getElements(); |
5927 | SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end()); |
5928 | |
5929 | // For DWARF v4 or earlier, only add objc_direct methods. |
5930 | for (auto &SubprogramDirect : P.second) |
5931 | if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt()) |
5932 | EltTys.push_back(Elt: SubprogramDirect.getPointer()); |
5933 | |
5934 | llvm::DINodeArray Elements = DBuilder.getOrCreateArray(Elements: EltTys); |
5935 | DBuilder.replaceArrays(T&: InterfaceDecl, Elements); |
5936 | } |
5937 | |
5938 | for (const auto &P : ReplaceMap) { |
5939 | assert(P.second); |
5940 | auto *Ty = cast<llvm::DIType>(Val: P.second); |
5941 | assert(Ty->isForwardDecl()); |
5942 | |
5943 | auto It = TypeCache.find(Val: P.first); |
5944 | assert(It != TypeCache.end()); |
5945 | assert(It->second); |
5946 | |
5947 | DBuilder.replaceTemporary(N: llvm::TempDIType(Ty), |
5948 | Replacement: cast<llvm::DIType>(Val&: It->second)); |
5949 | } |
5950 | |
5951 | for (const auto &P : FwdDeclReplaceMap) { |
5952 | assert(P.second); |
5953 | llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(Val: P.second)); |
5954 | llvm::Metadata *Repl; |
5955 | |
5956 | auto It = DeclCache.find(P.first); |
5957 | // If there has been no definition for the declaration, call RAUW |
5958 | // with ourselves, that will destroy the temporary MDNode and |
5959 | // replace it with a standard one, avoiding leaking memory. |
5960 | if (It == DeclCache.end()) |
5961 | Repl = P.second; |
5962 | else |
5963 | Repl = It->second; |
5964 | |
5965 | if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Val: Repl)) |
5966 | Repl = GVE->getVariable(); |
5967 | DBuilder.replaceTemporary(N: std::move(FwdDecl), Replacement: cast<llvm::MDNode>(Val: Repl)); |
5968 | } |
5969 | |
5970 | // We keep our own list of retained types, because we need to look |
5971 | // up the final type in the type cache. |
5972 | for (auto &RT : RetainedTypes) |
5973 | if (auto MD = TypeCache[RT]) |
5974 | DBuilder.retainType(T: cast<llvm::DIType>(Val&: MD)); |
5975 | |
5976 | DBuilder.finalize(); |
5977 | } |
5978 | |
5979 | // Don't ignore in case of explicit cast where it is referenced indirectly. |
5980 | void CGDebugInfo::EmitExplicitCastType(QualType Ty) { |
5981 | if (CGM.getCodeGenOpts().hasReducedDebugInfo()) |
5982 | if (auto *DieTy = getOrCreateType(Ty, Unit: TheCU->getFile())) |
5983 | DBuilder.retainType(T: DieTy); |
5984 | } |
5985 | |
5986 | void CGDebugInfo::EmitAndRetainType(QualType Ty) { |
5987 | if (CGM.getCodeGenOpts().hasMaybeUnusedDebugInfo()) |
5988 | if (auto *DieTy = getOrCreateType(Ty, Unit: TheCU->getFile())) |
5989 | DBuilder.retainType(T: DieTy); |
5990 | } |
5991 | |
5992 | llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) { |
5993 | if (LexicalBlockStack.empty()) |
5994 | return llvm::DebugLoc(); |
5995 | |
5996 | llvm::MDNode *Scope = LexicalBlockStack.back(); |
5997 | return llvm::DILocation::get(Context&: CGM.getLLVMContext(), Line: getLineNumber(Loc), |
5998 | Column: getColumnNumber(Loc), Scope); |
5999 | } |
6000 | |
6001 | llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const { |
6002 | // Call site-related attributes are only useful in optimized programs, and |
6003 | // when there's a possibility of debugging backtraces. |
6004 | if (!CGM.getLangOpts().Optimize || |
6005 | DebugKind == llvm::codegenoptions::NoDebugInfo || |
6006 | DebugKind == llvm::codegenoptions::LocTrackingOnly) |
6007 | return llvm::DINode::FlagZero; |
6008 | |
6009 | // Call site-related attributes are available in DWARF v5. Some debuggers, |
6010 | // while not fully DWARF v5-compliant, may accept these attributes as if they |
6011 | // were part of DWARF v4. |
6012 | bool SupportsDWARFv4Ext = |
6013 | CGM.getCodeGenOpts().DwarfVersion == 4 && |
6014 | (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB || |
6015 | CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB); |
6016 | |
6017 | if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5) |
6018 | return llvm::DINode::FlagZero; |
6019 | |
6020 | return llvm::DINode::FlagAllCallsDescribed; |
6021 | } |
6022 | |
6023 | llvm::DIExpression * |
6024 | CGDebugInfo::createConstantValueExpression(const clang::ValueDecl *VD, |
6025 | const APValue &Val) { |
6026 | // FIXME: Add a representation for integer constants wider than 64 bits. |
6027 | if (CGM.getContext().getTypeSize(T: VD->getType()) > 64) |
6028 | return nullptr; |
6029 | |
6030 | if (Val.isFloat()) |
6031 | return DBuilder.createConstantValueExpression( |
6032 | Val: Val.getFloat().bitcastToAPInt().getZExtValue()); |
6033 | |
6034 | if (!Val.isInt()) |
6035 | return nullptr; |
6036 | |
6037 | llvm::APSInt const &ValInt = Val.getInt(); |
6038 | std::optional<uint64_t> ValIntOpt; |
6039 | if (ValInt.isUnsigned()) |
6040 | ValIntOpt = ValInt.tryZExtValue(); |
6041 | else if (auto tmp = ValInt.trySExtValue()) |
6042 | // Transform a signed optional to unsigned optional. When cpp 23 comes, |
6043 | // use std::optional::transform |
6044 | ValIntOpt = static_cast<uint64_t>(*tmp); |
6045 | |
6046 | if (ValIntOpt) |
6047 | return DBuilder.createConstantValueExpression(Val: ValIntOpt.value()); |
6048 | |
6049 | return nullptr; |
6050 | } |
6051 | |