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