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