blob: d567d6a87cb65d2b900d880e9be79c2feb612add [file] [log] [blame]
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001//===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- C++ -*--===//
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002//
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//
Reid Kleckner70f5bc92016-01-14 19:25:04 +000010// This file contains support for writing Microsoft CodeView debug info.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000011//
12//===----------------------------------------------------------------------===//
13
Reid Kleckner70f5bc92016-01-14 19:25:04 +000014#include "CodeViewDebug.h"
Reid Kleckner156a7232016-06-22 18:31:14 +000015#include "llvm/ADT/TinyPtrVector.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000016#include "llvm/DebugInfo/CodeView/ByteStream.h"
17#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000018#include "llvm/DebugInfo/CodeView/CodeView.h"
Reid Klecknera8d57402016-06-03 15:58:20 +000019#include "llvm/DebugInfo/CodeView/FieldListRecordBuilder.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000020#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000021#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000022#include "llvm/DebugInfo/CodeView/TypeDumper.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000023#include "llvm/DebugInfo/CodeView/TypeIndex.h"
24#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000025#include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000026#include "llvm/IR/Constants.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000027#include "llvm/MC/MCExpr.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000028#include "llvm/MC/MCSectionCOFF.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000029#include "llvm/MC/MCSymbol.h"
30#include "llvm/Support/COFF.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000031#include "llvm/Support/ScopedPrinter.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000032#include "llvm/Target/TargetFrameLowering.h"
Amjad Aboud76c9eb92016-06-18 10:25:07 +000033#include "llvm/Target/TargetRegisterInfo.h"
34#include "llvm/Target/TargetSubtargetInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000035
Reid Klecknerf9c275f2016-02-10 20:55:49 +000036using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000037using namespace llvm::codeview;
38
Reid Klecknerf9c275f2016-02-10 20:55:49 +000039CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
40 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
41 // If module doesn't have named metadata anchors or COFF debug section
42 // is not available, skip any debug info related stuff.
43 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
44 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
45 Asm = nullptr;
46 return;
47 }
48
49 // Tell MMI that we have debug info.
50 MMI->setDebugInfoAvailability(true);
51}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000052
Reid Kleckner9533af42016-01-16 00:09:09 +000053StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
54 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000055 if (!Filepath.empty())
56 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000057
Reid Kleckner9533af42016-01-16 00:09:09 +000058 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
59
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000060 // Clang emits directory and relative filename info into the IR, but CodeView
61 // operates on full paths. We could change Clang to emit full paths too, but
62 // that would increase the IR size and probably not needed for other users.
63 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000064 if (Filename.find(':') == 1)
65 Filepath = Filename;
66 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +000067 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000068
69 // Canonicalize the path. We have to do it textually because we may no longer
70 // have access the file in the filesystem.
71 // First, replace all slashes with backslashes.
72 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
73
74 // Remove all "\.\" with "\".
75 size_t Cursor = 0;
76 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
77 Filepath.erase(Cursor, 2);
78
79 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
80 // path should be well-formatted, e.g. start with a drive letter, etc.
81 Cursor = 0;
82 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
83 // Something's wrong if the path starts with "\..\", abort.
84 if (Cursor == 0)
85 break;
86
87 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
88 if (PrevSlash == std::string::npos)
89 // Something's wrong, abort.
90 break;
91
92 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
93 // The next ".." might be following the one we've just erased.
94 Cursor = PrevSlash;
95 }
96
97 // Remove all duplicate backslashes.
98 Cursor = 0;
99 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
100 Filepath.erase(Cursor, 1);
101
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000102 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000103}
104
Reid Kleckner2214ed82016-01-29 00:49:42 +0000105unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
106 unsigned NextId = FileIdMap.size() + 1;
107 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
108 if (Insertion.second) {
109 // We have to compute the full filepath and emit a .cv_file directive.
110 StringRef FullPath = getFullFilepath(F);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000111 NextId = OS.EmitCVFileDirective(NextId, FullPath);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000112 assert(NextId == FileIdMap.size() && ".cv_file directive failed");
113 }
114 return Insertion.first->second;
115}
116
Reid Kleckner876330d2016-02-12 21:48:30 +0000117CodeViewDebug::InlineSite &
118CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
119 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000120 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
121 InlineSite *Site = &SiteInsertion.first->second;
122 if (SiteInsertion.second) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000123 Site->SiteFuncId = NextFuncId++;
Reid Kleckner876330d2016-02-12 21:48:30 +0000124 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000125 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000126 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000127 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000128 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000129}
130
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000131static const DISubprogram *getQualifiedNameComponents(
132 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
133 const DISubprogram *ClosestSubprogram = nullptr;
134 while (Scope != nullptr) {
135 if (ClosestSubprogram == nullptr)
136 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
137 StringRef ScopeName = Scope->getName();
138 if (!ScopeName.empty())
139 QualifiedNameComponents.push_back(ScopeName);
140 Scope = Scope->getScope().resolve();
141 }
142 return ClosestSubprogram;
143}
144
145static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
146 StringRef TypeName) {
147 std::string FullyQualifiedName;
148 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
149 FullyQualifiedName.append(QualifiedNameComponent);
150 FullyQualifiedName.append("::");
151 }
152 FullyQualifiedName.append(TypeName);
153 return FullyQualifiedName;
154}
155
156static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
157 SmallVector<StringRef, 5> QualifiedNameComponents;
158 getQualifiedNameComponents(Scope, QualifiedNameComponents);
159 return getQualifiedName(QualifiedNameComponents, Name);
160}
161
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000162struct CodeViewDebug::TypeLoweringScope {
163 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
164 ~TypeLoweringScope() {
165 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
166 // inner TypeLoweringScopes don't attempt to emit deferred types.
167 if (CVD.TypeEmissionLevel == 1)
168 CVD.emitDeferredCompleteTypes();
169 --CVD.TypeEmissionLevel;
170 }
171 CodeViewDebug &CVD;
172};
173
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000174TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
175 // No scope means global scope and that uses the zero index.
176 if (!Scope || isa<DIFile>(Scope))
177 return TypeIndex();
178
179 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
180
181 // Check if we've already translated this scope.
182 auto I = TypeIndices.find({Scope, nullptr});
183 if (I != TypeIndices.end())
184 return I->second;
185
186 // Build the fully qualified name of the scope.
187 std::string ScopeName =
188 getFullyQualifiedName(Scope->getScope().resolve(), Scope->getName());
189 TypeIndex TI =
190 TypeTable.writeStringId(StringIdRecord(TypeIndex(), ScopeName));
191 return recordTypeIndexForDINode(Scope, TI);
192}
193
David Majnemer75c3ebf2016-06-02 17:13:53 +0000194TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
195 // It's possible to ask for the FuncId of a function which doesn't have a
196 // subprogram: inlining a function with debug info into a function with none.
197 if (!SP)
David Majnemerb68f32f02016-06-02 18:51:24 +0000198 return TypeIndex::None();
Reid Kleckner2280f932016-05-23 20:23:46 +0000199
David Majnemer75c3ebf2016-06-02 17:13:53 +0000200 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000201 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000202 if (I != TypeIndices.end())
203 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000204
Reid Klecknerac945e22016-06-17 16:11:20 +0000205 // The display name includes function template arguments. Drop them to match
206 // MSVC.
207 StringRef DisplayName = SP->getDisplayName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000208
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000209 const DIScope *Scope = SP->getScope().resolve();
210 TypeIndex TI;
211 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
212 // If the scope is a DICompositeType, then this must be a method. Member
213 // function types take some special handling, and require access to the
214 // subprogram.
215 TypeIndex ClassType = getTypeIndex(Class);
216 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
217 DisplayName);
218 TI = TypeTable.writeMemberFuncId(MFuncId);
219 } else {
220 // Otherwise, this must be a free function.
221 TypeIndex ParentScope = getScopeIndex(Scope);
222 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
223 TI = TypeTable.writeFuncId(FuncId);
224 }
225
226 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000227}
228
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000229TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
230 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000231 // Always use the method declaration as the key for the function type. The
232 // method declaration contains the this adjustment.
233 if (SP->getDeclaration())
234 SP = SP->getDeclaration();
235 assert(!SP->getDeclaration() && "should use declaration as key");
236
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000237 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
238 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000239 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000240 if (I != TypeIndices.end())
241 return I->second;
242
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000243 // Make sure complete type info for the class is emitted *after* the member
244 // function type, as the complete class type is likely to reference this
245 // member function type.
246 TypeLoweringScope S(*this);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000247 TypeIndex TI =
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000248 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000249 return recordTypeIndexForDINode(SP, TI, Class);
250}
251
252TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, TypeIndex TI,
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000253 const DIType *ClassTy) {
254 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000255 (void)InsertResult;
256 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000257 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000258}
259
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000260unsigned CodeViewDebug::getPointerSizeInBytes() {
261 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
262}
263
Reid Kleckner876330d2016-02-12 21:48:30 +0000264void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
265 const DILocation *InlinedAt) {
266 if (InlinedAt) {
267 // This variable was inlined. Associate it with the InlineSite.
268 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
269 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
270 Site.InlinedLocals.emplace_back(Var);
271 } else {
272 // This variable goes in the main ProcSym.
273 CurFn->Locals.emplace_back(Var);
274 }
275}
276
Reid Kleckner829365a2016-02-11 19:41:47 +0000277static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
278 const DILocation *Loc) {
279 auto B = Locs.begin(), E = Locs.end();
280 if (std::find(B, E, Loc) == E)
281 Locs.push_back(Loc);
282}
283
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000284void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000285 const MachineFunction *MF) {
286 // Skip this instruction if it has the same location as the previous one.
287 if (DL == CurFn->LastLoc)
288 return;
289
290 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000291 if (!Scope)
292 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000293
David Majnemerc3340db2016-01-13 01:05:23 +0000294 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000295 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
296 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
297 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000298 return;
299
Reid Kleckner2214ed82016-01-29 00:49:42 +0000300 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
301 if (CI.getStartColumn() != DL.getCol())
302 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000303
Reid Kleckner2214ed82016-01-29 00:49:42 +0000304 if (!CurFn->HaveLineInfo)
305 CurFn->HaveLineInfo = true;
306 unsigned FileId = 0;
307 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
308 FileId = CurFn->LastFileId;
309 else
310 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
311 CurFn->LastLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000312
313 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000314 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000315 const DILocation *Loc = DL.get();
316
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000317 // If this location was actually inlined from somewhere else, give it the ID
318 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000319 FuncId =
320 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000321
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000322 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000323 bool FirstLoc = true;
324 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000325 InlineSite &Site =
326 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000327 if (!FirstLoc)
328 addLocIfNotPresent(Site.ChildSites, Loc);
329 FirstLoc = false;
330 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000331 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000332 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000333 }
334
Reid Klecknerdac21b42016-02-03 21:15:48 +0000335 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
336 /*PrologueEnd=*/false,
337 /*IsStmt=*/false, DL->getFilename());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000338}
339
Reid Kleckner5d122f82016-05-25 23:16:12 +0000340void CodeViewDebug::emitCodeViewMagicVersion() {
341 OS.EmitValueToAlignment(4);
342 OS.AddComment("Debug section magic");
343 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
344}
345
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000346void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000347 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000348 return;
349
350 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000351
352 // The COFF .debug$S section consists of several subsections, each starting
353 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
354 // of the payload followed by the payload itself. The subsections are 4-byte
355 // aligned.
356
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000357 // Use the generic .debug$S section, and make a subsection for all the inlined
358 // subprograms.
359 switchToDebugSectionForSymbol(nullptr);
Reid Kleckner5d122f82016-05-25 23:16:12 +0000360 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000361
Reid Kleckner2214ed82016-01-29 00:49:42 +0000362 // Emit per-function debug information.
363 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000364 if (!P.first->isDeclarationForLinker())
365 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000366
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000367 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000368 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000369 emitDebugInfoForGlobals();
370
Hans Wennborgb510b452016-06-23 16:33:53 +0000371 // Emit retained types.
372 emitDebugInfoForRetainedTypes();
373
Reid Kleckner5d122f82016-05-25 23:16:12 +0000374 // Switch back to the generic .debug$S section after potentially processing
375 // comdat symbol sections.
376 switchToDebugSectionForSymbol(nullptr);
377
David Majnemer3128b102016-06-15 18:00:01 +0000378 // Emit UDT records for any types used by global variables.
379 if (!GlobalUDTs.empty()) {
380 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
381 emitDebugInfoForUDTs(GlobalUDTs);
382 endCVSubsection(SymbolsEnd);
383 }
384
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000385 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000386 OS.AddComment("File index to string table offset subsection");
387 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000388
389 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000390 OS.AddComment("String table");
391 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000392
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000393 // Emit type information last, so that any types we translate while emitting
394 // function info are included.
395 emitTypeInformation();
396
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000397 clear();
398}
399
David Majnemerb9456a52016-03-14 05:15:09 +0000400static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
401 // Microsoft's linker seems to have trouble with symbol names longer than
402 // 0xffd8 bytes.
403 S = S.substr(0, 0xffd8);
404 SmallString<32> NullTerminatedString(S);
405 NullTerminatedString.push_back('\0');
406 OS.EmitBytes(NullTerminatedString);
407}
408
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000409void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000410 // Do nothing if we have no debug info or if no non-trivial types were emitted
411 // to TypeTable during codegen.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000412 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
Reid Klecknerfbd77872016-03-18 18:54:32 +0000413 if (!CU_Nodes)
414 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000415 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000416 return;
417
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000418 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000419 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000420 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000421
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000422 SmallString<8> CommentPrefix;
423 if (OS.isVerboseAsm()) {
424 CommentPrefix += '\t';
425 CommentPrefix += Asm->MAI->getCommentString();
426 CommentPrefix += ' ';
427 }
428
429 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
Reid Kleckner2280f932016-05-23 20:23:46 +0000430 TypeTable.ForEachRecord(
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000431 [&](TypeIndex Index, StringRef Record) {
432 if (OS.isVerboseAsm()) {
433 // Emit a block comment describing the type record for readability.
434 SmallString<512> CommentBlock;
435 raw_svector_ostream CommentOS(CommentBlock);
436 ScopedPrinter SP(CommentOS);
437 SP.setPrefix(CommentPrefix);
438 CVTD.setPrinter(&SP);
Reid Klecknerc92e9462016-07-01 18:05:56 +0000439 Error E = CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
440 if (E) {
441 logAllUnhandledErrors(std::move(E), errs(), "error: ");
442 llvm_unreachable("produced malformed type record");
443 }
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000444 // emitRawComment will insert its own tab and comment string before
445 // the first line, so strip off our first one. It also prints its own
446 // newline.
447 OS.emitRawComment(
448 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Reid Klecknerc92e9462016-07-01 18:05:56 +0000449 } else {
450#ifndef NDEBUG
451 // Assert that the type data is valid even if we aren't dumping
452 // comments. The MSVC linker doesn't do much type record validation,
453 // so the first link of an invalid type record can succeed while
454 // subsequent links will fail with LNK1285.
455 ByteStream<> Stream({Record.bytes_begin(), Record.bytes_end()});
456 CVTypeArray Types;
457 StreamReader Reader(Stream);
458 Error E = Reader.readArray(Types, Reader.getLength());
459 if (!E) {
460 TypeVisitorCallbacks C;
461 E = CVTypeVisitor(C).visitTypeStream(Types);
462 }
463 if (E) {
464 logAllUnhandledErrors(std::move(E), errs(), "error: ");
465 llvm_unreachable("produced malformed type record");
466 }
467#endif
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000468 }
469 OS.EmitBinaryData(Record);
Reid Kleckner2280f932016-05-23 20:23:46 +0000470 });
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000471}
472
Reid Kleckner5d122f82016-05-25 23:16:12 +0000473void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000474 if (InlinedSubprograms.empty())
475 return;
476
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000477 OS.AddComment("Inlinee lines subsection");
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000478 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000479
480 // We don't provide any extra file info.
481 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000482 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000483 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
484
485 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000486 assert(TypeIndices.count({SP, nullptr}));
487 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000488
David Majnemer30579ec2016-02-02 23:18:23 +0000489 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000490 unsigned FileId = maybeRecordFile(SP->getFile());
491 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
492 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000493 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000494 // The filechecksum table uses 8 byte entries for now, and file ids start at
495 // 1.
496 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000497 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000498 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000499 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000500 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000501 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000502 OS.EmitIntValue(SP->getLine(), 4);
503 }
504
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000505 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000506}
507
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000508void CodeViewDebug::collectInlineSiteChildren(
509 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
510 const InlineSite &Site) {
511 for (const DILocation *ChildSiteLoc : Site.ChildSites) {
512 auto I = FI.InlineSites.find(ChildSiteLoc);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000513 const InlineSite &ChildSite = I->second;
514 Children.push_back(ChildSite.SiteFuncId);
515 collectInlineSiteChildren(Children, FI, ChildSite);
516 }
517}
518
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000519void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
520 const DILocation *InlinedAt,
521 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000522 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
523 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000524
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000525 assert(TypeIndices.count({Site.Inlinee, nullptr}));
526 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000527
528 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000529 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000530 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000531 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000532 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000533 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000534
Reid Klecknerdac21b42016-02-03 21:15:48 +0000535 OS.AddComment("PtrParent");
536 OS.EmitIntValue(0, 4);
537 OS.AddComment("PtrEnd");
538 OS.EmitIntValue(0, 4);
539 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000540 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000541
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000542 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
543 unsigned StartLineNum = Site.Inlinee->getLine();
544 SmallVector<unsigned, 3> SecondaryFuncIds;
545 collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
546
547 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
David Majnemerc9911f22016-02-02 19:22:34 +0000548 FI.Begin, FI.End, SecondaryFuncIds);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000549
550 OS.EmitLabel(InlineEnd);
551
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000552 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000553
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000554 // Recurse on child inlined call sites before closing the scope.
555 for (const DILocation *ChildSite : Site.ChildSites) {
556 auto I = FI.InlineSites.find(ChildSite);
557 assert(I != FI.InlineSites.end() &&
558 "child site not in function inline site map");
559 emitInlinedCallSite(FI, ChildSite, I->second);
560 }
561
562 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000563 OS.AddComment("Record length");
564 OS.EmitIntValue(2, 2); // RecordLength
565 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000566 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000567}
568
Reid Kleckner5d122f82016-05-25 23:16:12 +0000569void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
570 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
571 // comdat key. A section may be comdat because of -ffunction-sections or
572 // because it is comdat in the IR.
573 MCSectionCOFF *GVSec =
574 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
575 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
576
577 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
578 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
579 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
580
581 OS.SwitchSection(DebugSec);
582
583 // Emit the magic version number if this is the first time we've switched to
584 // this section.
585 if (ComdatDebugSections.insert(DebugSec).second)
586 emitCodeViewMagicVersion();
587}
588
Reid Kleckner2214ed82016-01-29 00:49:42 +0000589void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
590 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000591 // For each function there is a separate subsection
592 // which holds the PC to file:line table.
593 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000594 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000595
Reid Kleckner5d122f82016-05-25 23:16:12 +0000596 // Switch to the to a comdat section, if appropriate.
597 switchToDebugSectionForSymbol(Fn);
598
Reid Klecknerac945e22016-06-17 16:11:20 +0000599 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000600 auto *SP = GV->getSubprogram();
601 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000602
603 // If we have a display name, build the fully qualified name by walking the
604 // chain of scopes.
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000605 if (SP != nullptr && !SP->getDisplayName().empty())
606 FuncName =
607 getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000608
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000609 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000610 if (FuncName.empty())
611 FuncName = GlobalValue::getRealLinkageName(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000612
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000613 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000614 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000615 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000616 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000617 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
618 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000619 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000620 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000621 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000622
Reid Klecknerdac21b42016-02-03 21:15:48 +0000623 OS.AddComment("Record kind: S_GPROC32_ID");
Zachary Turner63a28462016-05-17 23:50:21 +0000624 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000625
David Majnemer30579ec2016-02-02 23:18:23 +0000626 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000627 OS.AddComment("PtrParent");
628 OS.EmitIntValue(0, 4);
629 OS.AddComment("PtrEnd");
630 OS.EmitIntValue(0, 4);
631 OS.AddComment("PtrNext");
632 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000633 // This is the important bit that tells the debugger where the function
634 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000635 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000636 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000637 OS.AddComment("Offset after prologue");
638 OS.EmitIntValue(0, 4);
639 OS.AddComment("Offset before epilogue");
640 OS.EmitIntValue(0, 4);
641 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000642 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000643 OS.AddComment("Function section relative address");
644 OS.EmitCOFFSecRel32(Fn);
645 OS.AddComment("Function section index");
646 OS.EmitCOFFSectionIndex(Fn);
647 OS.AddComment("Flags");
648 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000649 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000650 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000651 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000652 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000653 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000654
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000655 emitLocalVariableList(FI.Locals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000656
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000657 // Emit inlined call site information. Only emit functions inlined directly
658 // into the parent function. We'll emit the other sites recursively as part
659 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000660 for (const DILocation *InlinedAt : FI.ChildSites) {
661 auto I = FI.InlineSites.find(InlinedAt);
662 assert(I != FI.InlineSites.end() &&
663 "child site not in function inline site map");
664 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000665 }
666
David Majnemer3128b102016-06-15 18:00:01 +0000667 if (SP != nullptr)
668 emitDebugInfoForUDTs(LocalUDTs);
669
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000670 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000671 OS.AddComment("Record length");
672 OS.EmitIntValue(0x0002, 2);
673 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000674 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000675 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000676 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000677
Reid Kleckner2214ed82016-01-29 00:49:42 +0000678 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000679 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000680}
681
Reid Kleckner876330d2016-02-12 21:48:30 +0000682CodeViewDebug::LocalVarDefRange
683CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
684 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000685 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000686 DR.DataOffset = Offset;
687 assert(DR.DataOffset == Offset && "truncation");
688 DR.StructOffset = 0;
689 DR.CVRegister = CVRegister;
690 return DR;
691}
692
693CodeViewDebug::LocalVarDefRange
694CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
695 LocalVarDefRange DR;
696 DR.InMemory = 0;
697 DR.DataOffset = 0;
698 DR.StructOffset = 0;
699 DR.CVRegister = CVRegister;
700 return DR;
701}
702
703void CodeViewDebug::collectVariableInfoFromMMITable(
704 DenseSet<InlinedVariable> &Processed) {
705 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
706 const TargetFrameLowering *TFI = TSI.getFrameLowering();
707 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
708
709 for (const MachineModuleInfo::VariableDbgInfo &VI :
710 MMI->getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000711 if (!VI.Var)
712 continue;
713 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
714 "Expected inlined-at fields to agree");
715
Reid Kleckner876330d2016-02-12 21:48:30 +0000716 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000717 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
718
719 // If variable scope is not found then skip this variable.
720 if (!Scope)
721 continue;
722
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000723 // Get the frame register used and the offset.
724 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000725 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
726 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000727
728 // Calculate the label ranges.
Reid Kleckner876330d2016-02-12 21:48:30 +0000729 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000730 for (const InsnRange &Range : Scope->getRanges()) {
731 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
732 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000733 End = End ? End : Asm->getFunctionEnd();
734 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000735 }
736
Reid Kleckner876330d2016-02-12 21:48:30 +0000737 LocalVariable Var;
738 Var.DIVar = VI.Var;
739 Var.DefRanges.emplace_back(std::move(DefRange));
740 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
741 }
742}
743
744void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
745 DenseSet<InlinedVariable> Processed;
746 // Grab the variable info that was squirreled away in the MMI side-table.
747 collectVariableInfoFromMMITable(Processed);
748
749 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
750
751 for (const auto &I : DbgValues) {
752 InlinedVariable IV = I.first;
753 if (Processed.count(IV))
754 continue;
755 const DILocalVariable *DIVar = IV.first;
756 const DILocation *InlinedAt = IV.second;
757
758 // Instruction ranges, specifying where IV is accessible.
759 const auto &Ranges = I.second;
760
761 LexicalScope *Scope = nullptr;
762 if (InlinedAt)
763 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
764 else
765 Scope = LScopes.findLexicalScope(DIVar->getScope());
766 // If variable scope is not found then skip this variable.
767 if (!Scope)
768 continue;
769
770 LocalVariable Var;
771 Var.DIVar = DIVar;
772
773 // Calculate the definition ranges.
774 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
775 const InsnRange &Range = *I;
776 const MachineInstr *DVInst = Range.first;
777 assert(DVInst->isDebugValue() && "Invalid History entry");
778 const DIExpression *DIExpr = DVInst->getDebugExpression();
779
780 // Bail if there is a complex DWARF expression for now.
781 if (DIExpr && DIExpr->getNumElements() > 0)
782 continue;
783
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000784 // Bail if operand 0 is not a valid register. This means the variable is a
785 // simple constant, or is described by a complex expression.
786 // FIXME: Find a way to represent constant variables, since they are
787 // relatively common.
788 unsigned Reg =
789 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
790 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000791 continue;
792
Reid Kleckner876330d2016-02-12 21:48:30 +0000793 // Handle the two cases we can handle: indirect in memory and in register.
794 bool IsIndirect = DVInst->getOperand(1).isImm();
795 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
796 {
797 LocalVarDefRange DefRange;
798 if (IsIndirect) {
799 int64_t Offset = DVInst->getOperand(1).getImm();
800 DefRange = createDefRangeMem(CVReg, Offset);
801 } else {
802 DefRange = createDefRangeReg(CVReg);
803 }
804 if (Var.DefRanges.empty() ||
805 Var.DefRanges.back().isDifferentLocation(DefRange)) {
806 Var.DefRanges.emplace_back(std::move(DefRange));
807 }
808 }
809
810 // Compute the label range.
811 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
812 const MCSymbol *End = getLabelAfterInsn(Range.second);
813 if (!End) {
814 if (std::next(I) != E)
815 End = getLabelBeforeInsn(std::next(I)->first);
816 else
817 End = Asm->getFunctionEnd();
818 }
819
820 // If the last range end is our begin, just extend the last range.
821 // Otherwise make a new range.
822 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
823 Var.DefRanges.back().Ranges;
824 if (!Ranges.empty() && Ranges.back().second == Begin)
825 Ranges.back().second = End;
826 else
827 Ranges.emplace_back(Begin, End);
828
829 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000830 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000831
832 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000833 }
834}
835
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000836void CodeViewDebug::beginFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000837 assert(!CurFn && "Can't process two functions at once!");
838
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000839 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000840 return;
841
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000842 DebugHandlerBase::beginFunction(MF);
843
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000844 const Function *GV = MF->getFunction();
845 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000846 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +0000847 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000848 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000849
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000850 // Find the end of the function prolog. First known non-DBG_VALUE and
851 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000852 // FIXME: is there a simpler a way to do this? Can we just search
853 // for the first instruction of the function, not the last of the prolog?
854 DebugLoc PrologEndLoc;
855 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000856 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000857 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000858 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
859 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000860 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000861 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000862 } else if (!MI.isDebugValue()) {
863 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000864 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000865 }
866 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000867
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000868 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000869 if (PrologEndLoc && !EmptyPrologue) {
870 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000871 maybeRecordLocation(FnStartDL, MF);
872 }
873}
874
Hans Wennborg4b63a982016-06-23 22:57:25 +0000875void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
Reid Klecknerad56ea32016-07-01 22:24:51 +0000876 // Don't record empty UDTs.
877 if (Ty->getName().empty())
878 return;
879
Hans Wennborg4b63a982016-06-23 22:57:25 +0000880 SmallVector<StringRef, 5> QualifiedNameComponents;
881 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
882 Ty->getScope().resolve(), QualifiedNameComponents);
883
884 std::string FullyQualifiedName =
885 getQualifiedName(QualifiedNameComponents, Ty->getName());
886
887 if (ClosestSubprogram == nullptr)
888 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
889 else if (ClosestSubprogram == CurrentSubprogram)
890 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
891
892 // TODO: What if the ClosestSubprogram is neither null or the current
893 // subprogram? Currently, the UDT just gets dropped on the floor.
894 //
895 // The current behavior is not desirable. To get maximal fidelity, we would
896 // need to perform all type translation before beginning emission of .debug$S
897 // and then make LocalUDTs a member of FunctionInfo
898}
899
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000900TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000901 // Generic dispatch for lowering an unknown type.
902 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000903 case dwarf::DW_TAG_array_type:
904 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +0000905 case dwarf::DW_TAG_typedef:
906 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000907 case dwarf::DW_TAG_base_type:
908 return lowerTypeBasic(cast<DIBasicType>(Ty));
909 case dwarf::DW_TAG_pointer_type:
910 case dwarf::DW_TAG_reference_type:
911 case dwarf::DW_TAG_rvalue_reference_type:
912 return lowerTypePointer(cast<DIDerivedType>(Ty));
913 case dwarf::DW_TAG_ptr_to_member_type:
914 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
915 case dwarf::DW_TAG_const_type:
916 case dwarf::DW_TAG_volatile_type:
917 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +0000918 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000919 if (ClassTy) {
920 // The member function type of a member function pointer has no
921 // ThisAdjustment.
922 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
923 /*ThisAdjustment=*/0);
924 }
David Majnemer75c3ebf2016-06-02 17:13:53 +0000925 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +0000926 case dwarf::DW_TAG_enumeration_type:
927 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +0000928 case dwarf::DW_TAG_class_type:
929 case dwarf::DW_TAG_structure_type:
930 return lowerTypeClass(cast<DICompositeType>(Ty));
931 case dwarf::DW_TAG_union_type:
932 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000933 default:
934 // Use the null type index.
935 return TypeIndex();
936 }
937}
938
David Majnemerd065e232016-06-02 06:21:37 +0000939TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +0000940 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
941 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +0000942 StringRef TypeName = Ty->getName();
943
Hans Wennborg4b63a982016-06-23 22:57:25 +0000944 addToUDTs(Ty, UnderlyingTypeIndex);
David Majnemer3128b102016-06-15 18:00:01 +0000945
David Majnemerd065e232016-06-02 06:21:37 +0000946 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +0000947 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +0000948 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +0000949 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +0000950 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +0000951 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +0000952
David Majnemerd065e232016-06-02 06:21:37 +0000953 return UnderlyingTypeIndex;
954}
955
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000956TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
957 DITypeRef ElementTypeRef = Ty->getBaseType();
958 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
959 // IndexType is size_t, which depends on the bitness of the target.
960 TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
961 ? TypeIndex(SimpleTypeKind::UInt64Quad)
962 : TypeIndex(SimpleTypeKind::UInt32Long);
Nico Weberd8db1e12016-06-26 15:10:34 +0000963 uint64_t Size = Ty->getSizeInBits() / 8;
964 ArrayRecord Record(ElementTypeIndex, IndexType, Size, Ty->getName());
965 return TypeTable.writeArray(Record);
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000966}
967
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000968TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
969 TypeIndex Index;
970 dwarf::TypeKind Kind;
971 uint32_t ByteSize;
972
973 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +0000974 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000975
976 SimpleTypeKind STK = SimpleTypeKind::None;
977 switch (Kind) {
978 case dwarf::DW_ATE_address:
979 // FIXME: Translate
980 break;
981 case dwarf::DW_ATE_boolean:
982 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000983 case 1: STK = SimpleTypeKind::Boolean8; break;
984 case 2: STK = SimpleTypeKind::Boolean16; break;
985 case 4: STK = SimpleTypeKind::Boolean32; break;
986 case 8: STK = SimpleTypeKind::Boolean64; break;
987 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000988 }
989 break;
990 case dwarf::DW_ATE_complex_float:
991 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000992 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000993 case 4: STK = SimpleTypeKind::Complex32; break;
994 case 8: STK = SimpleTypeKind::Complex64; break;
995 case 10: STK = SimpleTypeKind::Complex80; break;
996 case 16: STK = SimpleTypeKind::Complex128; break;
997 }
998 break;
999 case dwarf::DW_ATE_float:
1000 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001001 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001002 case 4: STK = SimpleTypeKind::Float32; break;
1003 case 6: STK = SimpleTypeKind::Float48; break;
1004 case 8: STK = SimpleTypeKind::Float64; break;
1005 case 10: STK = SimpleTypeKind::Float80; break;
1006 case 16: STK = SimpleTypeKind::Float128; break;
1007 }
1008 break;
1009 case dwarf::DW_ATE_signed:
1010 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001011 case 1: STK = SimpleTypeKind::SByte; break;
1012 case 2: STK = SimpleTypeKind::Int16Short; break;
1013 case 4: STK = SimpleTypeKind::Int32; break;
1014 case 8: STK = SimpleTypeKind::Int64Quad; break;
1015 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001016 }
1017 break;
1018 case dwarf::DW_ATE_unsigned:
1019 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001020 case 1: STK = SimpleTypeKind::Byte; break;
1021 case 2: STK = SimpleTypeKind::UInt16Short; break;
1022 case 4: STK = SimpleTypeKind::UInt32; break;
1023 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1024 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001025 }
1026 break;
1027 case dwarf::DW_ATE_UTF:
1028 switch (ByteSize) {
1029 case 2: STK = SimpleTypeKind::Character16; break;
1030 case 4: STK = SimpleTypeKind::Character32; break;
1031 }
1032 break;
1033 case dwarf::DW_ATE_signed_char:
1034 if (ByteSize == 1)
1035 STK = SimpleTypeKind::SignedCharacter;
1036 break;
1037 case dwarf::DW_ATE_unsigned_char:
1038 if (ByteSize == 1)
1039 STK = SimpleTypeKind::UnsignedCharacter;
1040 break;
1041 default:
1042 break;
1043 }
1044
1045 // Apply some fixups based on the source-level type name.
1046 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1047 STK = SimpleTypeKind::Int32Long;
1048 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1049 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001050 if (STK == SimpleTypeKind::UInt16Short &&
1051 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001052 STK = SimpleTypeKind::WideCharacter;
1053 if ((STK == SimpleTypeKind::SignedCharacter ||
1054 STK == SimpleTypeKind::UnsignedCharacter) &&
1055 Ty->getName() == "char")
1056 STK = SimpleTypeKind::NarrowCharacter;
1057
1058 return TypeIndex(STK);
1059}
1060
1061TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1062 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1063
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001064 // While processing the type being pointed to it is possible we already
1065 // created this pointer type. If so, we check here and return the existing
1066 // pointer type.
1067 auto I = TypeIndices.find({Ty, nullptr});
1068 if (I != TypeIndices.end())
1069 return I->second;
1070
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001071 // Pointers to simple types can use SimpleTypeMode, rather than having a
1072 // dedicated pointer type record.
1073 if (PointeeTI.isSimple() &&
1074 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1075 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1076 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1077 ? SimpleTypeMode::NearPointer64
1078 : SimpleTypeMode::NearPointer32;
1079 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1080 }
1081
1082 PointerKind PK =
1083 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1084 PointerMode PM = PointerMode::Pointer;
1085 switch (Ty->getTag()) {
1086 default: llvm_unreachable("not a pointer tag type");
1087 case dwarf::DW_TAG_pointer_type:
1088 PM = PointerMode::Pointer;
1089 break;
1090 case dwarf::DW_TAG_reference_type:
1091 PM = PointerMode::LValueReference;
1092 break;
1093 case dwarf::DW_TAG_rvalue_reference_type:
1094 PM = PointerMode::RValueReference;
1095 break;
1096 }
1097 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1098 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1099 // do.
1100 PointerOptions PO = PointerOptions::None;
1101 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1102 return TypeTable.writePointer(PR);
1103}
1104
Reid Kleckner6fa15462016-06-17 22:14:39 +00001105static PointerToMemberRepresentation
1106translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1107 // SizeInBytes being zero generally implies that the member pointer type was
1108 // incomplete, which can happen if it is part of a function prototype. In this
1109 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001110 if (IsPMF) {
1111 switch (Flags & DINode::FlagPtrToMemberRep) {
1112 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001113 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1114 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001115 case DINode::FlagSingleInheritance:
1116 return PointerToMemberRepresentation::SingleInheritanceFunction;
1117 case DINode::FlagMultipleInheritance:
1118 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1119 case DINode::FlagVirtualInheritance:
1120 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1121 }
1122 } else {
1123 switch (Flags & DINode::FlagPtrToMemberRep) {
1124 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001125 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1126 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001127 case DINode::FlagSingleInheritance:
1128 return PointerToMemberRepresentation::SingleInheritanceData;
1129 case DINode::FlagMultipleInheritance:
1130 return PointerToMemberRepresentation::MultipleInheritanceData;
1131 case DINode::FlagVirtualInheritance:
1132 return PointerToMemberRepresentation::VirtualInheritanceData;
1133 }
1134 }
1135 llvm_unreachable("invalid ptr to member representation");
1136}
1137
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001138TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1139 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1140 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001141 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001142 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
1143 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001144 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1145 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1146 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001147 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001148 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1149 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1150 MemberPointerInfo MPI(
1151 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001152 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001153 return TypeTable.writePointer(PR);
1154}
1155
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001156/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1157/// have a translation, use the NearC convention.
1158static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1159 switch (DwarfCC) {
1160 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1161 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1162 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1163 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1164 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1165 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1166 }
1167 return CallingConvention::NearC;
1168}
1169
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001170TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1171 ModifierOptions Mods = ModifierOptions::None;
1172 bool IsModifier = true;
1173 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001174 while (IsModifier && BaseTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001175 // FIXME: Need to add DWARF tag for __unaligned.
1176 switch (BaseTy->getTag()) {
1177 case dwarf::DW_TAG_const_type:
1178 Mods |= ModifierOptions::Const;
1179 break;
1180 case dwarf::DW_TAG_volatile_type:
1181 Mods |= ModifierOptions::Volatile;
1182 break;
1183 default:
1184 IsModifier = false;
1185 break;
1186 }
1187 if (IsModifier)
1188 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1189 }
1190 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001191
1192 // While processing the type being pointed to, it is possible we already
1193 // created this modifier type. If so, we check here and return the existing
1194 // modifier type.
1195 auto I = TypeIndices.find({Ty, nullptr});
1196 if (I != TypeIndices.end())
1197 return I->second;
1198
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001199 ModifierRecord MR(ModifiedTI, Mods);
1200 return TypeTable.writeModifier(MR);
1201}
1202
David Majnemer75c3ebf2016-06-02 17:13:53 +00001203TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1204 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1205 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1206 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1207
1208 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1209 ArrayRef<TypeIndex> ArgTypeIndices = None;
1210 if (!ReturnAndArgTypeIndices.empty()) {
1211 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1212 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1213 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1214 }
1215
1216 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1217 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
1218
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001219 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1220
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001221 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1222 ArgTypeIndices.size(), ArgListIndex);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001223 return TypeTable.writeProcedure(Procedure);
1224}
1225
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001226TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001227 const DIType *ClassTy,
1228 int ThisAdjustment) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001229 // Lower the containing class type.
1230 TypeIndex ClassType = getTypeIndex(ClassTy);
1231
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001232 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1233 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1234 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1235
1236 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1237 ArrayRef<TypeIndex> ArgTypeIndices = None;
1238 if (!ReturnAndArgTypeIndices.empty()) {
1239 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1240 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1241 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1242 }
1243 TypeIndex ThisTypeIndex = TypeIndex::Void();
1244 if (!ArgTypeIndices.empty()) {
1245 ThisTypeIndex = ArgTypeIndices.front();
1246 ArgTypeIndices = ArgTypeIndices.drop_front();
1247 }
1248
1249 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1250 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
1251
1252 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1253
1254 // TODO: Need to use the correct values for:
1255 // FunctionOptions
1256 // ThisPointerAdjustment.
1257 TypeIndex TI = TypeTable.writeMemberFunction(MemberFunctionRecord(
1258 ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001259 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001260
1261 return TI;
1262}
1263
1264static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1265 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001266 case DINode::FlagPrivate: return MemberAccess::Private;
1267 case DINode::FlagPublic: return MemberAccess::Public;
1268 case DINode::FlagProtected: return MemberAccess::Protected;
1269 case 0:
1270 // If there was no explicit access control, provide the default for the tag.
1271 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1272 : MemberAccess::Public;
1273 }
1274 llvm_unreachable("access flags are exclusive");
1275}
1276
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001277static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1278 if (SP->isArtificial())
1279 return MethodOptions::CompilerGenerated;
1280
1281 // FIXME: Handle other MethodOptions.
1282
1283 return MethodOptions::None;
1284}
1285
1286static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1287 bool Introduced) {
1288 switch (SP->getVirtuality()) {
1289 case dwarf::DW_VIRTUALITY_none:
1290 break;
1291 case dwarf::DW_VIRTUALITY_virtual:
1292 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1293 case dwarf::DW_VIRTUALITY_pure_virtual:
1294 return Introduced ? MethodKind::PureIntroducingVirtual
1295 : MethodKind::PureVirtual;
1296 default:
1297 llvm_unreachable("unhandled virtuality case");
1298 }
1299
1300 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1301
1302 return MethodKind::Vanilla;
1303}
1304
Reid Klecknera8d57402016-06-03 15:58:20 +00001305static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1306 switch (Ty->getTag()) {
1307 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1308 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1309 }
1310 llvm_unreachable("unexpected tag");
1311}
1312
1313/// Return the HasUniqueName option if it should be present in ClassOptions, or
1314/// None otherwise.
1315static ClassOptions getRecordUniqueNameOption(const DICompositeType *Ty) {
1316 // MSVC always sets this flag now, even for local types. Clang doesn't always
1317 // appear to give every type a linkage name, which may be problematic for us.
1318 // FIXME: Investigate the consequences of not following them here.
1319 return !Ty->getIdentifier().empty() ? ClassOptions::HasUniqueName
1320 : ClassOptions::None;
1321}
1322
David Majnemer979cb882016-06-16 21:32:16 +00001323TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
1324 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1325 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001326 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001327
David Majnemerda9548f2016-06-17 16:13:21 +00001328 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001329 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001330 } else {
1331 FieldListRecordBuilder Fields;
1332 for (const DINode *Element : Ty->getElements()) {
1333 // We assume that the frontend provides all members in source declaration
1334 // order, which is what MSVC does.
1335 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
1336 Fields.writeEnumerator(EnumeratorRecord(
1337 MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()),
1338 Enumerator->getName()));
1339 EnumeratorCount++;
1340 }
1341 }
1342 FTI = TypeTable.writeFieldList(Fields);
1343 }
David Majnemer979cb882016-06-16 21:32:16 +00001344
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001345 std::string FullName =
1346 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1347
1348 return TypeTable.writeEnum(EnumRecord(EnumeratorCount, CO, FTI, FullName,
David Majnemer979cb882016-06-16 21:32:16 +00001349 Ty->getIdentifier(),
1350 getTypeIndex(Ty->getBaseType())));
1351}
1352
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001353//===----------------------------------------------------------------------===//
1354// ClassInfo
1355//===----------------------------------------------------------------------===//
1356
1357struct llvm::ClassInfo {
1358 struct MemberInfo {
1359 const DIDerivedType *MemberTypeNode;
1360 unsigned BaseOffset;
1361 };
1362 // [MemberInfo]
1363 typedef std::vector<MemberInfo> MemberList;
1364
Reid Kleckner156a7232016-06-22 18:31:14 +00001365 typedef TinyPtrVector<const DISubprogram *> MethodsList;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001366 // MethodName -> MethodsList
1367 typedef MapVector<MDString *, MethodsList> MethodsMap;
1368
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001369 /// Base classes.
1370 std::vector<const DIDerivedType *> Inheritance;
1371
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001372 /// Direct members.
1373 MemberList Members;
1374 // Direct overloaded methods gathered by name.
1375 MethodsMap Methods;
1376};
1377
1378void CodeViewDebug::clear() {
1379 assert(CurFn == nullptr);
1380 FileIdMap.clear();
1381 FnDebugInfo.clear();
1382 FileToFilepathMap.clear();
1383 LocalUDTs.clear();
1384 GlobalUDTs.clear();
1385 TypeIndices.clear();
1386 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001387}
1388
1389void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1390 const DIDerivedType *DDTy) {
1391 if (!DDTy->getName().empty()) {
1392 Info.Members.push_back({DDTy, 0});
1393 return;
1394 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001395 // An unnamed member must represent a nested struct or union. Add all the
1396 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001397 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001398 unsigned Offset = DDTy->getOffsetInBits() / 8;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001399 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001400 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001401 ClassInfo NestedInfo = collectClassInfo(DCTy);
1402 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001403 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001404 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001405}
1406
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001407ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1408 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001409 // Add elements to structure type.
1410 DINodeArray Elements = Ty->getElements();
1411 for (auto *Element : Elements) {
1412 // We assume that the frontend provides all members in source declaration
1413 // order, which is what MSVC does.
1414 if (!Element)
1415 continue;
1416 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001417 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001418 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001419 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001420 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001421 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1422 Info.Inheritance.push_back(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001423 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1424 // Ignore friend members. It appears that MSVC emitted info about
1425 // friends in the past, but modern versions do not.
1426 }
1427 // FIXME: Get Clang to emit function virtual table here and handle it.
1428 // FIXME: Get clang to emit nested types here and do something with
1429 // them.
1430 }
1431 // Skip other unrecognized kinds of elements.
1432 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001433 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001434}
1435
Reid Klecknera8d57402016-06-03 15:58:20 +00001436TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1437 // First, construct the forward decl. Don't look into Ty to compute the
1438 // forward decl options, since it might not be available in all TUs.
1439 TypeRecordKind Kind = getRecordKind(Ty);
1440 ClassOptions CO =
1441 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001442 std::string FullName =
1443 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
Reid Klecknera8d57402016-06-03 15:58:20 +00001444 TypeIndex FwdDeclTI = TypeTable.writeClass(ClassRecord(
1445 Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001446 TypeIndex(), TypeIndex(), 0, FullName, Ty->getIdentifier()));
Reid Kleckner643dd832016-06-22 17:15:28 +00001447 if (!Ty->isForwardDecl())
1448 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001449 return FwdDeclTI;
1450}
1451
1452TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1453 // Construct the field list and complete type record.
1454 TypeRecordKind Kind = getRecordKind(Ty);
1455 // FIXME: Other ClassOptions, like ContainsNestedClass and NestedClass.
1456 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001457 TypeIndex FieldTI;
1458 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001459 unsigned FieldCount;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001460 std::tie(FieldTI, VShapeTI, FieldCount) = lowerRecordFieldList(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001461
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001462 std::string FullName =
1463 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1464
Reid Klecknera8d57402016-06-03 15:58:20 +00001465 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001466
1467 TypeIndex ClassTI = TypeTable.writeClass(ClassRecord(
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001468 Kind, FieldCount, CO, HfaKind::None, WindowsRTClassKind::None, FieldTI,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001469 TypeIndex(), VShapeTI, SizeInBytes, FullName, Ty->getIdentifier()));
Hans Wennborg9a519a02016-06-22 21:22:13 +00001470
1471 TypeTable.writeUdtSourceLine(UdtSourceLineRecord(
1472 ClassTI, TypeTable.writeStringId(StringIdRecord(
1473 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1474 Ty->getLine()));
1475
Hans Wennborg4b63a982016-06-23 22:57:25 +00001476 addToUDTs(Ty, ClassTI);
1477
Hans Wennborg9a519a02016-06-22 21:22:13 +00001478 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001479}
1480
1481TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1482 ClassOptions CO =
1483 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001484 std::string FullName =
1485 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
Reid Klecknera8d57402016-06-03 15:58:20 +00001486 TypeIndex FwdDeclTI =
1487 TypeTable.writeUnion(UnionRecord(0, CO, HfaKind::None, TypeIndex(), 0,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001488 FullName, Ty->getIdentifier()));
Reid Kleckner643dd832016-06-22 17:15:28 +00001489 if (!Ty->isForwardDecl())
1490 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001491 return FwdDeclTI;
1492}
1493
1494TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
1495 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001496 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001497 unsigned FieldCount;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001498 std::tie(FieldTI, std::ignore, FieldCount) = lowerRecordFieldList(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001499 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001500 std::string FullName =
1501 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
Hans Wennborg9a519a02016-06-22 21:22:13 +00001502
1503 TypeIndex UnionTI = TypeTable.writeUnion(
1504 UnionRecord(FieldCount, CO, HfaKind::None, FieldTI, SizeInBytes, FullName,
1505 Ty->getIdentifier()));
1506
1507 TypeTable.writeUdtSourceLine(UdtSourceLineRecord(
1508 UnionTI, TypeTable.writeStringId(StringIdRecord(
1509 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1510 Ty->getLine()));
1511
Hans Wennborg4b63a982016-06-23 22:57:25 +00001512 addToUDTs(Ty, UnionTI);
1513
Hans Wennborg9a519a02016-06-22 21:22:13 +00001514 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001515}
1516
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001517std::tuple<TypeIndex, TypeIndex, unsigned>
Reid Klecknera8d57402016-06-03 15:58:20 +00001518CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1519 // Manually count members. MSVC appears to count everything that generates a
1520 // field list record. Each individual overload in a method overload group
1521 // contributes to this count, even though the overload group is a single field
1522 // list record.
1523 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001524 ClassInfo Info = collectClassInfo(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001525 FieldListRecordBuilder Fields;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001526
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001527 // Create base classes.
1528 for (const DIDerivedType *I : Info.Inheritance) {
1529 if (I->getFlags() & DINode::FlagVirtual) {
1530 // Virtual base.
1531 // FIXME: Emit VBPtrOffset when the frontend provides it.
1532 unsigned VBPtrOffset = 0;
1533 // FIXME: Despite the accessor name, the offset is really in bytes.
1534 unsigned VBTableIndex = I->getOffsetInBits() / 4;
1535 Fields.writeVirtualBaseClass(VirtualBaseClassRecord(
1536 translateAccessFlags(Ty->getTag(), I->getFlags()),
1537 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
1538 VBTableIndex));
1539 } else {
1540 assert(I->getOffsetInBits() % 8 == 0 &&
1541 "bases must be on byte boundaries");
1542 Fields.writeBaseClass(BaseClassRecord(
1543 translateAccessFlags(Ty->getTag(), I->getFlags()),
1544 getTypeIndex(I->getBaseType()), I->getOffsetInBits() / 8));
1545 }
1546 }
1547
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001548 // Create members.
1549 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1550 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1551 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00001552 StringRef MemberName = Member->getName();
1553 MemberAccess Access =
1554 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001555
1556 if (Member->isStaticMember()) {
David Majnemer9319cbc2016-06-30 03:00:20 +00001557 Fields.writeStaticDataMember(
1558 StaticDataMemberRecord(Access, MemberBaseType, MemberName));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001559 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001560 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001561 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001562
David Majnemer9319cbc2016-06-30 03:00:20 +00001563 // Data member.
1564 uint64_t MemberOffsetInBits = Member->getOffsetInBits();
1565 if (Member->isBitField()) {
1566 uint64_t StartBitOffset = MemberOffsetInBits;
1567 if (const auto *CI =
1568 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
1569 MemberOffsetInBits = CI->getZExtValue();
1570 }
1571 StartBitOffset -= MemberOffsetInBits;
1572 MemberBaseType = TypeTable.writeBitField(BitFieldRecord(
1573 MemberBaseType, Member->getSizeInBits(), StartBitOffset));
1574 }
1575 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
1576 Fields.writeDataMember(DataMemberRecord(Access, MemberBaseType,
1577 MemberOffsetInBytes, MemberName));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001578 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001579 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001580
1581 // Create methods
1582 for (auto &MethodItr : Info.Methods) {
1583 StringRef Name = MethodItr.first->getString();
1584
1585 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00001586 for (const DISubprogram *SP : MethodItr.second) {
1587 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1588 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001589
1590 unsigned VFTableOffset = -1;
1591 if (Introduced)
1592 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1593
1594 Methods.push_back(
1595 OneMethodRecord(MethodType, translateMethodKindFlags(SP, Introduced),
1596 translateMethodOptionFlags(SP),
1597 translateAccessFlags(Ty->getTag(), SP->getFlags()),
1598 VFTableOffset, Name));
1599 MemberCount++;
1600 }
1601 assert(Methods.size() > 0 && "Empty methods map entry");
1602 if (Methods.size() == 1)
1603 Fields.writeOneMethod(Methods[0]);
1604 else {
1605 TypeIndex MethodList =
1606 TypeTable.writeMethodOverloadList(MethodOverloadListRecord(Methods));
1607 Fields.writeOverloadedMethod(
1608 OverloadedMethodRecord(Methods.size(), MethodList, Name));
1609 }
1610 }
1611 TypeIndex FieldTI = TypeTable.writeFieldList(Fields);
1612 return std::make_tuple(FieldTI, TypeIndex(), MemberCount);
Reid Klecknera8d57402016-06-03 15:58:20 +00001613}
1614
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001615TypeIndex CodeViewDebug::getVBPTypeIndex() {
1616 if (!VBPType.getIndex()) {
1617 // Make a 'const int *' type.
1618 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
1619 TypeIndex ModifiedTI = TypeTable.writeModifier(MR);
1620
1621 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1622 : PointerKind::Near32;
1623 PointerMode PM = PointerMode::Pointer;
1624 PointerOptions PO = PointerOptions::None;
1625 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1626
1627 VBPType = TypeTable.writePointer(PR);
1628 }
1629
1630 return VBPType;
1631}
1632
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001633TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001634 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001635 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001636
1637 // The null DIType is the void type. Don't try to hash it.
1638 if (!Ty)
1639 return TypeIndex::Void();
1640
Reid Klecknera8d57402016-06-03 15:58:20 +00001641 // Check if we've already translated this type. Don't try to do a
1642 // get-or-create style insertion that caches the hash lookup across the
1643 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001644 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001645 if (I != TypeIndices.end())
1646 return I->second;
1647
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001648 TypeLoweringScope S(*this);
1649 TypeIndex TI = lowerType(Ty, ClassTy);
1650 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00001651}
1652
1653TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1654 const DIType *Ty = TypeRef.resolve();
1655
1656 // The null DIType is the void type. Don't try to hash it.
1657 if (!Ty)
1658 return TypeIndex::Void();
1659
1660 // If this is a non-record type, the complete type index is the same as the
1661 // normal type index. Just call getTypeIndex.
1662 switch (Ty->getTag()) {
1663 case dwarf::DW_TAG_class_type:
1664 case dwarf::DW_TAG_structure_type:
1665 case dwarf::DW_TAG_union_type:
1666 break;
1667 default:
1668 return getTypeIndex(Ty);
1669 }
1670
1671 // Check if we've already translated the complete record type. Lowering a
1672 // complete type should never trigger lowering another complete type, so we
1673 // can reuse the hash table lookup result.
1674 const auto *CTy = cast<DICompositeType>(Ty);
1675 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1676 if (!InsertResult.second)
1677 return InsertResult.first->second;
1678
Reid Kleckner643dd832016-06-22 17:15:28 +00001679 TypeLoweringScope S(*this);
1680
Reid Klecknera8d57402016-06-03 15:58:20 +00001681 // Make sure the forward declaration is emitted first. It's unclear if this
1682 // is necessary, but MSVC does it, and we should follow suit until we can show
1683 // otherwise.
1684 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1685
1686 // Just use the forward decl if we don't have complete type info. This might
1687 // happen if the frontend is using modules and expects the complete definition
1688 // to be emitted elsewhere.
1689 if (CTy->isForwardDecl())
1690 return FwdDeclTI;
1691
1692 TypeIndex TI;
1693 switch (CTy->getTag()) {
1694 case dwarf::DW_TAG_class_type:
1695 case dwarf::DW_TAG_structure_type:
1696 TI = lowerCompleteTypeClass(CTy);
1697 break;
1698 case dwarf::DW_TAG_union_type:
1699 TI = lowerCompleteTypeUnion(CTy);
1700 break;
1701 default:
1702 llvm_unreachable("not a record");
1703 }
1704
1705 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001706 return TI;
1707}
1708
Reid Kleckner643dd832016-06-22 17:15:28 +00001709/// Emit all the deferred complete record types. Try to do this in FIFO order,
1710/// and do this until fixpoint, as each complete record type typically references
1711/// many other record types.
1712void CodeViewDebug::emitDeferredCompleteTypes() {
1713 SmallVector<const DICompositeType *, 4> TypesToEmit;
1714 while (!DeferredCompleteTypes.empty()) {
1715 std::swap(DeferredCompleteTypes, TypesToEmit);
1716 for (const DICompositeType *RecordTy : TypesToEmit)
1717 getCompleteTypeIndex(RecordTy);
1718 TypesToEmit.clear();
1719 }
1720}
1721
Reid Kleckner10dd55c2016-06-24 17:55:40 +00001722void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
1723 // Get the sorted list of parameters and emit them first.
1724 SmallVector<const LocalVariable *, 6> Params;
1725 for (const LocalVariable &L : Locals)
1726 if (L.DIVar->isParameter())
1727 Params.push_back(&L);
1728 std::sort(Params.begin(), Params.end(),
1729 [](const LocalVariable *L, const LocalVariable *R) {
1730 return L->DIVar->getArg() < R->DIVar->getArg();
1731 });
1732 for (const LocalVariable *L : Params)
1733 emitLocalVariable(*L);
1734
1735 // Next emit all non-parameters in the order that we found them.
1736 for (const LocalVariable &L : Locals)
1737 if (!L.DIVar->isParameter())
1738 emitLocalVariable(L);
1739}
1740
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001741void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
1742 // LocalSym record, see SymbolRecord.h for more info.
1743 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
1744 *LocalEnd = MMI->getContext().createTempSymbol();
1745 OS.AddComment("Record length");
1746 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
1747 OS.EmitLabel(LocalBegin);
1748
1749 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00001750 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001751
Zachary Turner63a28462016-05-17 23:50:21 +00001752 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001753 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00001754 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00001755 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00001756 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001757
1758 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00001759 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001760 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001761 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00001762 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00001763 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00001764 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001765 OS.EmitLabel(LocalEnd);
1766
Reid Kleckner876330d2016-02-12 21:48:30 +00001767 // Calculate the on disk prefix of the appropriate def range record. The
1768 // records and on disk formats are described in SymbolRecords.h. BytePrefix
1769 // should be big enough to hold all forms without memory allocation.
1770 SmallString<20> BytePrefix;
1771 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
1772 BytePrefix.clear();
1773 // FIXME: Handle bitpieces.
1774 if (DefRange.StructOffset != 0)
1775 continue;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001776
Reid Kleckner876330d2016-02-12 21:48:30 +00001777 if (DefRange.InMemory) {
Zachary Turnera78ecd12016-05-23 18:49:06 +00001778 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
1779 0, 0, ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001780 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00001781 BytePrefix +=
1782 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001783 BytePrefix +=
1784 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1785 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001786 } else {
1787 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Zachary Turnera78ecd12016-05-23 18:49:06 +00001788 // Unclear what matters here.
1789 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
1790 ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001791 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
Reid Kleckner876330d2016-02-12 21:48:30 +00001792 BytePrefix +=
1793 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001794 BytePrefix +=
1795 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1796 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001797 }
1798 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
1799 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001800}
1801
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001802void CodeViewDebug::endFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001803 if (!Asm || !CurFn) // We haven't created any debug info for this function.
1804 return;
1805
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001806 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00001807 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001808 assert(CurFn == &FnDebugInfo[GV]);
1809
Pete Cooperadebb932016-03-11 02:14:16 +00001810 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00001811
1812 DebugHandlerBase::endFunction(MF);
1813
Reid Kleckner2214ed82016-01-29 00:49:42 +00001814 // Don't emit anything if we don't have any line tables.
1815 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001816 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001817 CurFn = nullptr;
1818 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00001819 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001820
1821 CurFn->End = Asm->getFunctionEnd();
1822
Craig Topper353eda42014-04-24 06:44:33 +00001823 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001824}
1825
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001826void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001827 DebugHandlerBase::beginInstruction(MI);
1828
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001829 // Ignore DBG_VALUE locations and function prologue.
1830 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
1831 return;
1832 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001833 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001834 return;
1835 maybeRecordLocation(DL, Asm->MF);
1836}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001837
1838MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
1839 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
1840 *EndLabel = MMI->getContext().createTempSymbol();
1841 OS.EmitIntValue(unsigned(Kind), 4);
1842 OS.AddComment("Subsection size");
1843 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
1844 OS.EmitLabel(BeginLabel);
1845 return EndLabel;
1846}
1847
1848void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
1849 OS.EmitLabel(EndLabel);
1850 // Every subsection must be aligned to a 4-byte boundary.
1851 OS.EmitValueToAlignment(4);
1852}
1853
David Majnemer3128b102016-06-15 18:00:01 +00001854void CodeViewDebug::emitDebugInfoForUDTs(
1855 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
1856 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
1857 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
1858 *UDTRecordEnd = MMI->getContext().createTempSymbol();
1859 OS.AddComment("Record length");
1860 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
1861 OS.EmitLabel(UDTRecordBegin);
1862
1863 OS.AddComment("Record kind: S_UDT");
1864 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
1865
1866 OS.AddComment("Type");
1867 OS.EmitIntValue(UDT.second.getIndex(), 4);
1868
1869 emitNullTerminatedSymbolName(OS, UDT.first);
1870 OS.EmitLabel(UDTRecordEnd);
1871 }
1872}
1873
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001874void CodeViewDebug::emitDebugInfoForGlobals() {
1875 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1876 for (const MDNode *Node : CUs->operands()) {
1877 const auto *CU = cast<DICompileUnit>(Node);
1878
1879 // First, emit all globals that are not in a comdat in a single symbol
1880 // substream. MSVC doesn't like it if the substream is empty, so only open
1881 // it if we have at least one global to emit.
1882 switchToDebugSectionForSymbol(nullptr);
1883 MCSymbol *EndLabel = nullptr;
1884 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001885 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
David Majnemer577be0f2016-06-15 00:19:52 +00001886 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001887 if (!EndLabel) {
1888 OS.AddComment("Symbol subsection for globals");
1889 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1890 }
1891 emitDebugInfoForGlobal(G, Asm->getSymbol(GV));
1892 }
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001893 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001894 }
1895 if (EndLabel)
1896 endCVSubsection(EndLabel);
1897
1898 // Second, emit each global that is in a comdat into its own .debug$S
1899 // section along with its own symbol substream.
1900 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001901 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001902 if (GV->hasComdat()) {
1903 MCSymbol *GVSym = Asm->getSymbol(GV);
1904 OS.AddComment("Symbol subsection for " +
1905 Twine(GlobalValue::getRealLinkageName(GV->getName())));
1906 switchToDebugSectionForSymbol(GVSym);
1907 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1908 emitDebugInfoForGlobal(G, GVSym);
1909 endCVSubsection(EndLabel);
1910 }
1911 }
1912 }
1913 }
1914}
1915
Hans Wennborgb510b452016-06-23 16:33:53 +00001916void CodeViewDebug::emitDebugInfoForRetainedTypes() {
1917 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1918 for (const MDNode *Node : CUs->operands()) {
1919 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
1920 if (DIType *RT = dyn_cast<DIType>(Ty)) {
1921 getTypeIndex(RT);
1922 // FIXME: Add to global/local DTU list.
1923 }
1924 }
1925 }
1926}
1927
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001928void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
1929 MCSymbol *GVSym) {
1930 // DataSym record, see SymbolRecord.h for more info.
1931 // FIXME: Thread local data, etc
1932 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
1933 *DataEnd = MMI->getContext().createTempSymbol();
1934 OS.AddComment("Record length");
1935 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
1936 OS.EmitLabel(DataBegin);
1937 OS.AddComment("Record kind: S_GDATA32");
1938 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
1939 OS.AddComment("Type");
1940 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
1941 OS.AddComment("DataOffset");
1942 OS.EmitCOFFSecRel32(GVSym);
1943 OS.AddComment("Segment");
1944 OS.EmitCOFFSectionIndex(GVSym);
1945 OS.AddComment("Name");
1946 emitNullTerminatedSymbolName(OS, DIGV->getName());
1947 OS.EmitLabel(DataEnd);
1948}