1//===--- CGDebugInfo.h - DebugInfo for LLVM CodeGen -------------*- C++ -*-===//
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 is the source-level debug info generator for llvm translation.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H
14#define LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H
15
16#include "CGBuilder.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExternalASTSource.h"
20#include "clang/AST/PrettyPrinter.h"
21#include "clang/AST/Type.h"
22#include "clang/AST/TypeOrdering.h"
23#include "clang/Basic/ASTSourceDescriptor.h"
24#include "clang/Basic/CodeGenOptions.h"
25#include "clang/Basic/SourceLocation.h"
26#include "llvm/ADT/DenseMap.h"
27#include "llvm/ADT/DenseSet.h"
28#include "llvm/IR/DIBuilder.h"
29#include "llvm/IR/DebugInfo.h"
30#include "llvm/IR/ValueHandle.h"
31#include "llvm/Support/Allocator.h"
32#include <map>
33#include <optional>
34#include <string>
35
36namespace llvm {
37class MDNode;
38}
39
40namespace clang {
41class ClassTemplateSpecializationDecl;
42class GlobalDecl;
43class Module;
44class ModuleMap;
45class ObjCInterfaceDecl;
46class UsingDecl;
47class VarDecl;
48enum class DynamicInitKind : unsigned;
49
50namespace CodeGen {
51class CodeGenModule;
52class CodeGenFunction;
53class CGBlockInfo;
54
55/// This class gathers all debug information during compilation and is
56/// responsible for emitting to llvm globals or pass directly to the
57/// backend.
58class CGDebugInfo {
59 friend class ApplyDebugLocation;
60 friend class SaveAndRestoreLocation;
61 CodeGenModule &CGM;
62 const llvm::codegenoptions::DebugInfoKind DebugKind;
63 bool DebugTypeExtRefs;
64 llvm::DIBuilder DBuilder;
65 llvm::DICompileUnit *TheCU = nullptr;
66 ModuleMap *ClangModuleMap = nullptr;
67 ASTSourceDescriptor PCHDescriptor;
68 SourceLocation CurLoc;
69 llvm::MDNode *CurInlinedAt = nullptr;
70 llvm::DIType *VTablePtrType = nullptr;
71 llvm::DIType *ClassTy = nullptr;
72 llvm::DICompositeType *ObjTy = nullptr;
73 llvm::DIType *SelTy = nullptr;
74#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
75 llvm::DIType *SingletonId = nullptr;
76#include "clang/Basic/OpenCLImageTypes.def"
77 llvm::DIType *OCLSamplerDITy = nullptr;
78 llvm::DIType *OCLEventDITy = nullptr;
79 llvm::DIType *OCLClkEventDITy = nullptr;
80 llvm::DIType *OCLQueueDITy = nullptr;
81 llvm::DIType *OCLNDRangeDITy = nullptr;
82 llvm::DIType *OCLReserveIDDITy = nullptr;
83#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
84 llvm::DIType *Id##Ty = nullptr;
85#include "clang/Basic/OpenCLExtensionTypes.def"
86#define WASM_TYPE(Name, Id, SingletonId) llvm::DIType *SingletonId = nullptr;
87#include "clang/Basic/WebAssemblyReferenceTypes.def"
88#define AMDGPU_TYPE(Name, Id, SingletonId) llvm::DIType *SingletonId = nullptr;
89#include "clang/Basic/AMDGPUTypes.def"
90
91 /// Cache of previously constructed Types.
92 llvm::DenseMap<const void *, llvm::TrackingMDRef> TypeCache;
93
94 /// Cache that maps VLA types to size expressions for that type,
95 /// represented by instantiated Metadata nodes.
96 llvm::SmallDenseMap<QualType, llvm::Metadata *> SizeExprCache;
97
98 /// Callbacks to use when printing names and types.
99 class PrintingCallbacks final : public clang::PrintingCallbacks {
100 const CGDebugInfo &Self;
101
102 public:
103 PrintingCallbacks(const CGDebugInfo &Self) : Self(Self) {}
104 std::string remapPath(StringRef Path) const override {
105 return Self.remapDIPath(Path);
106 }
107 };
108 PrintingCallbacks PrintCB = {*this};
109
110 struct ObjCInterfaceCacheEntry {
111 const ObjCInterfaceType *Type;
112 llvm::DIType *Decl;
113 llvm::DIFile *Unit;
114 ObjCInterfaceCacheEntry(const ObjCInterfaceType *Type, llvm::DIType *Decl,
115 llvm::DIFile *Unit)
116 : Type(Type), Decl(Decl), Unit(Unit) {}
117 };
118
119 /// Cache of previously constructed interfaces which may change.
120 llvm::SmallVector<ObjCInterfaceCacheEntry, 32> ObjCInterfaceCache;
121
122 /// Cache of forward declarations for methods belonging to the interface.
123 /// The extra bit on the DISubprogram specifies whether a method is
124 /// "objc_direct".
125 llvm::DenseMap<const ObjCInterfaceDecl *,
126 std::vector<llvm::PointerIntPair<llvm::DISubprogram *, 1>>>
127 ObjCMethodCache;
128
129 /// Cache of references to clang modules and precompiled headers.
130 llvm::DenseMap<const Module *, llvm::TrackingMDRef> ModuleCache;
131
132 /// List of interfaces we want to keep even if orphaned.
133 std::vector<void *> RetainedTypes;
134
135 /// Cache of forward declared types to RAUW at the end of compilation.
136 std::vector<std::pair<const TagType *, llvm::TrackingMDRef>> ReplaceMap;
137
138 /// Cache of replaceable forward declarations (functions and
139 /// variables) to RAUW at the end of compilation.
140 std::vector<std::pair<const DeclaratorDecl *, llvm::TrackingMDRef>>
141 FwdDeclReplaceMap;
142
143 /// Keep track of our current nested lexical block.
144 std::vector<llvm::TypedTrackingMDRef<llvm::DIScope>> LexicalBlockStack;
145 llvm::DenseMap<const Decl *, llvm::TrackingMDRef> RegionMap;
146 /// Keep track of LexicalBlockStack counter at the beginning of a
147 /// function. This is used to pop unbalanced regions at the end of a
148 /// function.
149 std::vector<unsigned> FnBeginRegionCount;
150
151 /// This is a storage for names that are constructed on demand. For
152 /// example, C++ destructors, C++ operators etc..
153 llvm::BumpPtrAllocator DebugInfoNames;
154 StringRef CWDName;
155
156 llvm::DenseMap<const char *, llvm::TrackingMDRef> DIFileCache;
157 llvm::DenseMap<const FunctionDecl *, llvm::TrackingMDRef> SPCache;
158 /// Cache declarations relevant to DW_TAG_imported_declarations (C++
159 /// using declarations and global alias variables) that aren't covered
160 /// by other more specific caches.
161 llvm::DenseMap<const Decl *, llvm::TrackingMDRef> DeclCache;
162 llvm::DenseMap<const Decl *, llvm::TrackingMDRef> ImportedDeclCache;
163 llvm::DenseMap<const NamespaceDecl *, llvm::TrackingMDRef> NamespaceCache;
164 llvm::DenseMap<const NamespaceAliasDecl *, llvm::TrackingMDRef>
165 NamespaceAliasCache;
166 llvm::DenseMap<const Decl *, llvm::TypedTrackingMDRef<llvm::DIDerivedType>>
167 StaticDataMemberCache;
168
169 using ParamDecl2StmtTy = llvm::DenseMap<const ParmVarDecl *, const Stmt *>;
170 using Param2DILocTy =
171 llvm::DenseMap<const ParmVarDecl *, llvm::DILocalVariable *>;
172
173 /// The key is coroutine real parameters, value is coroutine move parameters.
174 ParamDecl2StmtTy CoroutineParameterMappings;
175 /// The key is coroutine real parameters, value is DIVariable in LLVM IR.
176 Param2DILocTy ParamDbgMappings;
177
178 /// Helper functions for getOrCreateType.
179 /// @{
180 /// Currently the checksum of an interface includes the number of
181 /// ivars and property accessors.
182 llvm::DIType *CreateType(const BuiltinType *Ty);
183 llvm::DIType *CreateType(const ComplexType *Ty);
184 llvm::DIType *CreateType(const BitIntType *Ty);
185 llvm::DIType *CreateQualifiedType(QualType Ty, llvm::DIFile *Fg);
186 llvm::DIType *CreateQualifiedType(const FunctionProtoType *Ty,
187 llvm::DIFile *Fg);
188 llvm::DIType *CreateType(const TypedefType *Ty, llvm::DIFile *Fg);
189 llvm::DIType *CreateType(const TemplateSpecializationType *Ty,
190 llvm::DIFile *Fg);
191 llvm::DIType *CreateType(const ObjCObjectPointerType *Ty, llvm::DIFile *F);
192 llvm::DIType *CreateType(const PointerType *Ty, llvm::DIFile *F);
193 llvm::DIType *CreateType(const BlockPointerType *Ty, llvm::DIFile *F);
194 llvm::DIType *CreateType(const FunctionType *Ty, llvm::DIFile *F);
195 /// Get structure or union type.
196 llvm::DIType *CreateType(const RecordType *Tyg);
197
198 /// Create definition for the specified 'Ty'.
199 ///
200 /// \returns A pair of 'llvm::DIType's. The first is the definition
201 /// of the 'Ty'. The second is the type specified by the preferred_name
202 /// attribute on 'Ty', which can be a nullptr if no such attribute
203 /// exists.
204 std::pair<llvm::DIType *, llvm::DIType *>
205 CreateTypeDefinition(const RecordType *Ty);
206 llvm::DICompositeType *CreateLimitedType(const RecordType *Ty);
207 void CollectContainingType(const CXXRecordDecl *RD,
208 llvm::DICompositeType *CT);
209 /// Get Objective-C interface type.
210 llvm::DIType *CreateType(const ObjCInterfaceType *Ty, llvm::DIFile *F);
211 llvm::DIType *CreateTypeDefinition(const ObjCInterfaceType *Ty,
212 llvm::DIFile *F);
213 /// Get Objective-C object type.
214 llvm::DIType *CreateType(const ObjCObjectType *Ty, llvm::DIFile *F);
215 llvm::DIType *CreateType(const ObjCTypeParamType *Ty, llvm::DIFile *Unit);
216
217 llvm::DIType *CreateType(const VectorType *Ty, llvm::DIFile *F);
218 llvm::DIType *CreateType(const ConstantMatrixType *Ty, llvm::DIFile *F);
219 llvm::DIType *CreateType(const ArrayType *Ty, llvm::DIFile *F);
220 llvm::DIType *CreateType(const LValueReferenceType *Ty, llvm::DIFile *F);
221 llvm::DIType *CreateType(const RValueReferenceType *Ty, llvm::DIFile *Unit);
222 llvm::DIType *CreateType(const MemberPointerType *Ty, llvm::DIFile *F);
223 llvm::DIType *CreateType(const AtomicType *Ty, llvm::DIFile *F);
224 llvm::DIType *CreateType(const PipeType *Ty, llvm::DIFile *F);
225 /// Get enumeration type.
226 llvm::DIType *CreateEnumType(const EnumType *Ty);
227 llvm::DIType *CreateTypeDefinition(const EnumType *Ty);
228 /// Look up the completed type for a self pointer in the TypeCache and
229 /// create a copy of it with the ObjectPointer and Artificial flags
230 /// set. If the type is not cached, a new one is created. This should
231 /// never happen though, since creating a type for the implicit self
232 /// argument implies that we already parsed the interface definition
233 /// and the ivar declarations in the implementation.
234 llvm::DIType *CreateSelfType(const QualType &QualTy, llvm::DIType *Ty);
235 /// @}
236
237 /// Get the type from the cache or return null type if it doesn't
238 /// exist.
239 llvm::DIType *getTypeOrNull(const QualType);
240 /// Return the debug type for a C++ method.
241 /// \arg CXXMethodDecl is of FunctionType. This function type is
242 /// not updated to include implicit \c this pointer. Use this routine
243 /// to get a method type which includes \c this pointer.
244 llvm::DISubroutineType *getOrCreateMethodType(const CXXMethodDecl *Method,
245 llvm::DIFile *F);
246 llvm::DISubroutineType *
247 getOrCreateInstanceMethodType(QualType ThisPtr, const FunctionProtoType *Func,
248 llvm::DIFile *Unit);
249 llvm::DISubroutineType *
250 getOrCreateFunctionType(const Decl *D, QualType FnType, llvm::DIFile *F);
251 /// \return debug info descriptor for vtable.
252 llvm::DIType *getOrCreateVTablePtrType(llvm::DIFile *F);
253
254 /// \return namespace descriptor for the given namespace decl.
255 llvm::DINamespace *getOrCreateNamespace(const NamespaceDecl *N);
256 llvm::DIType *CreatePointerLikeType(llvm::dwarf::Tag Tag, const Type *Ty,
257 QualType PointeeTy, llvm::DIFile *F);
258 llvm::DIType *getOrCreateStructPtrType(StringRef Name, llvm::DIType *&Cache);
259
260 /// A helper function to create a subprogram for a single member
261 /// function GlobalDecl.
262 llvm::DISubprogram *CreateCXXMemberFunction(const CXXMethodDecl *Method,
263 llvm::DIFile *F,
264 llvm::DIType *RecordTy);
265
266 /// A helper function to collect debug info for C++ member
267 /// functions. This is used while creating debug info entry for a
268 /// Record.
269 void CollectCXXMemberFunctions(const CXXRecordDecl *Decl, llvm::DIFile *F,
270 SmallVectorImpl<llvm::Metadata *> &E,
271 llvm::DIType *T);
272
273 /// A helper function to collect debug info for C++ base
274 /// classes. This is used while creating debug info entry for a
275 /// Record.
276 void CollectCXXBases(const CXXRecordDecl *Decl, llvm::DIFile *F,
277 SmallVectorImpl<llvm::Metadata *> &EltTys,
278 llvm::DIType *RecordTy);
279
280 /// Helper function for CollectCXXBases.
281 /// Adds debug info entries for types in Bases that are not in SeenTypes.
282 void CollectCXXBasesAux(
283 const CXXRecordDecl *RD, llvm::DIFile *Unit,
284 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
285 const CXXRecordDecl::base_class_const_range &Bases,
286 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
287 llvm::DINode::DIFlags StartingFlags);
288
289 /// Helper function that returns the llvm::DIType that the
290 /// PreferredNameAttr attribute on \ref RD refers to. If no such
291 /// attribute exists, returns nullptr.
292 llvm::DIType *GetPreferredNameType(const CXXRecordDecl *RD,
293 llvm::DIFile *Unit);
294
295 struct TemplateArgs {
296 const TemplateParameterList *TList;
297 llvm::ArrayRef<TemplateArgument> Args;
298 };
299 /// A helper function to collect template parameters.
300 llvm::DINodeArray CollectTemplateParams(std::optional<TemplateArgs> Args,
301 llvm::DIFile *Unit);
302 /// A helper function to collect debug info for function template
303 /// parameters.
304 llvm::DINodeArray CollectFunctionTemplateParams(const FunctionDecl *FD,
305 llvm::DIFile *Unit);
306
307 /// A helper function to collect debug info for function template
308 /// parameters.
309 llvm::DINodeArray CollectVarTemplateParams(const VarDecl *VD,
310 llvm::DIFile *Unit);
311
312 std::optional<TemplateArgs> GetTemplateArgs(const VarDecl *) const;
313 std::optional<TemplateArgs> GetTemplateArgs(const RecordDecl *) const;
314 std::optional<TemplateArgs> GetTemplateArgs(const FunctionDecl *) const;
315
316 /// A helper function to collect debug info for template
317 /// parameters.
318 llvm::DINodeArray CollectCXXTemplateParams(const RecordDecl *TS,
319 llvm::DIFile *F);
320
321 /// A helper function to collect debug info for btf_decl_tag annotations.
322 llvm::DINodeArray CollectBTFDeclTagAnnotations(const Decl *D);
323
324 llvm::DIType *createFieldType(StringRef name, QualType type,
325 SourceLocation loc, AccessSpecifier AS,
326 uint64_t offsetInBits, uint32_t AlignInBits,
327 llvm::DIFile *tunit, llvm::DIScope *scope,
328 const RecordDecl *RD = nullptr,
329 llvm::DINodeArray Annotations = nullptr);
330
331 llvm::DIType *createFieldType(StringRef name, QualType type,
332 SourceLocation loc, AccessSpecifier AS,
333 uint64_t offsetInBits, llvm::DIFile *tunit,
334 llvm::DIScope *scope,
335 const RecordDecl *RD = nullptr) {
336 return createFieldType(name, type, loc, AS, offsetInBits, AlignInBits: 0, tunit, scope,
337 RD);
338 }
339
340 /// Create new bit field member.
341 llvm::DIDerivedType *createBitFieldType(const FieldDecl *BitFieldDecl,
342 llvm::DIScope *RecordTy,
343 const RecordDecl *RD);
344
345 /// Create an anonnymous zero-size separator for bit-field-decl if needed on
346 /// the target.
347 llvm::DIDerivedType *createBitFieldSeparatorIfNeeded(
348 const FieldDecl *BitFieldDecl, const llvm::DIDerivedType *BitFieldDI,
349 llvm::ArrayRef<llvm::Metadata *> PreviousFieldsDI, const RecordDecl *RD);
350
351 /// A cache that maps names of artificial inlined functions to subprograms.
352 llvm::StringMap<llvm::DISubprogram *> InlinedTrapFuncMap;
353
354 /// A function that returns the subprogram corresponding to the artificial
355 /// inlined function for traps.
356 llvm::DISubprogram *createInlinedTrapSubprogram(StringRef FuncName,
357 llvm::DIFile *FileScope);
358
359 /// Helpers for collecting fields of a record.
360 /// @{
361 void CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
362 SmallVectorImpl<llvm::Metadata *> &E,
363 llvm::DIType *RecordTy);
364 llvm::DIDerivedType *CreateRecordStaticField(const VarDecl *Var,
365 llvm::DIType *RecordTy,
366 const RecordDecl *RD);
367 void CollectRecordNormalField(const FieldDecl *Field, uint64_t OffsetInBits,
368 llvm::DIFile *F,
369 SmallVectorImpl<llvm::Metadata *> &E,
370 llvm::DIType *RecordTy, const RecordDecl *RD);
371 void CollectRecordNestedType(const TypeDecl *RD,
372 SmallVectorImpl<llvm::Metadata *> &E);
373 void CollectRecordFields(const RecordDecl *Decl, llvm::DIFile *F,
374 SmallVectorImpl<llvm::Metadata *> &E,
375 llvm::DICompositeType *RecordTy);
376
377 /// If the C++ class has vtable info then insert appropriate debug
378 /// info entry in EltTys vector.
379 void CollectVTableInfo(const CXXRecordDecl *Decl, llvm::DIFile *F,
380 SmallVectorImpl<llvm::Metadata *> &EltTys);
381 /// @}
382
383 /// Create a new lexical block node and push it on the stack.
384 void CreateLexicalBlock(SourceLocation Loc);
385
386 /// If target-specific LLVM \p AddressSpace directly maps to target-specific
387 /// DWARF address space, appends extended dereferencing mechanism to complex
388 /// expression \p Expr. Otherwise, does nothing.
389 ///
390 /// Extended dereferencing mechanism is has the following format:
391 /// DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
392 void AppendAddressSpaceXDeref(unsigned AddressSpace,
393 SmallVectorImpl<uint64_t> &Expr) const;
394
395 /// A helper function to collect debug info for the default elements of a
396 /// block.
397 ///
398 /// \returns The next available field offset after the default elements.
399 uint64_t collectDefaultElementTypesForBlockPointer(
400 const BlockPointerType *Ty, llvm::DIFile *Unit,
401 llvm::DIDerivedType *DescTy, unsigned LineNo,
402 SmallVectorImpl<llvm::Metadata *> &EltTys);
403
404 /// A helper function to collect debug info for the default fields of a
405 /// block.
406 void collectDefaultFieldsForBlockLiteralDeclare(
407 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
408 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
409 SmallVectorImpl<llvm::Metadata *> &Fields);
410
411public:
412 CGDebugInfo(CodeGenModule &CGM);
413 ~CGDebugInfo();
414
415 void finalize();
416
417 /// Remap a given path with the current debug prefix map
418 std::string remapDIPath(StringRef) const;
419
420 /// Register VLA size expression debug node with the qualified type.
421 void registerVLASizeExpression(QualType Ty, llvm::Metadata *SizeExpr) {
422 SizeExprCache[Ty] = SizeExpr;
423 }
424
425 /// Module debugging: Support for building PCMs.
426 /// @{
427 /// Set the main CU's DwoId field to \p Signature.
428 void setDwoId(uint64_t Signature);
429
430 /// When generating debug information for a clang module or
431 /// precompiled header, this module map will be used to determine
432 /// the module of origin of each Decl.
433 void setModuleMap(ModuleMap &MMap) { ClangModuleMap = &MMap; }
434
435 /// When generating debug information for a clang module or
436 /// precompiled header, this module map will be used to determine
437 /// the module of origin of each Decl.
438 void setPCHDescriptor(ASTSourceDescriptor PCH) { PCHDescriptor = PCH; }
439 /// @}
440
441 /// Update the current source location. If \arg loc is invalid it is
442 /// ignored.
443 void setLocation(SourceLocation Loc);
444
445 /// Return the current source location. This does not necessarily correspond
446 /// to the IRBuilder's current DebugLoc.
447 SourceLocation getLocation() const { return CurLoc; }
448
449 /// Update the current inline scope. All subsequent calls to \p EmitLocation
450 /// will create a location with this inlinedAt field.
451 void setInlinedAt(llvm::MDNode *InlinedAt) { CurInlinedAt = InlinedAt; }
452
453 /// \return the current inline scope.
454 llvm::MDNode *getInlinedAt() const { return CurInlinedAt; }
455
456 // Converts a SourceLocation to a DebugLoc
457 llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Loc);
458
459 /// Emit metadata to indicate a change in line/column information in
460 /// the source file. If the location is invalid, the previous
461 /// location will be reused.
462 void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc);
463
464 QualType getFunctionType(const FunctionDecl *FD, QualType RetTy,
465 const SmallVectorImpl<const VarDecl *> &Args);
466
467 /// Emit a call to llvm.dbg.function.start to indicate
468 /// start of a new function.
469 /// \param Loc The location of the function header.
470 /// \param ScopeLoc The location of the function body.
471 void emitFunctionStart(GlobalDecl GD, SourceLocation Loc,
472 SourceLocation ScopeLoc, QualType FnType,
473 llvm::Function *Fn, bool CurFnIsThunk);
474
475 /// Start a new scope for an inlined function.
476 void EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD);
477 /// End an inlined function scope.
478 void EmitInlineFunctionEnd(CGBuilderTy &Builder);
479
480 /// Emit debug info for a function declaration.
481 /// \p Fn is set only when a declaration for a debug call site gets created.
482 void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
483 QualType FnType, llvm::Function *Fn = nullptr);
484
485 /// Emit debug info for an extern function being called.
486 /// This is needed for call site debug info.
487 void EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
488 QualType CalleeType,
489 const FunctionDecl *CalleeDecl);
490
491 /// Constructs the debug code for exiting a function.
492 void EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn);
493
494 /// Emit metadata to indicate the beginning of a new lexical block
495 /// and push the block onto the stack.
496 void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc);
497
498 /// Emit metadata to indicate the end of a new lexical block and pop
499 /// the current block.
500 void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc);
501
502 /// Emit call to \c llvm.dbg.declare for an automatic variable
503 /// declaration.
504 /// Returns a pointer to the DILocalVariable associated with the
505 /// llvm.dbg.declare, or nullptr otherwise.
506 llvm::DILocalVariable *
507 EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *AI,
508 CGBuilderTy &Builder,
509 const bool UsePointerValue = false);
510
511 /// Emit call to \c llvm.dbg.label for an label.
512 void EmitLabel(const LabelDecl *D, CGBuilderTy &Builder);
513
514 /// Emit call to \c llvm.dbg.declare for an imported variable
515 /// declaration in a block.
516 void EmitDeclareOfBlockDeclRefVariable(
517 const VarDecl *variable, llvm::Value *storage, CGBuilderTy &Builder,
518 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint = nullptr);
519
520 /// Emit call to \c llvm.dbg.declare for an argument variable
521 /// declaration.
522 llvm::DILocalVariable *
523 EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI, unsigned ArgNo,
524 CGBuilderTy &Builder, bool UsePointerValue = false);
525
526 /// Emit call to \c llvm.dbg.declare for the block-literal argument
527 /// to a block invocation function.
528 void EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
529 StringRef Name, unsigned ArgNo,
530 llvm::AllocaInst *LocalAddr,
531 CGBuilderTy &Builder);
532
533 /// Emit information about a global variable.
534 void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
535
536 /// Emit a constant global variable's debug info.
537 void EmitGlobalVariable(const ValueDecl *VD, const APValue &Init);
538
539 /// Emit information about an external variable.
540 void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
541
542 /// Emit a pseudo variable and debug info for an intermediate value if it does
543 /// not correspond to a variable in the source code, so that a profiler can
544 /// track more accurate usage of certain instructions of interest.
545 void EmitPseudoVariable(CGBuilderTy &Builder, llvm::Instruction *Value,
546 QualType Ty);
547
548 /// Emit information about global variable alias.
549 void EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl Decl);
550
551 /// Emit C++ using directive.
552 void EmitUsingDirective(const UsingDirectiveDecl &UD);
553
554 /// Emit the type explicitly casted to.
555 void EmitExplicitCastType(QualType Ty);
556
557 /// Emit the type even if it might not be used.
558 void EmitAndRetainType(QualType Ty);
559
560 /// Emit a shadow decl brought in by a using or using-enum
561 void EmitUsingShadowDecl(const UsingShadowDecl &USD);
562
563 /// Emit C++ using declaration.
564 void EmitUsingDecl(const UsingDecl &UD);
565
566 /// Emit C++ using-enum declaration.
567 void EmitUsingEnumDecl(const UsingEnumDecl &UD);
568
569 /// Emit an @import declaration.
570 void EmitImportDecl(const ImportDecl &ID);
571
572 /// DebugInfo isn't attached to string literals by default. While certain
573 /// aspects of debuginfo aren't useful for string literals (like a name), it's
574 /// nice to be able to symbolize the line and column information. This is
575 /// especially useful for sanitizers, as it allows symbolization of
576 /// heap-buffer-overflows on constant strings.
577 void AddStringLiteralDebugInfo(llvm::GlobalVariable *GV,
578 const StringLiteral *S);
579
580 /// Emit C++ namespace alias.
581 llvm::DIImportedEntity *EmitNamespaceAlias(const NamespaceAliasDecl &NA);
582
583 /// Emit record type's standalone debug info.
584 llvm::DIType *getOrCreateRecordType(QualType Ty, SourceLocation L);
585
586 /// Emit an Objective-C interface type standalone debug info.
587 llvm::DIType *getOrCreateInterfaceType(QualType Ty, SourceLocation Loc);
588
589 /// Emit standalone debug info for a type.
590 llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Loc);
591
592 /// Add heapallocsite metadata for MSAllocator calls.
593 void addHeapAllocSiteMetadata(llvm::CallBase *CallSite, QualType AllocatedTy,
594 SourceLocation Loc);
595
596 void completeType(const EnumDecl *ED);
597 void completeType(const RecordDecl *RD);
598 void completeRequiredType(const RecordDecl *RD);
599 void completeClassData(const RecordDecl *RD);
600 void completeClass(const RecordDecl *RD);
601
602 void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD);
603 void completeUnusedClass(const CXXRecordDecl &D);
604
605 /// Create debug info for a macro defined by a #define directive or a macro
606 /// undefined by a #undef directive.
607 llvm::DIMacro *CreateMacro(llvm::DIMacroFile *Parent, unsigned MType,
608 SourceLocation LineLoc, StringRef Name,
609 StringRef Value);
610
611 /// Create debug info for a file referenced by an #include directive.
612 llvm::DIMacroFile *CreateTempMacroFile(llvm::DIMacroFile *Parent,
613 SourceLocation LineLoc,
614 SourceLocation FileLoc);
615
616 Param2DILocTy &getParamDbgMappings() { return ParamDbgMappings; }
617 ParamDecl2StmtTy &getCoroutineParameterMappings() {
618 return CoroutineParameterMappings;
619 }
620
621 /// Create a debug location from `TrapLocation` that adds an artificial inline
622 /// frame where the frame name is
623 ///
624 /// * `<Prefix>:<Category>:<FailureMsg>`
625 ///
626 /// `<Prefix>` is "__clang_trap_msg".
627 ///
628 /// This is used to store failure reasons for traps.
629 llvm::DILocation *CreateTrapFailureMessageFor(llvm::DebugLoc TrapLocation,
630 StringRef Category,
631 StringRef FailureMsg);
632
633private:
634 /// Emit call to llvm.dbg.declare for a variable declaration.
635 /// Returns a pointer to the DILocalVariable associated with the
636 /// llvm.dbg.declare, or nullptr otherwise.
637 llvm::DILocalVariable *EmitDeclare(const VarDecl *decl, llvm::Value *AI,
638 std::optional<unsigned> ArgNo,
639 CGBuilderTy &Builder,
640 const bool UsePointerValue = false);
641
642 /// Emit call to llvm.dbg.declare for a binding declaration.
643 /// Returns a pointer to the DILocalVariable associated with the
644 /// llvm.dbg.declare, or nullptr otherwise.
645 llvm::DILocalVariable *EmitDeclare(const BindingDecl *decl, llvm::Value *AI,
646 std::optional<unsigned> ArgNo,
647 CGBuilderTy &Builder,
648 const bool UsePointerValue = false);
649
650 struct BlockByRefType {
651 /// The wrapper struct used inside the __block_literal struct.
652 llvm::DIType *BlockByRefWrapper;
653 /// The type as it appears in the source code.
654 llvm::DIType *WrappedType;
655 };
656
657 bool HasReconstitutableArgs(ArrayRef<TemplateArgument> Args) const;
658 std::string GetName(const Decl *, bool Qualified = false) const;
659
660 /// Build up structure info for the byref. See \a BuildByRefType.
661 BlockByRefType EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
662 uint64_t *OffSet);
663
664 /// Get context info for the DeclContext of \p Decl.
665 llvm::DIScope *getDeclContextDescriptor(const Decl *D);
666 /// Get context info for a given DeclContext \p Decl.
667 llvm::DIScope *getContextDescriptor(const Decl *Context,
668 llvm::DIScope *Default);
669
670 llvm::DIScope *getCurrentContextDescriptor(const Decl *Decl);
671
672 /// Create a forward decl for a RecordType in a given context.
673 llvm::DICompositeType *getOrCreateRecordFwdDecl(const RecordType *,
674 llvm::DIScope *);
675
676 /// Return current directory name.
677 StringRef getCurrentDirname();
678
679 /// Create new compile unit.
680 void CreateCompileUnit();
681
682 /// Compute the file checksum debug info for input file ID.
683 std::optional<llvm::DIFile::ChecksumKind>
684 computeChecksum(FileID FID, SmallString<64> &Checksum) const;
685
686 /// Get the source of the given file ID.
687 std::optional<StringRef> getSource(const SourceManager &SM, FileID FID);
688
689 /// Convenience function to get the file debug info descriptor for the input
690 /// location.
691 llvm::DIFile *getOrCreateFile(SourceLocation Loc);
692
693 /// Create a file debug info descriptor for a source file.
694 llvm::DIFile *
695 createFile(StringRef FileName,
696 std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
697 std::optional<StringRef> Source);
698
699 /// Get the type from the cache or create a new type if necessary.
700 llvm::DIType *getOrCreateType(QualType Ty, llvm::DIFile *Fg);
701
702 /// Get a reference to a clang module. If \p CreateSkeletonCU is true,
703 /// this also creates a split dwarf skeleton compile unit.
704 llvm::DIModule *getOrCreateModuleRef(ASTSourceDescriptor Mod,
705 bool CreateSkeletonCU);
706
707 /// DebugTypeExtRefs: If \p D originated in a clang module, return it.
708 llvm::DIModule *getParentModuleOrNull(const Decl *D);
709
710 /// Get the type from the cache or create a new partial type if
711 /// necessary.
712 llvm::DICompositeType *getOrCreateLimitedType(const RecordType *Ty);
713
714 /// Create type metadata for a source language type.
715 llvm::DIType *CreateTypeNode(QualType Ty, llvm::DIFile *Fg);
716
717 /// Create new member and increase Offset by FType's size.
718 llvm::DIType *CreateMemberType(llvm::DIFile *Unit, QualType FType,
719 StringRef Name, uint64_t *Offset);
720
721 /// Retrieve the DIDescriptor, if any, for the canonical form of this
722 /// declaration.
723 llvm::DINode *getDeclarationOrDefinition(const Decl *D);
724
725 /// \return debug info descriptor to describe method
726 /// declaration for the given method definition.
727 llvm::DISubprogram *getFunctionDeclaration(const Decl *D);
728
729 /// \return debug info descriptor to the describe method declaration
730 /// for the given method definition.
731 /// \param FnType For Objective-C methods, their type.
732 /// \param LineNo The declaration's line number.
733 /// \param Flags The DIFlags for the method declaration.
734 /// \param SPFlags The subprogram-spcific flags for the method declaration.
735 llvm::DISubprogram *
736 getObjCMethodDeclaration(const Decl *D, llvm::DISubroutineType *FnType,
737 unsigned LineNo, llvm::DINode::DIFlags Flags,
738 llvm::DISubprogram::DISPFlags SPFlags);
739
740 /// \return debug info descriptor to describe in-class static data
741 /// member declaration for the given out-of-class definition. If D
742 /// is an out-of-class definition of a static data member of a
743 /// class, find its corresponding in-class declaration.
744 llvm::DIDerivedType *
745 getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D);
746
747 /// Helper that either creates a forward declaration or a stub.
748 llvm::DISubprogram *getFunctionFwdDeclOrStub(GlobalDecl GD, bool Stub);
749
750 /// Create a subprogram describing the forward declaration
751 /// represented in the given FunctionDecl wrapped in a GlobalDecl.
752 llvm::DISubprogram *getFunctionForwardDeclaration(GlobalDecl GD);
753
754 /// Create a DISubprogram describing the function
755 /// represented in the given FunctionDecl wrapped in a GlobalDecl.
756 llvm::DISubprogram *getFunctionStub(GlobalDecl GD);
757
758 /// Create a global variable describing the forward declaration
759 /// represented in the given VarDecl.
760 llvm::DIGlobalVariable *
761 getGlobalVariableForwardDeclaration(const VarDecl *VD);
762
763 /// Return a global variable that represents one of the collection of global
764 /// variables created for an anonmyous union.
765 ///
766 /// Recursively collect all of the member fields of a global
767 /// anonymous decl and create static variables for them. The first
768 /// time this is called it needs to be on a union and then from
769 /// there we can have additional unnamed fields.
770 llvm::DIGlobalVariableExpression *
771 CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile *Unit,
772 unsigned LineNo, StringRef LinkageName,
773 llvm::GlobalVariable *Var, llvm::DIScope *DContext);
774
775
776 /// Return flags which enable debug info emission for call sites, provided
777 /// that it is supported and enabled.
778 llvm::DINode::DIFlags getCallSiteRelatedAttrs() const;
779
780 /// Get the printing policy for producing names for debug info.
781 PrintingPolicy getPrintingPolicy() const;
782
783 /// Get function name for the given FunctionDecl. If the name is
784 /// constructed on demand (e.g., C++ destructor) then the name is
785 /// stored on the side.
786 StringRef getFunctionName(const FunctionDecl *FD);
787
788 /// Returns the unmangled name of an Objective-C method.
789 /// This is the display name for the debugging info.
790 StringRef getObjCMethodName(const ObjCMethodDecl *FD);
791
792 /// Return selector name. This is used for debugging
793 /// info.
794 StringRef getSelectorName(Selector S);
795
796 /// Get class name including template argument list.
797 StringRef getClassName(const RecordDecl *RD);
798
799 /// Get the vtable name for the given class.
800 StringRef getVTableName(const CXXRecordDecl *Decl);
801
802 /// Get the name to use in the debug info for a dynamic initializer or atexit
803 /// stub function.
804 StringRef getDynamicInitializerName(const VarDecl *VD,
805 DynamicInitKind StubKind,
806 llvm::Function *InitFn);
807
808 /// Get line number for the location. If location is invalid
809 /// then use current location.
810 unsigned getLineNumber(SourceLocation Loc);
811
812 /// Get column number for the location. If location is
813 /// invalid then use current location.
814 /// \param Force Assume DebugColumnInfo option is true.
815 unsigned getColumnNumber(SourceLocation Loc, bool Force = false);
816
817 /// Collect various properties of a FunctionDecl.
818 /// \param GD A GlobalDecl whose getDecl() must return a FunctionDecl.
819 void collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
820 StringRef &Name, StringRef &LinkageName,
821 llvm::DIScope *&FDContext,
822 llvm::DINodeArray &TParamsArray,
823 llvm::DINode::DIFlags &Flags);
824
825 /// Collect various properties of a VarDecl.
826 void collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
827 unsigned &LineNo, QualType &T, StringRef &Name,
828 StringRef &LinkageName,
829 llvm::MDTuple *&TemplateParameters,
830 llvm::DIScope *&VDContext);
831
832 /// Create a DIExpression representing the constant corresponding
833 /// to the specified 'Val'. Returns nullptr on failure.
834 llvm::DIExpression *createConstantValueExpression(const clang::ValueDecl *VD,
835 const APValue &Val);
836
837 /// Allocate a copy of \p A using the DebugInfoNames allocator
838 /// and return a reference to it. If multiple arguments are given the strings
839 /// are concatenated.
840 StringRef internString(StringRef A, StringRef B = StringRef()) {
841 char *Data = DebugInfoNames.Allocate<char>(Num: A.size() + B.size());
842 if (!A.empty())
843 std::memcpy(dest: Data, src: A.data(), n: A.size());
844 if (!B.empty())
845 std::memcpy(dest: Data + A.size(), src: B.data(), n: B.size());
846 return StringRef(Data, A.size() + B.size());
847 }
848};
849
850/// A scoped helper to set the current debug location to the specified
851/// location or preferred location of the specified Expr.
852class ApplyDebugLocation {
853private:
854 void init(SourceLocation TemporaryLocation, bool DefaultToEmpty = false);
855 ApplyDebugLocation(CodeGenFunction &CGF, bool DefaultToEmpty,
856 SourceLocation TemporaryLocation);
857
858 llvm::DebugLoc OriginalLocation;
859 CodeGenFunction *CGF;
860
861public:
862 /// Set the location to the (valid) TemporaryLocation.
863 ApplyDebugLocation(CodeGenFunction &CGF, SourceLocation TemporaryLocation);
864 ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E);
865 ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc);
866 ApplyDebugLocation(ApplyDebugLocation &&Other) : CGF(Other.CGF) {
867 Other.CGF = nullptr;
868 }
869
870 // Define copy assignment operator.
871 ApplyDebugLocation &operator=(ApplyDebugLocation &&Other) {
872 if (this != &Other) {
873 CGF = Other.CGF;
874 Other.CGF = nullptr;
875 }
876 return *this;
877 }
878
879 ~ApplyDebugLocation();
880
881 /// Apply TemporaryLocation if it is valid. Otherwise switch
882 /// to an artificial debug location that has a valid scope, but no
883 /// line information.
884 ///
885 /// Artificial locations are useful when emitting compiler-generated
886 /// helper functions that have no source location associated with
887 /// them. The DWARF specification allows the compiler to use the
888 /// special line number 0 to indicate code that can not be
889 /// attributed to any source location. Note that passing an empty
890 /// SourceLocation to CGDebugInfo::setLocation() will result in the
891 /// last valid location being reused.
892 static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF) {
893 return ApplyDebugLocation(CGF, false, SourceLocation());
894 }
895 /// Apply TemporaryLocation if it is valid. Otherwise switch
896 /// to an artificial debug location that has a valid scope, but no
897 /// line information.
898 static ApplyDebugLocation
899 CreateDefaultArtificial(CodeGenFunction &CGF,
900 SourceLocation TemporaryLocation) {
901 return ApplyDebugLocation(CGF, false, TemporaryLocation);
902 }
903
904 /// Set the IRBuilder to not attach debug locations. Note that
905 /// passing an empty SourceLocation to \a CGDebugInfo::setLocation()
906 /// will result in the last valid location being reused. Note that
907 /// all instructions that do not have a location at the beginning of
908 /// a function are counted towards to function prologue.
909 static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF) {
910 return ApplyDebugLocation(CGF, true, SourceLocation());
911 }
912};
913
914/// A scoped helper to set the current debug location to an inlined location.
915class ApplyInlineDebugLocation {
916 SourceLocation SavedLocation;
917 CodeGenFunction *CGF;
918
919public:
920 /// Set up the CodeGenFunction's DebugInfo to produce inline locations for the
921 /// function \p InlinedFn. The current debug location becomes the inlined call
922 /// site of the inlined function.
923 ApplyInlineDebugLocation(CodeGenFunction &CGF, GlobalDecl InlinedFn);
924 /// Restore everything back to the original state.
925 ~ApplyInlineDebugLocation();
926};
927
928} // namespace CodeGen
929} // namespace clang
930
931#endif // LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H
932