brintos

brintos / llvm-project-archived public Read only

0
0
Text · 43.3 KiB · 2378bdd Raw
1005 lines · c
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-exception6//7//===----------------------------------------------------------------------===//8//9// This is the source-level debug info generator for llvm translation.10//11//===----------------------------------------------------------------------===//12 13#ifndef LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H14#define LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H15 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 is57/// responsible for emitting to llvm globals or pass directly to the58/// 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 is131  /// "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 and146  /// 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 a154  /// function. This is used to pop unbalanced regions at the end of a155  /// function.156  std::vector<unsigned> FnBeginRegionCount;157 158  /// This is a storage for names that are constructed on demand. For159  /// example, C++ destructors, C++ operators etc..160  llvm::BumpPtrAllocator DebugInfoNames;161 162  llvm::DenseMap<const char *, llvm::TrackingMDRef> DIFileCache;163  llvm::DenseMap<const FunctionDecl *, llvm::TrackingMDRef> SPCache;164  /// Cache declarations relevant to DW_TAG_imported_declarations (C++165  /// using declarations and global alias variables) that aren't covered166  /// by other more specific caches.167  llvm::DenseMap<const Decl *, llvm::TrackingMDRef> DeclCache;168  llvm::DenseMap<const Decl *, llvm::TrackingMDRef> ImportedDeclCache;169  llvm::DenseMap<const NamespaceDecl *, llvm::TrackingMDRef> NamespaceCache;170  llvm::DenseMap<const NamespaceAliasDecl *, llvm::TrackingMDRef>171      NamespaceAliasCache;172  llvm::DenseMap<const Decl *, llvm::TypedTrackingMDRef<llvm::DIDerivedType>>173      StaticDataMemberCache;174 175  using ParamDecl2StmtTy = llvm::DenseMap<const ParmVarDecl *, const Stmt *>;176  using Param2DILocTy =177      llvm::DenseMap<const ParmVarDecl *, llvm::DILocalVariable *>;178 179  /// The key is coroutine real parameters, value is coroutine move parameters.180  ParamDecl2StmtTy CoroutineParameterMappings;181  /// The key is coroutine real parameters, value is DIVariable in LLVM IR.182  Param2DILocTy ParamDbgMappings;183 184  /// Key Instructions bookkeeping.185  /// Source atoms are identified by a {AtomGroup, InlinedAt} pair, meaning186  /// AtomGroup numbers can be repeated across different functions.187  struct {188    uint64_t NextAtom = 1;189    uint64_t HighestEmittedAtom = 0;190    uint64_t CurrentAtom = 0;191  } KeyInstructionsInfo;192 193private:194  /// Helper functions for getOrCreateType.195  /// @{196  /// Currently the checksum of an interface includes the number of197  /// ivars and property accessors.198  llvm::DIType *CreateType(const BuiltinType *Ty);199  llvm::DIType *CreateType(const ComplexType *Ty);200  llvm::DIType *CreateType(const BitIntType *Ty);201  llvm::DIType *CreateQualifiedType(QualType Ty, llvm::DIFile *Fg);202  llvm::DIType *CreateQualifiedType(const FunctionProtoType *Ty,203                                    llvm::DIFile *Fg);204  llvm::DIType *CreateType(const TypedefType *Ty, llvm::DIFile *Fg);205  llvm::DIType *CreateType(const TemplateSpecializationType *Ty,206                           llvm::DIFile *Fg);207  llvm::DIType *CreateType(const ObjCObjectPointerType *Ty, llvm::DIFile *F);208  llvm::DIType *CreateType(const PointerType *Ty, llvm::DIFile *F);209  llvm::DIType *CreateType(const BlockPointerType *Ty, llvm::DIFile *F);210  llvm::DIType *CreateType(const FunctionType *Ty, llvm::DIFile *F);211  llvm::DIType *CreateType(const HLSLAttributedResourceType *Ty,212                           llvm::DIFile *F);213  llvm::DIType *CreateType(const HLSLInlineSpirvType *Ty, llvm::DIFile *F);214  /// Get structure or union type.215  llvm::DIType *CreateType(const RecordType *Tyg);216 217  /// Create definition for the specified 'Ty'.218  ///219  /// \returns A pair of 'llvm::DIType's. The first is the definition220  /// of the 'Ty'. The second is the type specified by the preferred_name221  /// attribute on 'Ty', which can be a nullptr if no such attribute222  /// exists.223  std::pair<llvm::DIType *, llvm::DIType *>224  CreateTypeDefinition(const RecordType *Ty);225  llvm::DICompositeType *CreateLimitedType(const RecordType *Ty);226  void CollectContainingType(const CXXRecordDecl *RD,227                             llvm::DICompositeType *CT);228  /// Get Objective-C interface type.229  llvm::DIType *CreateType(const ObjCInterfaceType *Ty, llvm::DIFile *F);230  llvm::DIType *CreateTypeDefinition(const ObjCInterfaceType *Ty,231                                     llvm::DIFile *F);232  /// Get Objective-C object type.233  llvm::DIType *CreateType(const ObjCObjectType *Ty, llvm::DIFile *F);234  llvm::DIType *CreateType(const ObjCTypeParamType *Ty, llvm::DIFile *Unit);235 236  llvm::DIType *CreateType(const VectorType *Ty, llvm::DIFile *F);237  llvm::DIType *CreateType(const ConstantMatrixType *Ty, llvm::DIFile *F);238  llvm::DIType *CreateType(const ArrayType *Ty, llvm::DIFile *F);239  llvm::DIType *CreateType(const LValueReferenceType *Ty, llvm::DIFile *F);240  llvm::DIType *CreateType(const RValueReferenceType *Ty, llvm::DIFile *Unit);241  llvm::DIType *CreateType(const MemberPointerType *Ty, llvm::DIFile *F);242  llvm::DIType *CreateType(const AtomicType *Ty, llvm::DIFile *F);243  llvm::DIType *CreateType(const PipeType *Ty, llvm::DIFile *F);244  /// Get enumeration type.245  llvm::DIType *CreateEnumType(const EnumType *Ty);246  llvm::DIType *CreateTypeDefinition(const EnumType *Ty);247  /// Look up the completed type for a self pointer in the TypeCache and248  /// create a copy of it with the ObjectPointer and Artificial flags249  /// set. If the type is not cached, a new one is created. This should250  /// never happen though, since creating a type for the implicit self251  /// argument implies that we already parsed the interface definition252  /// and the ivar declarations in the implementation.253  llvm::DIType *CreateSelfType(const QualType &QualTy, llvm::DIType *Ty);254  /// @}255 256  /// Get the type from the cache or return null type if it doesn't257  /// exist.258  llvm::DIType *getTypeOrNull(const QualType);259  /// Return the debug type for a C++ method.260  /// \arg CXXMethodDecl is of FunctionType. This function type is261  /// not updated to include implicit \c this pointer. Use this routine262  /// to get a method type which includes \c this pointer.263  llvm::DISubroutineType *getOrCreateMethodType(const CXXMethodDecl *Method,264                                                llvm::DIFile *F);265 266  llvm::DISubroutineType *267  getOrCreateMethodTypeForDestructor(const CXXMethodDecl *Method,268                                     llvm::DIFile *F, QualType FNType);269 270  llvm::DISubroutineType *271  getOrCreateInstanceMethodType(QualType ThisPtr, const FunctionProtoType *Func,272                                llvm::DIFile *Unit, bool SkipFirst = false);273  llvm::DISubroutineType *274  getOrCreateFunctionType(const Decl *D, QualType FnType, llvm::DIFile *F);275  /// \return debug info descriptor for vtable.276  llvm::DIType *getOrCreateVTablePtrType(llvm::DIFile *F);277 278  /// \return namespace descriptor for the given namespace decl.279  llvm::DINamespace *getOrCreateNamespace(const NamespaceDecl *N);280  llvm::DIType *CreatePointerLikeType(llvm::dwarf::Tag Tag, const Type *Ty,281                                      QualType PointeeTy, llvm::DIFile *F);282  llvm::DIType *getOrCreateStructPtrType(StringRef Name, llvm::DIType *&Cache);283 284  /// A helper function to create a subprogram for a single member285  /// function GlobalDecl.286  llvm::DISubprogram *CreateCXXMemberFunction(const CXXMethodDecl *Method,287                                              llvm::DIFile *F,288                                              llvm::DIType *RecordTy);289 290  /// A helper function to collect debug info for C++ member291  /// functions. This is used while creating debug info entry for a292  /// Record.293  void CollectCXXMemberFunctions(const CXXRecordDecl *Decl, llvm::DIFile *F,294                                 SmallVectorImpl<llvm::Metadata *> &E,295                                 llvm::DIType *T);296 297  /// A helper function to collect debug info for C++ base298  /// classes. This is used while creating debug info entry for a299  /// Record.300  void CollectCXXBases(const CXXRecordDecl *Decl, llvm::DIFile *F,301                       SmallVectorImpl<llvm::Metadata *> &EltTys,302                       llvm::DIType *RecordTy);303 304  /// Helper function for CollectCXXBases.305  /// Adds debug info entries for types in Bases that are not in SeenTypes.306  void CollectCXXBasesAux(307      const CXXRecordDecl *RD, llvm::DIFile *Unit,308      SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,309      const CXXRecordDecl::base_class_const_range &Bases,310      llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,311      llvm::DINode::DIFlags StartingFlags);312 313  /// Helper function that returns the llvm::DIType that the314  /// PreferredNameAttr attribute on \ref RD refers to. If no such315  /// attribute exists, returns nullptr.316  llvm::DIType *GetPreferredNameType(const CXXRecordDecl *RD,317                                     llvm::DIFile *Unit);318 319  struct TemplateArgs {320    const TemplateParameterList *TList;321    llvm::ArrayRef<TemplateArgument> Args;322  };323  /// A helper function to collect template parameters.324  llvm::DINodeArray CollectTemplateParams(std::optional<TemplateArgs> Args,325                                          llvm::DIFile *Unit);326  /// A helper function to collect debug info for function template327  /// parameters.328  llvm::DINodeArray CollectFunctionTemplateParams(const FunctionDecl *FD,329                                                  llvm::DIFile *Unit);330 331  /// A helper function to collect debug info for function template332  /// parameters.333  llvm::DINodeArray CollectVarTemplateParams(const VarDecl *VD,334                                             llvm::DIFile *Unit);335 336  std::optional<TemplateArgs> GetTemplateArgs(const VarDecl *) const;337  std::optional<TemplateArgs> GetTemplateArgs(const RecordDecl *) const;338  std::optional<TemplateArgs> GetTemplateArgs(const FunctionDecl *) const;339 340  /// A helper function to collect debug info for template341  /// parameters.342  llvm::DINodeArray CollectCXXTemplateParams(const RecordDecl *TS,343                                             llvm::DIFile *F);344 345  /// A helper function to collect debug info for btf_decl_tag annotations.346  llvm::DINodeArray CollectBTFDeclTagAnnotations(const Decl *D);347 348  llvm::DIType *createFieldType(StringRef name, QualType type,349                                SourceLocation loc, AccessSpecifier AS,350                                uint64_t offsetInBits, uint32_t AlignInBits,351                                llvm::DIFile *tunit, llvm::DIScope *scope,352                                const RecordDecl *RD = nullptr,353                                llvm::DINodeArray Annotations = nullptr);354 355  llvm::DIType *createFieldType(StringRef name, QualType type,356                                SourceLocation loc, AccessSpecifier AS,357                                uint64_t offsetInBits, llvm::DIFile *tunit,358                                llvm::DIScope *scope,359                                const RecordDecl *RD = nullptr) {360    return createFieldType(name, type, loc, AS, offsetInBits, 0, tunit, scope,361                           RD);362  }363 364  /// Create new bit field member.365  llvm::DIDerivedType *createBitFieldType(const FieldDecl *BitFieldDecl,366                                          llvm::DIScope *RecordTy,367                                          const RecordDecl *RD);368 369  /// Create an anonnymous zero-size separator for bit-field-decl if needed on370  /// the target.371  llvm::DIDerivedType *createBitFieldSeparatorIfNeeded(372      const FieldDecl *BitFieldDecl, const llvm::DIDerivedType *BitFieldDI,373      llvm::ArrayRef<llvm::Metadata *> PreviousFieldsDI, const RecordDecl *RD);374 375  /// A cache that maps names of artificial inlined functions to subprograms.376  llvm::StringMap<llvm::DISubprogram *> InlinedSubprogramMap;377 378  /// A function that returns the subprogram corresponding to the artificial379  /// inlined function for traps.380  llvm::DISubprogram *createInlinedSubprogram(StringRef FuncName,381                                              llvm::DIFile *FileScope);382 383  /// Helpers for collecting fields of a record.384  /// @{385  void CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,386                                 SmallVectorImpl<llvm::Metadata *> &E,387                                 llvm::DIType *RecordTy);388  llvm::DIDerivedType *CreateRecordStaticField(const VarDecl *Var,389                                               llvm::DIType *RecordTy,390                                               const RecordDecl *RD);391  void CollectRecordNormalField(const FieldDecl *Field, uint64_t OffsetInBits,392                                llvm::DIFile *F,393                                SmallVectorImpl<llvm::Metadata *> &E,394                                llvm::DIType *RecordTy, const RecordDecl *RD);395  void CollectRecordNestedType(const TypeDecl *RD,396                               SmallVectorImpl<llvm::Metadata *> &E);397  void CollectRecordFields(const RecordDecl *Decl, llvm::DIFile *F,398                           SmallVectorImpl<llvm::Metadata *> &E,399                           llvm::DICompositeType *RecordTy);400  llvm::StringRef GetLambdaCaptureName(const LambdaCapture &Capture);401 402  /// If the C++ class has vtable info then insert appropriate debug403  /// info entry in EltTys vector.404  void CollectVTableInfo(const CXXRecordDecl *Decl, llvm::DIFile *F,405                         SmallVectorImpl<llvm::Metadata *> &EltTys);406  /// @}407 408  /// Create a new lexical block node and push it on the stack.409  void CreateLexicalBlock(SourceLocation Loc);410 411  /// If target-specific LLVM \p AddressSpace directly maps to target-specific412  /// DWARF address space, appends extended dereferencing mechanism to complex413  /// expression \p Expr. Otherwise, does nothing.414  ///415  /// Extended dereferencing mechanism is has the following format:416  ///     DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef417  void AppendAddressSpaceXDeref(unsigned AddressSpace,418                                SmallVectorImpl<uint64_t> &Expr) const;419 420  /// A helper function to collect debug info for the default elements of a421  /// block.422  ///423  /// \returns The next available field offset after the default elements.424  uint64_t collectDefaultElementTypesForBlockPointer(425      const BlockPointerType *Ty, llvm::DIFile *Unit,426      llvm::DIDerivedType *DescTy, unsigned LineNo,427      SmallVectorImpl<llvm::Metadata *> &EltTys);428 429  /// A helper function to collect debug info for the default fields of a430  /// block.431  void collectDefaultFieldsForBlockLiteralDeclare(432      const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,433      const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,434      SmallVectorImpl<llvm::Metadata *> &Fields);435 436public:437  CGDebugInfo(CodeGenModule &CGM);438  ~CGDebugInfo();439 440  void finalize();441 442  /// Remap a given path with the current debug prefix map443  std::string remapDIPath(StringRef) const;444 445  /// Register VLA size expression debug node with the qualified type.446  void registerVLASizeExpression(QualType Ty, llvm::Metadata *SizeExpr) {447    SizeExprCache[Ty] = SizeExpr;448  }449 450  /// Module debugging: Support for building PCMs.451  /// @{452  /// Set the main CU's DwoId field to \p Signature.453  void setDwoId(uint64_t Signature);454 455  /// When generating debug information for a clang module or456  /// precompiled header, this module map will be used to determine457  /// the module of origin of each Decl.458  void setModuleMap(ModuleMap &MMap) { ClangModuleMap = &MMap; }459 460  /// When generating debug information for a clang module or461  /// precompiled header, this module map will be used to determine462  /// the module of origin of each Decl.463  void setPCHDescriptor(ASTSourceDescriptor PCH) { PCHDescriptor = PCH; }464  /// @}465 466  /// Update the current source location. If \arg loc is invalid it is467  /// ignored.468  void setLocation(SourceLocation Loc);469 470  /// Return the current source location. This does not necessarily correspond471  /// to the IRBuilder's current DebugLoc.472  SourceLocation getLocation() const { return CurLoc; }473 474  /// Update the current inline scope. All subsequent calls to \p EmitLocation475  /// will create a location with this inlinedAt field.476  void setInlinedAt(llvm::MDNode *InlinedAt) { CurInlinedAt = InlinedAt; }477 478  /// \return the current inline scope.479  llvm::MDNode *getInlinedAt() const { return CurInlinedAt; }480 481  // Converts a SourceLocation to a DebugLoc482  llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Loc);483 484  /// Emit metadata to indicate a change in line/column information in485  /// the source file. If the location is invalid, the previous486  /// location will be reused.487  void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc);488 489  QualType getFunctionType(const FunctionDecl *FD, QualType RetTy,490                           const SmallVectorImpl<const VarDecl *> &Args);491 492  /// Emit a call to llvm.dbg.function.start to indicate493  /// start of a new function.494  /// \param Loc       The location of the function header.495  /// \param ScopeLoc  The location of the function body.496  void emitFunctionStart(GlobalDecl GD, SourceLocation Loc,497                         SourceLocation ScopeLoc, QualType FnType,498                         llvm::Function *Fn, bool CurFnIsThunk);499 500  /// Start a new scope for an inlined function.501  void EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD);502  /// End an inlined function scope.503  void EmitInlineFunctionEnd(CGBuilderTy &Builder);504 505  /// Emit debug info for a function declaration.506  /// \p Fn is set only when a declaration for a debug call site gets created.507  void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,508                        QualType FnType, llvm::Function *Fn = nullptr);509 510  /// Emit debug info for an extern function being called.511  /// This is needed for call site debug info.512  void EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,513                               QualType CalleeType,514                               GlobalDecl CalleeGlobalDecl);515 516  /// Constructs the debug code for exiting a function.517  void EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn);518 519  /// Emit metadata to indicate the beginning of a new lexical block520  /// and push the block onto the stack.521  void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc);522 523  /// Emit metadata to indicate the end of a new lexical block and pop524  /// the current block.525  void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc);526 527  /// Emit call to \c llvm.dbg.declare for an automatic variable528  /// declaration.529  /// Returns a pointer to the DILocalVariable associated with the530  /// llvm.dbg.declare, or nullptr otherwise.531  llvm::DILocalVariable *532  EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *AI,533                            CGBuilderTy &Builder,534                            const bool UsePointerValue = false);535 536  /// Emit call to \c llvm.dbg.label for an label.537  void EmitLabel(const LabelDecl *D, CGBuilderTy &Builder);538 539  /// Emit call to \c llvm.dbg.declare for an imported variable540  /// declaration in a block.541  void EmitDeclareOfBlockDeclRefVariable(542      const VarDecl *variable, llvm::Value *storage, CGBuilderTy &Builder,543      const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint = nullptr);544 545  /// Emit call to \c llvm.dbg.declare for an argument variable546  /// declaration.547  llvm::DILocalVariable *548  EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI, unsigned ArgNo,549                           CGBuilderTy &Builder, bool UsePointerValue = false);550 551  /// Emit call to \c llvm.dbg.declare for the block-literal argument552  /// to a block invocation function.553  void EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,554                                            StringRef Name, unsigned ArgNo,555                                            llvm::AllocaInst *LocalAddr,556                                            CGBuilderTy &Builder);557 558  /// Emit information about a global variable.559  void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);560 561  /// Emit a constant global variable's debug info.562  void EmitGlobalVariable(const ValueDecl *VD, const APValue &Init);563 564  /// Emit information about an external variable.565  void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);566 567  /// Emit a pseudo variable and debug info for an intermediate value if it does568  /// not correspond to a variable in the source code, so that a profiler can569  /// track more accurate usage of certain instructions of interest.570  void EmitPseudoVariable(CGBuilderTy &Builder, llvm::Instruction *Value,571                          QualType Ty);572 573  /// Emit information about global variable alias.574  void EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl Decl);575 576  /// Emit C++ using directive.577  void EmitUsingDirective(const UsingDirectiveDecl &UD);578 579  /// Emit the type explicitly casted to.580  void EmitExplicitCastType(QualType Ty);581 582  /// Emit the type even if it might not be used.583  void EmitAndRetainType(QualType Ty);584 585  /// Emit a shadow decl brought in by a using or using-enum586  void EmitUsingShadowDecl(const UsingShadowDecl &USD);587 588  /// Emit C++ using declaration.589  void EmitUsingDecl(const UsingDecl &UD);590 591  /// Emit C++ using-enum declaration.592  void EmitUsingEnumDecl(const UsingEnumDecl &UD);593 594  /// Emit an @import declaration.595  void EmitImportDecl(const ImportDecl &ID);596 597  /// DebugInfo isn't attached to string literals by default. While certain598  /// aspects of debuginfo aren't useful for string literals (like a name), it's599  /// nice to be able to symbolize the line and column information. This is600  /// especially useful for sanitizers, as it allows symbolization of601  /// heap-buffer-overflows on constant strings.602  void AddStringLiteralDebugInfo(llvm::GlobalVariable *GV,603                                 const StringLiteral *S);604 605  /// Emit C++ namespace alias.606  llvm::DIImportedEntity *EmitNamespaceAlias(const NamespaceAliasDecl &NA);607 608  /// Emit record type's standalone debug info.609  llvm::DIType *getOrCreateRecordType(QualType Ty, SourceLocation L);610 611  /// Emit an Objective-C interface type standalone debug info.612  llvm::DIType *getOrCreateInterfaceType(QualType Ty, SourceLocation Loc);613 614  /// Emit standalone debug info for a type.615  llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Loc);616 617  /// Add heapallocsite metadata for MSAllocator calls.618  void addHeapAllocSiteMetadata(llvm::CallBase *CallSite, QualType AllocatedTy,619                                SourceLocation Loc);620 621  void completeType(const EnumDecl *ED);622  void completeType(const RecordDecl *RD);623  void completeRequiredType(const RecordDecl *RD);624  void completeClassData(const RecordDecl *RD);625  void completeClass(const RecordDecl *RD);626 627  void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD);628  void completeUnusedClass(const CXXRecordDecl &D);629 630  /// Create debug info for a macro defined by a #define directive or a macro631  /// undefined by a #undef directive.632  llvm::DIMacro *CreateMacro(llvm::DIMacroFile *Parent, unsigned MType,633                             SourceLocation LineLoc, StringRef Name,634                             StringRef Value);635 636  /// Create debug info for a file referenced by an #include directive.637  llvm::DIMacroFile *CreateTempMacroFile(llvm::DIMacroFile *Parent,638                                         SourceLocation LineLoc,639                                         SourceLocation FileLoc);640 641  Param2DILocTy &getParamDbgMappings() { return ParamDbgMappings; }642  ParamDecl2StmtTy &getCoroutineParameterMappings() {643    return CoroutineParameterMappings;644  }645 646  /// Create a debug location from `TrapLocation` that adds an artificial inline647  /// frame where the frame name is648  ///649  /// * `<Prefix>:<Category>:<FailureMsg>`650  ///651  /// `<Prefix>` is "__clang_trap_msg".652  ///653  /// This is used to store failure reasons for traps.654  llvm::DILocation *CreateTrapFailureMessageFor(llvm::DebugLoc TrapLocation,655                                                StringRef Category,656                                                StringRef FailureMsg);657  /// Create a debug location from `Location` that adds an artificial inline658  /// frame where the frame name is FuncName659  ///660  /// This is used to indiciate instructions that come from compiler661  /// instrumentation.662  llvm::DILocation *CreateSyntheticInlineAt(llvm::DebugLoc Location,663                                            StringRef FuncName);664 665  /// Reset internal state.666  void completeFunction();667 668  /// Add \p KeyInstruction and an optional \p Backup instruction to the669  /// current atom group, created using ApplyAtomGroup.670  void addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction,671                                  llvm::Value *Backup);672 673  /// Add \p KeyInstruction and an optional \p Backup instruction to the atom674  /// group \p Atom.675  void addInstToSpecificSourceAtom(llvm::Instruction *KeyInstruction,676                                   llvm::Value *Backup, uint64_t Atom);677 678  /// Emit symbol for debugger that holds the pointer to the vtable.679  void emitVTableSymbol(llvm::GlobalVariable *VTable, const CXXRecordDecl *RD);680 681  /// Return flags which enable debug info emission for call sites, provided682  /// that it is supported and enabled.683  llvm::DINode::DIFlags getCallSiteRelatedAttrs() const;684 685private:686  /// Amend \p I's DebugLoc with \p Group (its source atom group) and \p687  /// Rank (lower nonzero rank is higher precedence). Does nothing if \p I688  /// has no DebugLoc, and chooses the atom group in which the instruction689  /// has the highest precedence if it's already in one.690  void addInstSourceAtomMetadata(llvm::Instruction *I, uint64_t Group,691                                 uint8_t Rank);692 693  /// Emit call to llvm.dbg.declare for a variable declaration.694  /// Returns a pointer to the DILocalVariable associated with the695  /// llvm.dbg.declare, or nullptr otherwise.696  llvm::DILocalVariable *EmitDeclare(const VarDecl *decl, llvm::Value *AI,697                                     std::optional<unsigned> ArgNo,698                                     CGBuilderTy &Builder,699                                     const bool UsePointerValue = false);700 701  /// Emit call to llvm.dbg.declare for a binding declaration.702  /// Returns a pointer to the DILocalVariable associated with the703  /// llvm.dbg.declare, or nullptr otherwise.704  llvm::DILocalVariable *EmitDeclare(const BindingDecl *decl, llvm::Value *AI,705                                     std::optional<unsigned> ArgNo,706                                     CGBuilderTy &Builder,707                                     const bool UsePointerValue = false);708 709  struct BlockByRefType {710    /// The wrapper struct used inside the __block_literal struct.711    llvm::DIType *BlockByRefWrapper;712    /// The type as it appears in the source code.713    llvm::DIType *WrappedType;714  };715 716  bool HasReconstitutableArgs(ArrayRef<TemplateArgument> Args) const;717  std::string GetName(const Decl *, bool Qualified = false) const;718 719  /// Build up structure info for the byref.  See \a BuildByRefType.720  BlockByRefType EmitTypeForVarWithBlocksAttr(const VarDecl *VD,721                                              uint64_t *OffSet);722 723  /// Get context info for the DeclContext of \p Decl.724  llvm::DIScope *getDeclContextDescriptor(const Decl *D);725  /// Get context info for a given DeclContext \p Decl.726  llvm::DIScope *getContextDescriptor(const Decl *Context,727                                      llvm::DIScope *Default);728 729  llvm::DIScope *getCurrentContextDescriptor(const Decl *Decl);730 731  /// Create a forward decl for a RecordType in a given context.732  llvm::DICompositeType *getOrCreateRecordFwdDecl(const RecordType *,733                                                  llvm::DIScope *);734 735  /// Return current directory name.736  StringRef getCurrentDirname();737 738  /// Create new compile unit.739  void CreateCompileUnit();740 741  /// Compute the file checksum debug info for input file ID.742  std::optional<llvm::DIFile::ChecksumKind>743  computeChecksum(FileID FID, SmallString<64> &Checksum) const;744 745  /// Get the source of the given file ID.746  std::optional<StringRef> getSource(const SourceManager &SM, FileID FID);747 748  /// Convenience function to get the file debug info descriptor for the input749  /// location.750  llvm::DIFile *getOrCreateFile(SourceLocation Loc);751 752  /// Create a file debug info descriptor for a source file.753  llvm::DIFile *754  createFile(StringRef FileName,755             std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,756             std::optional<StringRef> Source);757 758  /// Get the type from the cache or create a new type if necessary.759  llvm::DIType *getOrCreateType(QualType Ty, llvm::DIFile *Fg);760 761  /// Get a reference to a clang module.  If \p CreateSkeletonCU is true,762  /// this also creates a split dwarf skeleton compile unit.763  llvm::DIModule *getOrCreateModuleRef(ASTSourceDescriptor Mod,764                                       bool CreateSkeletonCU);765 766  /// DebugTypeExtRefs: If \p D originated in a clang module, return it.767  llvm::DIModule *getParentModuleOrNull(const Decl *D);768 769  /// Get the type from the cache or create a new partial type if770  /// necessary.771  llvm::DICompositeType *getOrCreateLimitedType(const RecordType *Ty);772 773  /// Create type metadata for a source language type.774  llvm::DIType *CreateTypeNode(QualType Ty, llvm::DIFile *Fg);775 776  /// Create new member and increase Offset by FType's size.777  llvm::DIType *CreateMemberType(llvm::DIFile *Unit, QualType FType,778                                 StringRef Name, uint64_t *Offset);779 780  /// Retrieve the DIDescriptor, if any, for the canonical form of this781  /// declaration.782  llvm::DINode *getDeclarationOrDefinition(const Decl *D);783 784  /// \return debug info descriptor to describe method785  /// declaration for the given method definition.786  llvm::DISubprogram *getFunctionDeclaration(const Decl *D);787 788  /// \return          debug info descriptor to the describe method declaration789  ///                  for the given method definition.790  /// \param FnType    For Objective-C methods, their type.791  /// \param LineNo    The declaration's line number.792  /// \param Flags     The DIFlags for the method declaration.793  /// \param SPFlags   The subprogram-spcific flags for the method declaration.794  llvm::DISubprogram *795  getObjCMethodDeclaration(const Decl *D, llvm::DISubroutineType *FnType,796                           unsigned LineNo, llvm::DINode::DIFlags Flags,797                           llvm::DISubprogram::DISPFlags SPFlags);798 799  /// \return debug info descriptor to describe in-class static data800  /// member declaration for the given out-of-class definition.  If D801  /// is an out-of-class definition of a static data member of a802  /// class, find its corresponding in-class declaration.803  llvm::DIDerivedType *804  getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D);805 806  /// Helper that either creates a forward declaration or a stub.807  llvm::DISubprogram *getFunctionFwdDeclOrStub(GlobalDecl GD, bool Stub);808 809  /// Create a subprogram describing the forward declaration810  /// represented in the given FunctionDecl wrapped in a GlobalDecl.811  llvm::DISubprogram *getFunctionForwardDeclaration(GlobalDecl GD);812 813  /// Create a DISubprogram describing the function814  /// represented in the given FunctionDecl wrapped in a GlobalDecl.815  llvm::DISubprogram *getFunctionStub(GlobalDecl GD);816 817  /// Create a global variable describing the forward declaration818  /// represented in the given VarDecl.819  llvm::DIGlobalVariable *820  getGlobalVariableForwardDeclaration(const VarDecl *VD);821 822  /// Return a global variable that represents one of the collection of global823  /// variables created for an anonmyous union.824  ///825  /// Recursively collect all of the member fields of a global826  /// anonymous decl and create static variables for them. The first827  /// time this is called it needs to be on a union and then from828  /// there we can have additional unnamed fields.829  llvm::DIGlobalVariableExpression *830  CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile *Unit,831                         unsigned LineNo, StringRef LinkageName,832                         llvm::GlobalVariable *Var, llvm::DIScope *DContext);833 834  /// Get the printing policy for producing names for debug info.835  PrintingPolicy getPrintingPolicy() const;836 837  /// Get function name for the given FunctionDecl. If the name is838  /// constructed on demand (e.g., C++ destructor) then the name is839  /// stored on the side.840  StringRef getFunctionName(const FunctionDecl *FD);841 842  /// Returns the unmangled name of an Objective-C method.843  /// This is the display name for the debugging info.844  StringRef getObjCMethodName(const ObjCMethodDecl *FD);845 846  /// Return selector name. This is used for debugging847  /// info.848  StringRef getSelectorName(Selector S);849 850  /// Get class name including template argument list.851  StringRef getClassName(const RecordDecl *RD);852 853  /// Get the vtable name for the given class.854  StringRef getVTableName(const CXXRecordDecl *Decl);855 856  /// Get the name to use in the debug info for a dynamic initializer or atexit857  /// stub function.858  StringRef getDynamicInitializerName(const VarDecl *VD,859                                      DynamicInitKind StubKind,860                                      llvm::Function *InitFn);861 862  /// Get line number for the location. If location is invalid863  /// then use current location.864  unsigned getLineNumber(SourceLocation Loc);865 866  /// Get column number for the location. If location is867  /// invalid then use current location.868  /// \param Force  Assume DebugColumnInfo option is true.869  unsigned getColumnNumber(SourceLocation Loc, bool Force = false);870 871  /// Collect various properties of a FunctionDecl.872  /// \param GD  A GlobalDecl whose getDecl() must return a FunctionDecl.873  void collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,874                                StringRef &Name, StringRef &LinkageName,875                                llvm::DIScope *&FDContext,876                                llvm::DINodeArray &TParamsArray,877                                llvm::DINode::DIFlags &Flags);878 879  /// Collect various properties of a VarDecl.880  void collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,881                           unsigned &LineNo, QualType &T, StringRef &Name,882                           StringRef &LinkageName,883                           llvm::MDTuple *&TemplateParameters,884                           llvm::DIScope *&VDContext);885 886  /// Create a DIExpression representing the constant corresponding887  /// to the specified 'Val'. Returns nullptr on failure.888  llvm::DIExpression *createConstantValueExpression(const clang::ValueDecl *VD,889                                                    const APValue &Val);890 891  /// Allocate a copy of \p A using the DebugInfoNames allocator892  /// and return a reference to it. If multiple arguments are given the strings893  /// are concatenated.894  StringRef internString(StringRef A, StringRef B = StringRef()) {895    char *Data = DebugInfoNames.Allocate<char>(A.size() + B.size());896    if (!A.empty())897      std::memcpy(Data, A.data(), A.size());898    if (!B.empty())899      std::memcpy(Data + A.size(), B.data(), B.size());900    return StringRef(Data, A.size() + B.size());901  }902 903  /// If one exists, returns the linkage name of the specified \904  /// (non-null) \c Method. Returns empty string otherwise.905  llvm::StringRef GetMethodLinkageName(const CXXMethodDecl *Method) const;906};907 908/// A scoped helper to set the current debug location to the specified909/// location or preferred location of the specified Expr.910class ApplyDebugLocation {911private:912  void init(SourceLocation TemporaryLocation, bool DefaultToEmpty = false);913  ApplyDebugLocation(CodeGenFunction &CGF, bool DefaultToEmpty,914                     SourceLocation TemporaryLocation);915 916  llvm::DebugLoc OriginalLocation;917  CodeGenFunction *CGF;918 919public:920  /// Set the location to the (valid) TemporaryLocation.921  ApplyDebugLocation(CodeGenFunction &CGF, SourceLocation TemporaryLocation);922  ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E);923  ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc);924  ApplyDebugLocation(ApplyDebugLocation &&Other) : CGF(Other.CGF) {925    Other.CGF = nullptr;926  }927 928  // Define copy assignment operator.929  ApplyDebugLocation &operator=(ApplyDebugLocation &&Other) {930    if (this != &Other) {931      CGF = Other.CGF;932      Other.CGF = nullptr;933    }934    return *this;935  }936 937  ~ApplyDebugLocation();938 939  /// Apply TemporaryLocation if it is valid. Otherwise switch940  /// to an artificial debug location that has a valid scope, but no941  /// line information.942  ///943  /// Artificial locations are useful when emitting compiler-generated944  /// helper functions that have no source location associated with945  /// them. The DWARF specification allows the compiler to use the946  /// special line number 0 to indicate code that can not be947  /// attributed to any source location. Note that passing an empty948  /// SourceLocation to CGDebugInfo::setLocation() will result in the949  /// last valid location being reused.950  static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF) {951    return ApplyDebugLocation(CGF, false, SourceLocation());952  }953  /// Apply TemporaryLocation if it is valid. Otherwise switch954  /// to an artificial debug location that has a valid scope, but no955  /// line information.956  static ApplyDebugLocation957  CreateDefaultArtificial(CodeGenFunction &CGF,958                          SourceLocation TemporaryLocation) {959    return ApplyDebugLocation(CGF, false, TemporaryLocation);960  }961 962  /// Set the IRBuilder to not attach debug locations.  Note that963  /// passing an empty SourceLocation to \a CGDebugInfo::setLocation()964  /// will result in the last valid location being reused.  Note that965  /// all instructions that do not have a location at the beginning of966  /// a function are counted towards to function prologue.967  static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF) {968    return ApplyDebugLocation(CGF, true, SourceLocation());969  }970};971 972/// A scoped helper to set the current debug location to an inlined location.973class ApplyInlineDebugLocation {974  SourceLocation SavedLocation;975  CodeGenFunction *CGF;976 977public:978  /// Set up the CodeGenFunction's DebugInfo to produce inline locations for the979  /// function \p InlinedFn. The current debug location becomes the inlined call980  /// site of the inlined function.981  ApplyInlineDebugLocation(CodeGenFunction &CGF, GlobalDecl InlinedFn);982  /// Restore everything back to the original state.983  ~ApplyInlineDebugLocation();984  ApplyInlineDebugLocation(const ApplyInlineDebugLocation &) = delete;985  ApplyInlineDebugLocation &operator=(ApplyInlineDebugLocation &) = delete;986};987 988class SanitizerDebugLocation {989  CodeGenFunction *CGF;990  ApplyDebugLocation Apply;991 992public:993  SanitizerDebugLocation(CodeGenFunction *CGF,994                         ArrayRef<SanitizerKind::SanitizerOrdinal> Ordinals,995                         SanitizerHandler Handler);996  ~SanitizerDebugLocation();997  SanitizerDebugLocation(const SanitizerDebugLocation &) = delete;998  SanitizerDebugLocation &operator=(SanitizerDebugLocation &) = delete;999};1000 1001} // namespace CodeGen1002} // namespace clang1003 1004#endif // LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H1005