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