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

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

source code of clang/lib/CodeGen/CGDebugInfo.h