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