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