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