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