1 //===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h ----*- 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 file contains support for writing Microsoft CodeView debug info.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H
15 #define LLVM_LIB_CODEGEN_ASMPRINTER_CODEVIEWDEBUG_H
16 
17 #include "DebugHandlerBase.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/CodeGen/AsmPrinter.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/DebugInfo/CodeView/MemoryTypeTableBuilder.h"
24 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DebugLoc.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/Target/TargetLoweringObjectFile.h"
29 
30 namespace llvm {
31 
32 class StringRef;
33 class LexicalScope;
34 struct ClassInfo;
35 
36 /// \brief Collects and handles line tables information in a CodeView format.
37 class LLVM_LIBRARY_VISIBILITY CodeViewDebug : public DebugHandlerBase {
38   MCStreamer &OS;
39   codeview::MemoryTypeTableBuilder TypeTable;
40 
41   /// Represents the most general definition range.
42   struct LocalVarDefRange {
43     /// Indicates that variable data is stored in memory relative to the
44     /// specified register.
45     int InMemory : 1;
46 
47     /// Offset of variable data in memory.
48     int DataOffset : 31;
49 
50     /// Offset of the data into the user level struct. If zero, no splitting
51     /// occurred.
52     uint16_t StructOffset;
53 
54     /// Register containing the data or the register base of the memory
55     /// location containing the data.
56     uint16_t CVRegister;
57 
58     /// Compares all location fields. This includes all fields except the label
59     /// ranges.
60     bool isDifferentLocation(LocalVarDefRange &O) {
61       return InMemory != O.InMemory || DataOffset != O.DataOffset ||
62              StructOffset != O.StructOffset || CVRegister != O.CVRegister;
63     }
64 
65     SmallVector<std::pair<const MCSymbol *, const MCSymbol *>, 1> Ranges;
66   };
67 
68   static LocalVarDefRange createDefRangeMem(uint16_t CVRegister, int Offset);
69   static LocalVarDefRange createDefRangeReg(uint16_t CVRegister);
70 
71   /// Similar to DbgVariable in DwarfDebug, but not dwarf-specific.
72   struct LocalVariable {
73     const DILocalVariable *DIVar = nullptr;
74     SmallVector<LocalVarDefRange, 1> DefRanges;
75   };
76 
77   struct InlineSite {
78     SmallVector<LocalVariable, 1> InlinedLocals;
79     SmallVector<const DILocation *, 1> ChildSites;
80     const DISubprogram *Inlinee = nullptr;
81 
82     /// The ID of the inline site or function used with .cv_loc. Not a type
83     /// index.
84     unsigned SiteFuncId = 0;
85   };
86 
87   // For each function, store a vector of labels to its instructions, as well as
88   // to the end of the function.
89   struct FunctionInfo {
90     /// Map from inlined call site to inlined instructions and child inlined
91     /// call sites. Listed in program order.
92     std::unordered_map<const DILocation *, InlineSite> InlineSites;
93 
94     /// Ordered list of top-level inlined call sites.
95     SmallVector<const DILocation *, 1> ChildSites;
96 
97     SmallVector<LocalVariable, 1> Locals;
98 
99     DebugLoc LastLoc;
100     const MCSymbol *Begin = nullptr;
101     const MCSymbol *End = nullptr;
102     unsigned FuncId = 0;
103     unsigned LastFileId = 0;
104     bool HaveLineInfo = false;
105   };
106   FunctionInfo *CurFn;
107 
108   /// The set of comdat .debug$S sections that we've seen so far. Each section
109   /// must start with a magic version number that must only be emitted once.
110   /// This set tracks which sections we've already opened.
111   DenseSet<MCSectionCOFF *> ComdatDebugSections;
112 
113   /// Switch to the appropriate .debug$S section for GVSym. If GVSym, the symbol
114   /// of an emitted global value, is in a comdat COFF section, this will switch
115   /// to a new .debug$S section in that comdat. This method ensures that the
116   /// section starts with the magic version number on first use. If GVSym is
117   /// null, uses the main .debug$S section.
118   void switchToDebugSectionForSymbol(const MCSymbol *GVSym);
119 
120   /// The next available function index for use with our .cv_* directives. Not
121   /// to be confused with type indices for LF_FUNC_ID records.
122   unsigned NextFuncId = 0;
123 
124   InlineSite &getInlineSite(const DILocation *InlinedAt,
125                             const DISubprogram *Inlinee);
126 
127   codeview::TypeIndex getFuncIdForSubprogram(const DISubprogram *SP);
128 
129   static void collectInlineSiteChildren(SmallVectorImpl<unsigned> &Children,
130                                         const FunctionInfo &FI,
131                                         const InlineSite &Site);
132 
133   /// Remember some debug info about each function. Keep it in a stable order to
134   /// emit at the end of the TU.
135   MapVector<const Function *, FunctionInfo> FnDebugInfo;
136 
137   /// Map from DIFile to .cv_file id.
138   DenseMap<const DIFile *, unsigned> FileIdMap;
139 
140   /// All inlined subprograms in the order they should be emitted.
141   SmallSetVector<const DISubprogram *, 4> InlinedSubprograms;
142 
143   /// Map from a pair of DI metadata nodes and its DI type (or scope) that can
144   /// be nullptr, to CodeView type indices. Primarily indexed by
145   /// {DIType*, DIType*} and {DISubprogram*, DIType*}.
146   ///
147   /// The second entry in the key is needed for methods as DISubroutineType
148   /// representing static method type are shared with non-method function type.
149   DenseMap<std::pair<const DINode *, const DIType *>, codeview::TypeIndex>
150       TypeIndices;
151 
152   /// Map from DICompositeType* to complete type index. Non-record types are
153   /// always looked up in the normal TypeIndices map.
154   DenseMap<const DICompositeType *, codeview::TypeIndex> CompleteTypeIndices;
155 
156   /// Complete record types to emit after all active type lowerings are
157   /// finished.
158   SmallVector<const DICompositeType *, 4> DeferredCompleteTypes;
159 
160   /// Number of type lowering frames active on the stack.
161   unsigned TypeEmissionLevel = 0;
162 
163   codeview::TypeIndex VBPType;
164 
165   const DISubprogram *CurrentSubprogram = nullptr;
166 
167   // The UDTs we have seen while processing types; each entry is a pair of type
168   // index and type name.
169   std::vector<std::pair<std::string, codeview::TypeIndex>> LocalUDTs,
170       GlobalUDTs;
171 
172   typedef std::map<const DIFile *, std::string> FileToFilepathMapTy;
173   FileToFilepathMapTy FileToFilepathMap;
174   StringRef getFullFilepath(const DIFile *S);
175 
176   unsigned maybeRecordFile(const DIFile *F);
177 
178   void maybeRecordLocation(const DebugLoc &DL, const MachineFunction *MF);
179 
180   void clear();
181 
182   void setCurrentSubprogram(const DISubprogram *SP) {
183     CurrentSubprogram = SP;
184     LocalUDTs.clear();
185   }
186 
187   /// Emit the magic version number at the start of a CodeView type or symbol
188   /// section. Appears at the front of every .debug$S or .debug$T section.
189   void emitCodeViewMagicVersion();
190 
191   void emitTypeInformation();
192 
193   void emitInlineeLinesSubsection();
194 
195   void emitDebugInfoForFunction(const Function *GV, FunctionInfo &FI);
196 
197   void emitDebugInfoForGlobals();
198 
199   void emitDebugInfoForRetainedTypes();
200 
201   void emitDebugInfoForUDTs(
202       ArrayRef<std::pair<std::string, codeview::TypeIndex>> UDTs);
203 
204   void emitDebugInfoForGlobal(const DIGlobalVariable *DIGV, MCSymbol *GVSym);
205 
206   /// Opens a subsection of the given kind in a .debug$S codeview section.
207   /// Returns an end label for use with endCVSubsection when the subsection is
208   /// finished.
209   MCSymbol *beginCVSubsection(codeview::ModuleSubstreamKind Kind);
210 
211   void endCVSubsection(MCSymbol *EndLabel);
212 
213   void emitInlinedCallSite(const FunctionInfo &FI, const DILocation *InlinedAt,
214                            const InlineSite &Site);
215 
216   typedef DbgValueHistoryMap::InlinedVariable InlinedVariable;
217 
218   void collectVariableInfo(const DISubprogram *SP);
219 
220   void collectVariableInfoFromMMITable(DenseSet<InlinedVariable> &Processed);
221 
222   /// Records information about a local variable in the appropriate scope. In
223   /// particular, locals from inlined code live inside the inlining site.
224   void recordLocalVariable(LocalVariable &&Var, const DILocation *Loc);
225 
226   /// Emits local variables in the appropriate order.
227   void emitLocalVariableList(ArrayRef<LocalVariable> Locals);
228 
229   /// Emits an S_LOCAL record and its associated defined ranges.
230   void emitLocalVariable(const LocalVariable &Var);
231 
232   /// Translates the DIType to codeview if necessary and returns a type index
233   /// for it.
234   codeview::TypeIndex getTypeIndex(DITypeRef TypeRef,
235                                    DITypeRef ClassTyRef = DITypeRef());
236 
237   codeview::TypeIndex getMemberFunctionType(const DISubprogram *SP,
238                                             const DICompositeType *Class);
239 
240   codeview::TypeIndex getScopeIndex(const DIScope *Scope);
241 
242   codeview::TypeIndex getVBPTypeIndex();
243 
244   void addToUDTs(const DIType *Ty, codeview::TypeIndex TI);
245 
246   codeview::TypeIndex lowerType(const DIType *Ty, const DIType *ClassTy);
247   codeview::TypeIndex lowerTypeAlias(const DIDerivedType *Ty);
248   codeview::TypeIndex lowerTypeArray(const DICompositeType *Ty);
249   codeview::TypeIndex lowerTypeBasic(const DIBasicType *Ty);
250   codeview::TypeIndex lowerTypePointer(const DIDerivedType *Ty);
251   codeview::TypeIndex lowerTypeMemberPointer(const DIDerivedType *Ty);
252   codeview::TypeIndex lowerTypeModifier(const DIDerivedType *Ty);
253   codeview::TypeIndex lowerTypeFunction(const DISubroutineType *Ty);
254   codeview::TypeIndex lowerTypeMemberFunction(const DISubroutineType *Ty,
255                                               const DIType *ClassTy,
256                                               int ThisAdjustment);
257   codeview::TypeIndex lowerTypeEnum(const DICompositeType *Ty);
258   codeview::TypeIndex lowerTypeClass(const DICompositeType *Ty);
259   codeview::TypeIndex lowerTypeUnion(const DICompositeType *Ty);
260 
261   /// Symbol records should point to complete types, but type records should
262   /// always point to incomplete types to avoid cycles in the type graph. Only
263   /// use this entry point when generating symbol records. The complete and
264   /// incomplete type indices only differ for record types. All other types use
265   /// the same index.
266   codeview::TypeIndex getCompleteTypeIndex(DITypeRef TypeRef);
267 
268   codeview::TypeIndex lowerCompleteTypeClass(const DICompositeType *Ty);
269   codeview::TypeIndex lowerCompleteTypeUnion(const DICompositeType *Ty);
270 
271   struct TypeLoweringScope;
272 
273   void emitDeferredCompleteTypes();
274 
275   void collectMemberInfo(ClassInfo &Info, const DIDerivedType *DDTy);
276   ClassInfo collectClassInfo(const DICompositeType *Ty);
277 
278   /// Common record member lowering functionality for record types, which are
279   /// structs, classes, and unions. Returns the field list index and the member
280   /// count.
281   std::tuple<codeview::TypeIndex, codeview::TypeIndex, unsigned, bool>
282   lowerRecordFieldList(const DICompositeType *Ty);
283 
284   /// Inserts {{Node, ClassTy}, TI} into TypeIndices and checks for duplicates.
285   codeview::TypeIndex recordTypeIndexForDINode(const DINode *Node,
286                                                codeview::TypeIndex TI,
287                                                const DIType *ClassTy = nullptr);
288 
289   unsigned getPointerSizeInBytes();
290 
291 public:
292   CodeViewDebug(AsmPrinter *Asm);
293 
294   void setSymbolSize(const llvm::MCSymbol *, uint64_t) override {}
295 
296   /// \brief Emit the COFF section that holds the line table information.
297   void endModule() override;
298 
299   /// \brief Gather pre-function debug information.
300   void beginFunction(const MachineFunction *MF) override;
301 
302   /// \brief Gather post-function debug information.
303   void endFunction(const MachineFunction *) override;
304 
305   /// \brief Process beginning of an instruction.
306   void beginInstruction(const MachineInstr *MI) override;
307 };
308 } // End of namespace llvm
309 
310 #endif
311