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 *EmitDeclareOfAutoVariable(const VarDecl *Decl,
426                                                    llvm::Value *AI,
427                                                    CGBuilderTy &Builder);
428 
429   /// Emit call to \c llvm.dbg.label for an label.
430   void EmitLabel(const LabelDecl *D, CGBuilderTy &Builder);
431 
432   /// Emit call to \c llvm.dbg.declare for an imported variable
433   /// declaration in a block.
434   void EmitDeclareOfBlockDeclRefVariable(
435       const VarDecl *variable, llvm::Value *storage, CGBuilderTy &Builder,
436       const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint = nullptr);
437 
438   /// Emit call to \c llvm.dbg.declare for an argument variable
439   /// declaration.
440   void EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI,
441                                 unsigned ArgNo, CGBuilderTy &Builder);
442 
443   /// Emit call to \c llvm.dbg.declare for the block-literal argument
444   /// to a block invocation function.
445   void EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
446                                             StringRef Name, unsigned ArgNo,
447                                             llvm::AllocaInst *LocalAddr,
448                                             CGBuilderTy &Builder);
449 
450   /// Emit information about a global variable.
451   void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl);
452 
453   /// Emit a constant global variable's debug info.
454   void EmitGlobalVariable(const ValueDecl *VD, const APValue &Init);
455 
456   /// Emit C++ using directive.
457   void EmitUsingDirective(const UsingDirectiveDecl &UD);
458 
459   /// Emit the type explicitly casted to.
460   void EmitExplicitCastType(QualType Ty);
461 
462   /// Emit C++ using declaration.
463   void EmitUsingDecl(const UsingDecl &UD);
464 
465   /// Emit an @import declaration.
466   void EmitImportDecl(const ImportDecl &ID);
467 
468   /// Emit C++ namespace alias.
469   llvm::DIImportedEntity *EmitNamespaceAlias(const NamespaceAliasDecl &NA);
470 
471   /// Emit record type's standalone debug info.
472   llvm::DIType *getOrCreateRecordType(QualType Ty, SourceLocation L);
473 
474   /// Emit an Objective-C interface type standalone debug info.
475   llvm::DIType *getOrCreateInterfaceType(QualType Ty, SourceLocation Loc);
476 
477   /// Emit standalone debug info for a type.
478   llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Loc);
479 
480   /// Add heapallocsite metadata for MSAllocator calls.
481   void addHeapAllocSiteMetadata(llvm::Instruction *CallSite, QualType Ty,
482                                 SourceLocation Loc);
483 
484   void completeType(const EnumDecl *ED);
485   void completeType(const RecordDecl *RD);
486   void completeRequiredType(const RecordDecl *RD);
487   void completeClassData(const RecordDecl *RD);
488   void completeClass(const RecordDecl *RD);
489 
490   void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD);
491   void completeUnusedClass(const CXXRecordDecl &D);
492 
493   /// Create debug info for a macro defined by a #define directive or a macro
494   /// undefined by a #undef directive.
495   llvm::DIMacro *CreateMacro(llvm::DIMacroFile *Parent, unsigned MType,
496                              SourceLocation LineLoc, StringRef Name,
497                              StringRef Value);
498 
499   /// Create debug info for a file referenced by an #include directive.
500   llvm::DIMacroFile *CreateTempMacroFile(llvm::DIMacroFile *Parent,
501                                          SourceLocation LineLoc,
502                                          SourceLocation FileLoc);
503 
504 private:
505   /// Emit call to llvm.dbg.declare for a variable declaration.
506   /// Returns a pointer to the DILocalVariable associated with the
507   /// llvm.dbg.declare, or nullptr otherwise.
508   llvm::DILocalVariable *EmitDeclare(const VarDecl *decl, llvm::Value *AI,
509                                      llvm::Optional<unsigned> ArgNo,
510                                      CGBuilderTy &Builder);
511 
512   struct BlockByRefType {
513     /// The wrapper struct used inside the __block_literal struct.
514     llvm::DIType *BlockByRefWrapper;
515     /// The type as it appears in the source code.
516     llvm::DIType *WrappedType;
517   };
518 
519   /// Build up structure info for the byref.  See \a BuildByRefType.
520   BlockByRefType EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
521                                               uint64_t *OffSet);
522 
523   /// Get context info for the DeclContext of \p Decl.
524   llvm::DIScope *getDeclContextDescriptor(const Decl *D);
525   /// Get context info for a given DeclContext \p Decl.
526   llvm::DIScope *getContextDescriptor(const Decl *Context,
527                                       llvm::DIScope *Default);
528 
529   llvm::DIScope *getCurrentContextDescriptor(const Decl *Decl);
530 
531   /// Create a forward decl for a RecordType in a given context.
532   llvm::DICompositeType *getOrCreateRecordFwdDecl(const RecordType *,
533                                                   llvm::DIScope *);
534 
535   /// Return current directory name.
536   StringRef getCurrentDirname();
537 
538   /// Create new compile unit.
539   void CreateCompileUnit();
540 
541   /// Compute the file checksum debug info for input file ID.
542   Optional<llvm::DIFile::ChecksumKind>
543   computeChecksum(FileID FID, SmallString<32> &Checksum) const;
544 
545   /// Get the source of the given file ID.
546   Optional<StringRef> getSource(const SourceManager &SM, FileID FID);
547 
548   /// Convenience function to get the file debug info descriptor for the input
549   /// location.
550   llvm::DIFile *getOrCreateFile(SourceLocation Loc);
551 
552   /// Create a file debug info descriptor for a source file.
553   llvm::DIFile *
554   createFile(StringRef FileName,
555              Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
556              Optional<StringRef> Source);
557 
558   /// Get the type from the cache or create a new type if necessary.
559   llvm::DIType *getOrCreateType(QualType Ty, llvm::DIFile *Fg);
560 
561   /// Get a reference to a clang module.  If \p CreateSkeletonCU is true,
562   /// this also creates a split dwarf skeleton compile unit.
563   llvm::DIModule *
564   getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
565                        bool CreateSkeletonCU);
566 
567   /// DebugTypeExtRefs: If \p D originated in a clang module, return it.
568   llvm::DIModule *getParentModuleOrNull(const Decl *D);
569 
570   /// Get the type from the cache or create a new partial type if
571   /// necessary.
572   llvm::DICompositeType *getOrCreateLimitedType(const RecordType *Ty,
573                                                 llvm::DIFile *F);
574 
575   /// Create type metadata for a source language type.
576   llvm::DIType *CreateTypeNode(QualType Ty, llvm::DIFile *Fg);
577 
578   /// Create new member and increase Offset by FType's size.
579   llvm::DIType *CreateMemberType(llvm::DIFile *Unit, QualType FType,
580                                  StringRef Name, uint64_t *Offset);
581 
582   /// Retrieve the DIDescriptor, if any, for the canonical form of this
583   /// declaration.
584   llvm::DINode *getDeclarationOrDefinition(const Decl *D);
585 
586   /// \return debug info descriptor to describe method
587   /// declaration for the given method definition.
588   llvm::DISubprogram *getFunctionDeclaration(const Decl *D);
589 
590   /// \return debug info descriptor to describe in-class static data
591   /// member declaration for the given out-of-class definition.  If D
592   /// is an out-of-class definition of a static data member of a
593   /// class, find its corresponding in-class declaration.
594   llvm::DIDerivedType *
595   getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D);
596 
597   /// Helper that either creates a forward declaration or a stub.
598   llvm::DISubprogram *getFunctionFwdDeclOrStub(GlobalDecl GD, bool Stub);
599 
600   /// Create a subprogram describing the forward declaration
601   /// represented in the given FunctionDecl wrapped in a GlobalDecl.
602   llvm::DISubprogram *getFunctionForwardDeclaration(GlobalDecl GD);
603 
604   /// Create a DISubprogram describing the function
605   /// represented in the given FunctionDecl wrapped in a GlobalDecl.
606   llvm::DISubprogram *getFunctionStub(GlobalDecl GD);
607 
608   /// Create a global variable describing the forward declaration
609   /// represented in the given VarDecl.
610   llvm::DIGlobalVariable *
611   getGlobalVariableForwardDeclaration(const VarDecl *VD);
612 
613   /// Return a global variable that represents one of the collection of global
614   /// variables created for an anonmyous union.
615   ///
616   /// Recursively collect all of the member fields of a global
617   /// anonymous decl and create static variables for them. The first
618   /// time this is called it needs to be on a union and then from
619   /// there we can have additional unnamed fields.
620   llvm::DIGlobalVariableExpression *
621   CollectAnonRecordDecls(const RecordDecl *RD, llvm::DIFile *Unit,
622                          unsigned LineNo, StringRef LinkageName,
623                          llvm::GlobalVariable *Var, llvm::DIScope *DContext);
624 
625 
626   /// Return flags which enable debug info emission for call sites, provided
627   /// that it is supported and enabled.
628   llvm::DINode::DIFlags getCallSiteRelatedAttrs() const;
629 
630   /// Get the printing policy for producing names for debug info.
631   PrintingPolicy getPrintingPolicy() const;
632 
633   /// Get function name for the given FunctionDecl. If the name is
634   /// constructed on demand (e.g., C++ destructor) then the name is
635   /// stored on the side.
636   StringRef getFunctionName(const FunctionDecl *FD);
637 
638   /// Returns the unmangled name of an Objective-C method.
639   /// This is the display name for the debugging info.
640   StringRef getObjCMethodName(const ObjCMethodDecl *FD);
641 
642   /// Return selector name. This is used for debugging
643   /// info.
644   StringRef getSelectorName(Selector S);
645 
646   /// Get class name including template argument list.
647   StringRef getClassName(const RecordDecl *RD);
648 
649   /// Get the vtable name for the given class.
650   StringRef getVTableName(const CXXRecordDecl *Decl);
651 
652   /// Get the name to use in the debug info for a dynamic initializer or atexit
653   /// stub function.
654   StringRef getDynamicInitializerName(const VarDecl *VD,
655                                       DynamicInitKind StubKind,
656                                       llvm::Function *InitFn);
657 
658   /// Get line number for the location. If location is invalid
659   /// then use current location.
660   unsigned getLineNumber(SourceLocation Loc);
661 
662   /// Get column number for the location. If location is
663   /// invalid then use current location.
664   /// \param Force  Assume DebugColumnInfo option is true.
665   unsigned getColumnNumber(SourceLocation Loc, bool Force = false);
666 
667   /// Collect various properties of a FunctionDecl.
668   /// \param GD  A GlobalDecl whose getDecl() must return a FunctionDecl.
669   void collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
670                                 StringRef &Name, StringRef &LinkageName,
671                                 llvm::DIScope *&FDContext,
672                                 llvm::DINodeArray &TParamsArray,
673                                 llvm::DINode::DIFlags &Flags);
674 
675   /// Collect various properties of a VarDecl.
676   void collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
677                            unsigned &LineNo, QualType &T, StringRef &Name,
678                            StringRef &LinkageName,
679                            llvm::MDTuple *&TemplateParameters,
680                            llvm::DIScope *&VDContext);
681 
682   /// Allocate a copy of \p A using the DebugInfoNames allocator
683   /// and return a reference to it. If multiple arguments are given the strings
684   /// are concatenated.
685   StringRef internString(StringRef A, StringRef B = StringRef()) {
686     char *Data = DebugInfoNames.Allocate<char>(A.size() + B.size());
687     if (!A.empty())
688       std::memcpy(Data, A.data(), A.size());
689     if (!B.empty())
690       std::memcpy(Data + A.size(), B.data(), B.size());
691     return StringRef(Data, A.size() + B.size());
692   }
693 };
694 
695 /// A scoped helper to set the current debug location to the specified
696 /// location or preferred location of the specified Expr.
697 class ApplyDebugLocation {
698 private:
699   void init(SourceLocation TemporaryLocation, bool DefaultToEmpty = false);
700   ApplyDebugLocation(CodeGenFunction &CGF, bool DefaultToEmpty,
701                      SourceLocation TemporaryLocation);
702 
703   llvm::DebugLoc OriginalLocation;
704   CodeGenFunction *CGF;
705 
706 public:
707   /// Set the location to the (valid) TemporaryLocation.
708   ApplyDebugLocation(CodeGenFunction &CGF, SourceLocation TemporaryLocation);
709   ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E);
710   ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc);
711   ApplyDebugLocation(ApplyDebugLocation &&Other) : CGF(Other.CGF) {
712     Other.CGF = nullptr;
713   }
714 
715   ~ApplyDebugLocation();
716 
717   /// Apply TemporaryLocation if it is valid. Otherwise switch
718   /// to an artificial debug location that has a valid scope, but no
719   /// line information.
720   ///
721   /// Artificial locations are useful when emitting compiler-generated
722   /// helper functions that have no source location associated with
723   /// them. The DWARF specification allows the compiler to use the
724   /// special line number 0 to indicate code that can not be
725   /// attributed to any source location. Note that passing an empty
726   /// SourceLocation to CGDebugInfo::setLocation() will result in the
727   /// last valid location being reused.
728   static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF) {
729     return ApplyDebugLocation(CGF, false, SourceLocation());
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   static ApplyDebugLocation
735   CreateDefaultArtificial(CodeGenFunction &CGF,
736                           SourceLocation TemporaryLocation) {
737     return ApplyDebugLocation(CGF, false, TemporaryLocation);
738   }
739 
740   /// Set the IRBuilder to not attach debug locations.  Note that
741   /// passing an empty SourceLocation to \a CGDebugInfo::setLocation()
742   /// will result in the last valid location being reused.  Note that
743   /// all instructions that do not have a location at the beginning of
744   /// a function are counted towards to function prologue.
745   static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF) {
746     return ApplyDebugLocation(CGF, true, SourceLocation());
747   }
748 };
749 
750 /// A scoped helper to set the current debug location to an inlined location.
751 class ApplyInlineDebugLocation {
752   SourceLocation SavedLocation;
753   CodeGenFunction *CGF;
754 
755 public:
756   /// Set up the CodeGenFunction's DebugInfo to produce inline locations for the
757   /// function \p InlinedFn. The current debug location becomes the inlined call
758   /// site of the inlined function.
759   ApplyInlineDebugLocation(CodeGenFunction &CGF, GlobalDecl InlinedFn);
760   /// Restore everything back to the original state.
761   ~ApplyInlineDebugLocation();
762 };
763 
764 } // namespace CodeGen
765 } // namespace clang
766 
767 #endif // LLVM_CLANG_LIB_CODEGEN_CGDEBUGINFO_H
768