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