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