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