Coverage Report

Created: 2023-11-11 10:31

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