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