blob: 040bef50f0a7acf7c8e953780f177efc910a4f48 [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 Kleckner6b3faef2016-01-13 23:44:57 +000015#include "llvm/DebugInfo/CodeView/CodeView.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000016#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000017#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000018#include "llvm/DebugInfo/CodeView/TypeDumper.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000019#include "llvm/DebugInfo/CodeView/TypeIndex.h"
20#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000021#include "llvm/MC/MCExpr.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000022#include "llvm/MC/MCSectionCOFF.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000023#include "llvm/MC/MCSymbol.h"
24#include "llvm/Support/COFF.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000025#include "llvm/Support/ScopedPrinter.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000026#include "llvm/Target/TargetSubtargetInfo.h"
27#include "llvm/Target/TargetRegisterInfo.h"
28#include "llvm/Target/TargetFrameLowering.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000029
Reid Klecknerf9c275f2016-02-10 20:55:49 +000030using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000031using namespace llvm::codeview;
32
Reid Klecknerf9c275f2016-02-10 20:55:49 +000033CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
34 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
35 // If module doesn't have named metadata anchors or COFF debug section
36 // is not available, skip any debug info related stuff.
37 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
38 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
39 Asm = nullptr;
40 return;
41 }
42
43 // Tell MMI that we have debug info.
44 MMI->setDebugInfoAvailability(true);
45}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000046
Reid Kleckner9533af42016-01-16 00:09:09 +000047StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
48 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000049 if (!Filepath.empty())
50 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000051
Reid Kleckner9533af42016-01-16 00:09:09 +000052 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
53
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000054 // Clang emits directory and relative filename info into the IR, but CodeView
55 // operates on full paths. We could change Clang to emit full paths too, but
56 // that would increase the IR size and probably not needed for other users.
57 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000058 if (Filename.find(':') == 1)
59 Filepath = Filename;
60 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +000061 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000062
63 // Canonicalize the path. We have to do it textually because we may no longer
64 // have access the file in the filesystem.
65 // First, replace all slashes with backslashes.
66 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
67
68 // Remove all "\.\" with "\".
69 size_t Cursor = 0;
70 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
71 Filepath.erase(Cursor, 2);
72
73 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
74 // path should be well-formatted, e.g. start with a drive letter, etc.
75 Cursor = 0;
76 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
77 // Something's wrong if the path starts with "\..\", abort.
78 if (Cursor == 0)
79 break;
80
81 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
82 if (PrevSlash == std::string::npos)
83 // Something's wrong, abort.
84 break;
85
86 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
87 // The next ".." might be following the one we've just erased.
88 Cursor = PrevSlash;
89 }
90
91 // Remove all duplicate backslashes.
92 Cursor = 0;
93 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
94 Filepath.erase(Cursor, 1);
95
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000096 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000097}
98
Reid Kleckner2214ed82016-01-29 00:49:42 +000099unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
100 unsigned NextId = FileIdMap.size() + 1;
101 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
102 if (Insertion.second) {
103 // We have to compute the full filepath and emit a .cv_file directive.
104 StringRef FullPath = getFullFilepath(F);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000105 NextId = OS.EmitCVFileDirective(NextId, FullPath);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000106 assert(NextId == FileIdMap.size() && ".cv_file directive failed");
107 }
108 return Insertion.first->second;
109}
110
Reid Kleckner876330d2016-02-12 21:48:30 +0000111CodeViewDebug::InlineSite &
112CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
113 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000114 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
115 InlineSite *Site = &SiteInsertion.first->second;
116 if (SiteInsertion.second) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000117 Site->SiteFuncId = NextFuncId++;
Reid Kleckner876330d2016-02-12 21:48:30 +0000118 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000119 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000120 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000121 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000122 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000123}
124
David Majnemer75c3ebf2016-06-02 17:13:53 +0000125TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
126 // It's possible to ask for the FuncId of a function which doesn't have a
127 // subprogram: inlining a function with debug info into a function with none.
128 if (!SP)
129 return TypeIndex::Void();
Reid Kleckner2280f932016-05-23 20:23:46 +0000130
David Majnemer75c3ebf2016-06-02 17:13:53 +0000131 // Check if we've already translated this subprogram.
132 auto I = TypeIndices.find(SP);
133 if (I != TypeIndices.end())
134 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000135
Reid Kleckner2280f932016-05-23 20:23:46 +0000136 TypeIndex ParentScope = TypeIndex(0);
137 StringRef DisplayName = SP->getDisplayName();
David Majnemer75c3ebf2016-06-02 17:13:53 +0000138 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Reid Kleckner2280f932016-05-23 20:23:46 +0000139 TypeIndex TI = TypeTable.writeFuncId(FuncId);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000140
141 auto InsertResult = TypeIndices.insert({SP, TI});
142 (void)InsertResult;
143 assert(InsertResult.second && "DISubprogram lowered twice");
144 return TI;
Reid Kleckner2280f932016-05-23 20:23:46 +0000145}
146
Reid Kleckner876330d2016-02-12 21:48:30 +0000147void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
148 const DILocation *InlinedAt) {
149 if (InlinedAt) {
150 // This variable was inlined. Associate it with the InlineSite.
151 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
152 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
153 Site.InlinedLocals.emplace_back(Var);
154 } else {
155 // This variable goes in the main ProcSym.
156 CurFn->Locals.emplace_back(Var);
157 }
158}
159
Reid Kleckner829365a2016-02-11 19:41:47 +0000160static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
161 const DILocation *Loc) {
162 auto B = Locs.begin(), E = Locs.end();
163 if (std::find(B, E, Loc) == E)
164 Locs.push_back(Loc);
165}
166
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000167void CodeViewDebug::maybeRecordLocation(DebugLoc DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000168 const MachineFunction *MF) {
169 // Skip this instruction if it has the same location as the previous one.
170 if (DL == CurFn->LastLoc)
171 return;
172
173 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000174 if (!Scope)
175 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000176
David Majnemerc3340db2016-01-13 01:05:23 +0000177 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000178 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
179 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
180 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000181 return;
182
Reid Kleckner2214ed82016-01-29 00:49:42 +0000183 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
184 if (CI.getStartColumn() != DL.getCol())
185 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000186
Reid Kleckner2214ed82016-01-29 00:49:42 +0000187 if (!CurFn->HaveLineInfo)
188 CurFn->HaveLineInfo = true;
189 unsigned FileId = 0;
190 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
191 FileId = CurFn->LastFileId;
192 else
193 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
194 CurFn->LastLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000195
196 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000197 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000198 const DILocation *Loc = DL.get();
199
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000200 // If this location was actually inlined from somewhere else, give it the ID
201 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000202 FuncId =
203 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000204
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000205 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000206 bool FirstLoc = true;
207 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000208 InlineSite &Site =
209 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000210 if (!FirstLoc)
211 addLocIfNotPresent(Site.ChildSites, Loc);
212 FirstLoc = false;
213 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000214 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000215 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000216 }
217
Reid Klecknerdac21b42016-02-03 21:15:48 +0000218 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
219 /*PrologueEnd=*/false,
220 /*IsStmt=*/false, DL->getFilename());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000221}
222
Reid Kleckner5d122f82016-05-25 23:16:12 +0000223void CodeViewDebug::emitCodeViewMagicVersion() {
224 OS.EmitValueToAlignment(4);
225 OS.AddComment("Debug section magic");
226 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
227}
228
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000229void CodeViewDebug::endModule() {
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000230 if (FnDebugInfo.empty())
231 return;
232
233 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000234
235 // The COFF .debug$S section consists of several subsections, each starting
236 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
237 // of the payload followed by the payload itself. The subsections are 4-byte
238 // aligned.
239
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000240 // Make a subsection for all the inlined subprograms.
Reid Kleckner5d122f82016-05-25 23:16:12 +0000241 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000242
Reid Kleckner2214ed82016-01-29 00:49:42 +0000243 // Emit per-function debug information.
244 for (auto &P : FnDebugInfo)
245 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000246
Reid Kleckner5d122f82016-05-25 23:16:12 +0000247 // Switch back to the generic .debug$S section after potentially processing
248 // comdat symbol sections.
249 switchToDebugSectionForSymbol(nullptr);
250
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000251 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000252 OS.AddComment("File index to string table offset subsection");
253 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000254
255 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000256 OS.AddComment("String table");
257 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000258
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000259 // Emit type information last, so that any types we translate while emitting
260 // function info are included.
261 emitTypeInformation();
262
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000263 clear();
264}
265
David Majnemerb9456a52016-03-14 05:15:09 +0000266static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
267 // Microsoft's linker seems to have trouble with symbol names longer than
268 // 0xffd8 bytes.
269 S = S.substr(0, 0xffd8);
270 SmallString<32> NullTerminatedString(S);
271 NullTerminatedString.push_back('\0');
272 OS.EmitBytes(NullTerminatedString);
273}
274
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000275void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000276 // Do nothing if we have no debug info or if no non-trivial types were emitted
277 // to TypeTable during codegen.
Reid Klecknerfbd77872016-03-18 18:54:32 +0000278 NamedMDNode *CU_Nodes =
279 MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
280 if (!CU_Nodes)
281 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000282 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000283 return;
284
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000285 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000286 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000287 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000288
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000289 SmallString<8> CommentPrefix;
290 if (OS.isVerboseAsm()) {
291 CommentPrefix += '\t';
292 CommentPrefix += Asm->MAI->getCommentString();
293 CommentPrefix += ' ';
294 }
295
296 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
Reid Kleckner2280f932016-05-23 20:23:46 +0000297 TypeTable.ForEachRecord(
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000298 [&](TypeIndex Index, StringRef Record) {
299 if (OS.isVerboseAsm()) {
300 // Emit a block comment describing the type record for readability.
301 SmallString<512> CommentBlock;
302 raw_svector_ostream CommentOS(CommentBlock);
303 ScopedPrinter SP(CommentOS);
304 SP.setPrefix(CommentPrefix);
305 CVTD.setPrinter(&SP);
306 bool DumpSuccess =
307 CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
308 (void)DumpSuccess;
309 assert(DumpSuccess && "produced malformed type record");
310 // emitRawComment will insert its own tab and comment string before
311 // the first line, so strip off our first one. It also prints its own
312 // newline.
313 OS.emitRawComment(
314 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
315 }
316 OS.EmitBinaryData(Record);
Reid Kleckner2280f932016-05-23 20:23:46 +0000317 });
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000318}
319
Reid Kleckner5d122f82016-05-25 23:16:12 +0000320void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000321 if (InlinedSubprograms.empty())
322 return;
323
Reid Kleckner5d122f82016-05-25 23:16:12 +0000324 // Use the generic .debug$S section.
325 switchToDebugSectionForSymbol(nullptr);
326
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000327 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
328 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000329
330 OS.AddComment("Inlinee lines subsection");
331 OS.EmitIntValue(unsigned(ModuleSubstreamKind::InlineeLines), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000332 OS.AddComment("Subsection size");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000333 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 4);
334 OS.EmitLabel(InlineBegin);
335
336 // We don't provide any extra file info.
337 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000338 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000339 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
340
341 for (const DISubprogram *SP : InlinedSubprograms) {
Reid Kleckner2280f932016-05-23 20:23:46 +0000342 assert(TypeIndices.count(SP));
343 TypeIndex InlineeIdx = TypeIndices[SP];
344
David Majnemer30579ec2016-02-02 23:18:23 +0000345 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000346 unsigned FileId = maybeRecordFile(SP->getFile());
347 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
348 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000349 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000350 // The filechecksum table uses 8 byte entries for now, and file ids start at
351 // 1.
352 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000353 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000354 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000355 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000356 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000357 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000358 OS.EmitIntValue(SP->getLine(), 4);
359 }
360
361 OS.EmitLabel(InlineEnd);
362}
363
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000364void CodeViewDebug::collectInlineSiteChildren(
365 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
366 const InlineSite &Site) {
367 for (const DILocation *ChildSiteLoc : Site.ChildSites) {
368 auto I = FI.InlineSites.find(ChildSiteLoc);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000369 const InlineSite &ChildSite = I->second;
370 Children.push_back(ChildSite.SiteFuncId);
371 collectInlineSiteChildren(Children, FI, ChildSite);
372 }
373}
374
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000375void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
376 const DILocation *InlinedAt,
377 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000378 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
379 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000380
Reid Kleckner2280f932016-05-23 20:23:46 +0000381 assert(TypeIndices.count(Site.Inlinee));
382 TypeIndex InlineeIdx = TypeIndices[Site.Inlinee];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000383
384 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000385 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000386 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000387 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000388 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000389 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000390
Reid Klecknerdac21b42016-02-03 21:15:48 +0000391 OS.AddComment("PtrParent");
392 OS.EmitIntValue(0, 4);
393 OS.AddComment("PtrEnd");
394 OS.EmitIntValue(0, 4);
395 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000396 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000397
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000398 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
399 unsigned StartLineNum = Site.Inlinee->getLine();
400 SmallVector<unsigned, 3> SecondaryFuncIds;
401 collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
402
403 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
David Majnemerc9911f22016-02-02 19:22:34 +0000404 FI.Begin, FI.End, SecondaryFuncIds);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000405
406 OS.EmitLabel(InlineEnd);
407
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000408 for (const LocalVariable &Var : Site.InlinedLocals)
409 emitLocalVariable(Var);
410
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000411 // Recurse on child inlined call sites before closing the scope.
412 for (const DILocation *ChildSite : Site.ChildSites) {
413 auto I = FI.InlineSites.find(ChildSite);
414 assert(I != FI.InlineSites.end() &&
415 "child site not in function inline site map");
416 emitInlinedCallSite(FI, ChildSite, I->second);
417 }
418
419 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000420 OS.AddComment("Record length");
421 OS.EmitIntValue(2, 2); // RecordLength
422 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000423 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000424}
425
Reid Kleckner5d122f82016-05-25 23:16:12 +0000426void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
427 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
428 // comdat key. A section may be comdat because of -ffunction-sections or
429 // because it is comdat in the IR.
430 MCSectionCOFF *GVSec =
431 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
432 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
433
434 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
435 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
436 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
437
438 OS.SwitchSection(DebugSec);
439
440 // Emit the magic version number if this is the first time we've switched to
441 // this section.
442 if (ComdatDebugSections.insert(DebugSec).second)
443 emitCodeViewMagicVersion();
444}
445
Reid Kleckner2214ed82016-01-29 00:49:42 +0000446void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
447 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000448 // For each function there is a separate subsection
449 // which holds the PC to file:line table.
450 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000451 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000452
Reid Kleckner5d122f82016-05-25 23:16:12 +0000453 // Switch to the to a comdat section, if appropriate.
454 switchToDebugSectionForSymbol(Fn);
455
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000456 StringRef FuncName;
Pete Cooperadebb932016-03-11 02:14:16 +0000457 if (auto *SP = GV->getSubprogram())
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000458 FuncName = SP->getDisplayName();
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000459
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000460 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000461 if (FuncName.empty())
462 FuncName = GlobalValue::getRealLinkageName(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000463
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000464 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000465 MCSymbol *SymbolsBegin = MMI->getContext().createTempSymbol(),
466 *SymbolsEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000467 OS.AddComment("Symbol subsection for " + Twine(FuncName));
468 OS.EmitIntValue(unsigned(ModuleSubstreamKind::Symbols), 4);
469 OS.AddComment("Subsection size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000470 OS.emitAbsoluteSymbolDiff(SymbolsEnd, SymbolsBegin, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000471 OS.EmitLabel(SymbolsBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000472 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000473 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
474 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000475 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000476 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000477 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000478
Reid Klecknerdac21b42016-02-03 21:15:48 +0000479 OS.AddComment("Record kind: S_GPROC32_ID");
Zachary Turner63a28462016-05-17 23:50:21 +0000480 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000481
David Majnemer30579ec2016-02-02 23:18:23 +0000482 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000483 OS.AddComment("PtrParent");
484 OS.EmitIntValue(0, 4);
485 OS.AddComment("PtrEnd");
486 OS.EmitIntValue(0, 4);
487 OS.AddComment("PtrNext");
488 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000489 // This is the important bit that tells the debugger where the function
490 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000491 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000492 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000493 OS.AddComment("Offset after prologue");
494 OS.EmitIntValue(0, 4);
495 OS.AddComment("Offset before epilogue");
496 OS.EmitIntValue(0, 4);
497 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000498 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000499 OS.AddComment("Function section relative address");
500 OS.EmitCOFFSecRel32(Fn);
501 OS.AddComment("Function section index");
502 OS.EmitCOFFSectionIndex(Fn);
503 OS.AddComment("Flags");
504 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000505 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000506 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000507 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000508 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000509 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000510
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000511 for (const LocalVariable &Var : FI.Locals)
512 emitLocalVariable(Var);
513
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000514 // Emit inlined call site information. Only emit functions inlined directly
515 // into the parent function. We'll emit the other sites recursively as part
516 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000517 for (const DILocation *InlinedAt : FI.ChildSites) {
518 auto I = FI.InlineSites.find(InlinedAt);
519 assert(I != FI.InlineSites.end() &&
520 "child site not in function inline site map");
521 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000522 }
523
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000524 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000525 OS.AddComment("Record length");
526 OS.EmitIntValue(0x0002, 2);
527 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000528 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000529 }
Reid Klecknerdac21b42016-02-03 21:15:48 +0000530 OS.EmitLabel(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000531 // Every subsection must be aligned to a 4-byte boundary.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000532 OS.EmitValueToAlignment(4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000533
Reid Kleckner2214ed82016-01-29 00:49:42 +0000534 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000535 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000536}
537
Reid Kleckner876330d2016-02-12 21:48:30 +0000538CodeViewDebug::LocalVarDefRange
539CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
540 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000541 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000542 DR.DataOffset = Offset;
543 assert(DR.DataOffset == Offset && "truncation");
544 DR.StructOffset = 0;
545 DR.CVRegister = CVRegister;
546 return DR;
547}
548
549CodeViewDebug::LocalVarDefRange
550CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
551 LocalVarDefRange DR;
552 DR.InMemory = 0;
553 DR.DataOffset = 0;
554 DR.StructOffset = 0;
555 DR.CVRegister = CVRegister;
556 return DR;
557}
558
559void CodeViewDebug::collectVariableInfoFromMMITable(
560 DenseSet<InlinedVariable> &Processed) {
561 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
562 const TargetFrameLowering *TFI = TSI.getFrameLowering();
563 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
564
565 for (const MachineModuleInfo::VariableDbgInfo &VI :
566 MMI->getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000567 if (!VI.Var)
568 continue;
569 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
570 "Expected inlined-at fields to agree");
571
Reid Kleckner876330d2016-02-12 21:48:30 +0000572 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000573 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
574
575 // If variable scope is not found then skip this variable.
576 if (!Scope)
577 continue;
578
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000579 // Get the frame register used and the offset.
580 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000581 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
582 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000583
584 // Calculate the label ranges.
Reid Kleckner876330d2016-02-12 21:48:30 +0000585 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000586 for (const InsnRange &Range : Scope->getRanges()) {
587 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
588 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000589 End = End ? End : Asm->getFunctionEnd();
590 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000591 }
592
Reid Kleckner876330d2016-02-12 21:48:30 +0000593 LocalVariable Var;
594 Var.DIVar = VI.Var;
595 Var.DefRanges.emplace_back(std::move(DefRange));
596 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
597 }
598}
599
600void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
601 DenseSet<InlinedVariable> Processed;
602 // Grab the variable info that was squirreled away in the MMI side-table.
603 collectVariableInfoFromMMITable(Processed);
604
605 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
606
607 for (const auto &I : DbgValues) {
608 InlinedVariable IV = I.first;
609 if (Processed.count(IV))
610 continue;
611 const DILocalVariable *DIVar = IV.first;
612 const DILocation *InlinedAt = IV.second;
613
614 // Instruction ranges, specifying where IV is accessible.
615 const auto &Ranges = I.second;
616
617 LexicalScope *Scope = nullptr;
618 if (InlinedAt)
619 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
620 else
621 Scope = LScopes.findLexicalScope(DIVar->getScope());
622 // If variable scope is not found then skip this variable.
623 if (!Scope)
624 continue;
625
626 LocalVariable Var;
627 Var.DIVar = DIVar;
628
629 // Calculate the definition ranges.
630 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
631 const InsnRange &Range = *I;
632 const MachineInstr *DVInst = Range.first;
633 assert(DVInst->isDebugValue() && "Invalid History entry");
634 const DIExpression *DIExpr = DVInst->getDebugExpression();
635
636 // Bail if there is a complex DWARF expression for now.
637 if (DIExpr && DIExpr->getNumElements() > 0)
638 continue;
639
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000640 // Bail if operand 0 is not a valid register. This means the variable is a
641 // simple constant, or is described by a complex expression.
642 // FIXME: Find a way to represent constant variables, since they are
643 // relatively common.
644 unsigned Reg =
645 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
646 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000647 continue;
648
Reid Kleckner876330d2016-02-12 21:48:30 +0000649 // Handle the two cases we can handle: indirect in memory and in register.
650 bool IsIndirect = DVInst->getOperand(1).isImm();
651 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
652 {
653 LocalVarDefRange DefRange;
654 if (IsIndirect) {
655 int64_t Offset = DVInst->getOperand(1).getImm();
656 DefRange = createDefRangeMem(CVReg, Offset);
657 } else {
658 DefRange = createDefRangeReg(CVReg);
659 }
660 if (Var.DefRanges.empty() ||
661 Var.DefRanges.back().isDifferentLocation(DefRange)) {
662 Var.DefRanges.emplace_back(std::move(DefRange));
663 }
664 }
665
666 // Compute the label range.
667 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
668 const MCSymbol *End = getLabelAfterInsn(Range.second);
669 if (!End) {
670 if (std::next(I) != E)
671 End = getLabelBeforeInsn(std::next(I)->first);
672 else
673 End = Asm->getFunctionEnd();
674 }
675
676 // If the last range end is our begin, just extend the last range.
677 // Otherwise make a new range.
678 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
679 Var.DefRanges.back().Ranges;
680 if (!Ranges.empty() && Ranges.back().second == Begin)
681 Ranges.back().second = End;
682 else
683 Ranges.emplace_back(Begin, End);
684
685 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000686 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000687
688 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000689 }
690}
691
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000692void CodeViewDebug::beginFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000693 assert(!CurFn && "Can't process two functions at once!");
694
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000695 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000696 return;
697
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000698 DebugHandlerBase::beginFunction(MF);
699
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000700 const Function *GV = MF->getFunction();
701 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000702 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +0000703 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000704 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000705
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000706 // Find the end of the function prolog. First known non-DBG_VALUE and
707 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000708 // FIXME: is there a simpler a way to do this? Can we just search
709 // for the first instruction of the function, not the last of the prolog?
710 DebugLoc PrologEndLoc;
711 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000712 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000713 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000714 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
715 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000716 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000717 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000718 } else if (!MI.isDebugValue()) {
719 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000720 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000721 }
722 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000723
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000724 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000725 if (PrologEndLoc && !EmptyPrologue) {
726 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000727 maybeRecordLocation(FnStartDL, MF);
728 }
729}
730
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000731TypeIndex CodeViewDebug::lowerType(const DIType *Ty) {
732 // Generic dispatch for lowering an unknown type.
733 switch (Ty->getTag()) {
David Majnemerd065e232016-06-02 06:21:37 +0000734 case dwarf::DW_TAG_typedef:
735 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000736 case dwarf::DW_TAG_base_type:
737 return lowerTypeBasic(cast<DIBasicType>(Ty));
738 case dwarf::DW_TAG_pointer_type:
739 case dwarf::DW_TAG_reference_type:
740 case dwarf::DW_TAG_rvalue_reference_type:
741 return lowerTypePointer(cast<DIDerivedType>(Ty));
742 case dwarf::DW_TAG_ptr_to_member_type:
743 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
744 case dwarf::DW_TAG_const_type:
745 case dwarf::DW_TAG_volatile_type:
746 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +0000747 case dwarf::DW_TAG_subroutine_type:
748 return lowerTypeFunction(cast<DISubroutineType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000749 default:
750 // Use the null type index.
751 return TypeIndex();
752 }
753}
754
David Majnemerd065e232016-06-02 06:21:37 +0000755TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
756 // TODO: MSVC emits a S_UDT record.
757 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
758 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
759 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
760 Ty->getName() == "HRESULT")
761 return TypeIndex(SimpleTypeKind::HResult);
762 return UnderlyingTypeIndex;
763}
764
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000765TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
766 TypeIndex Index;
767 dwarf::TypeKind Kind;
768 uint32_t ByteSize;
769
770 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +0000771 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000772
773 SimpleTypeKind STK = SimpleTypeKind::None;
774 switch (Kind) {
775 case dwarf::DW_ATE_address:
776 // FIXME: Translate
777 break;
778 case dwarf::DW_ATE_boolean:
779 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000780 case 1: STK = SimpleTypeKind::Boolean8; break;
781 case 2: STK = SimpleTypeKind::Boolean16; break;
782 case 4: STK = SimpleTypeKind::Boolean32; break;
783 case 8: STK = SimpleTypeKind::Boolean64; break;
784 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000785 }
786 break;
787 case dwarf::DW_ATE_complex_float:
788 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000789 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000790 case 4: STK = SimpleTypeKind::Complex32; break;
791 case 8: STK = SimpleTypeKind::Complex64; break;
792 case 10: STK = SimpleTypeKind::Complex80; break;
793 case 16: STK = SimpleTypeKind::Complex128; break;
794 }
795 break;
796 case dwarf::DW_ATE_float:
797 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000798 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000799 case 4: STK = SimpleTypeKind::Float32; break;
800 case 6: STK = SimpleTypeKind::Float48; break;
801 case 8: STK = SimpleTypeKind::Float64; break;
802 case 10: STK = SimpleTypeKind::Float80; break;
803 case 16: STK = SimpleTypeKind::Float128; break;
804 }
805 break;
806 case dwarf::DW_ATE_signed:
807 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000808 case 1: STK = SimpleTypeKind::SByte; break;
809 case 2: STK = SimpleTypeKind::Int16Short; break;
810 case 4: STK = SimpleTypeKind::Int32; break;
811 case 8: STK = SimpleTypeKind::Int64Quad; break;
812 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000813 }
814 break;
815 case dwarf::DW_ATE_unsigned:
816 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000817 case 1: STK = SimpleTypeKind::Byte; break;
818 case 2: STK = SimpleTypeKind::UInt16Short; break;
819 case 4: STK = SimpleTypeKind::UInt32; break;
820 case 8: STK = SimpleTypeKind::UInt64Quad; break;
821 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000822 }
823 break;
824 case dwarf::DW_ATE_UTF:
825 switch (ByteSize) {
826 case 2: STK = SimpleTypeKind::Character16; break;
827 case 4: STK = SimpleTypeKind::Character32; break;
828 }
829 break;
830 case dwarf::DW_ATE_signed_char:
831 if (ByteSize == 1)
832 STK = SimpleTypeKind::SignedCharacter;
833 break;
834 case dwarf::DW_ATE_unsigned_char:
835 if (ByteSize == 1)
836 STK = SimpleTypeKind::UnsignedCharacter;
837 break;
838 default:
839 break;
840 }
841
842 // Apply some fixups based on the source-level type name.
843 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
844 STK = SimpleTypeKind::Int32Long;
845 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
846 STK = SimpleTypeKind::UInt32Long;
847 if ((STK == SimpleTypeKind::Int16Short ||
848 STK == SimpleTypeKind::UInt16Short) &&
849 Ty->getName() == "wchar_t")
850 STK = SimpleTypeKind::WideCharacter;
851 if ((STK == SimpleTypeKind::SignedCharacter ||
852 STK == SimpleTypeKind::UnsignedCharacter) &&
853 Ty->getName() == "char")
854 STK = SimpleTypeKind::NarrowCharacter;
855
856 return TypeIndex(STK);
857}
858
859TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
860 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
861
862 // Pointers to simple types can use SimpleTypeMode, rather than having a
863 // dedicated pointer type record.
864 if (PointeeTI.isSimple() &&
865 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
866 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
867 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
868 ? SimpleTypeMode::NearPointer64
869 : SimpleTypeMode::NearPointer32;
870 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
871 }
872
873 PointerKind PK =
874 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
875 PointerMode PM = PointerMode::Pointer;
876 switch (Ty->getTag()) {
877 default: llvm_unreachable("not a pointer tag type");
878 case dwarf::DW_TAG_pointer_type:
879 PM = PointerMode::Pointer;
880 break;
881 case dwarf::DW_TAG_reference_type:
882 PM = PointerMode::LValueReference;
883 break;
884 case dwarf::DW_TAG_rvalue_reference_type:
885 PM = PointerMode::RValueReference;
886 break;
887 }
888 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
889 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
890 // do.
891 PointerOptions PO = PointerOptions::None;
892 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
893 return TypeTable.writePointer(PR);
894}
895
896TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
897 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
898 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
899 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
900 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
901 : PointerKind::Near32;
902 PointerMode PM = isa<DISubroutineType>(Ty->getBaseType())
903 ? PointerMode::PointerToMemberFunction
904 : PointerMode::PointerToDataMember;
905 PointerOptions PO = PointerOptions::None; // FIXME
906 // FIXME: Thread this ABI info through metadata.
907 PointerToMemberRepresentation PMR = PointerToMemberRepresentation::Unknown;
908 MemberPointerInfo MPI(ClassTI, PMR);
909 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8, MPI);
910 return TypeTable.writePointer(PR);
911}
912
913TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
914 ModifierOptions Mods = ModifierOptions::None;
915 bool IsModifier = true;
916 const DIType *BaseTy = Ty;
917 while (IsModifier) {
918 assert(BaseTy);
919 // FIXME: Need to add DWARF tag for __unaligned.
920 switch (BaseTy->getTag()) {
921 case dwarf::DW_TAG_const_type:
922 Mods |= ModifierOptions::Const;
923 break;
924 case dwarf::DW_TAG_volatile_type:
925 Mods |= ModifierOptions::Volatile;
926 break;
927 default:
928 IsModifier = false;
929 break;
930 }
931 if (IsModifier)
932 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
933 }
934 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
935 ModifierRecord MR(ModifiedTI, Mods);
936 return TypeTable.writeModifier(MR);
937}
938
David Majnemer75c3ebf2016-06-02 17:13:53 +0000939TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
940 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
941 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
942 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
943
944 TypeIndex ReturnTypeIndex = TypeIndex::Void();
945 ArrayRef<TypeIndex> ArgTypeIndices = None;
946 if (!ReturnAndArgTypeIndices.empty()) {
947 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
948 ReturnTypeIndex = ReturnAndArgTypesRef.front();
949 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
950 }
951
952 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
953 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
954
955 // TODO: We should use DW_AT_calling_convention to determine what CC this
956 // procedure record should have.
957 // TODO: Some functions are member functions, we should use a more appropriate
958 // record for those.
959 ProcedureRecord Procedure(ReturnTypeIndex, CallingConvention::NearC,
960 FunctionOptions::None, ArgTypeIndices.size(),
961 ArgListIndex);
962 return TypeTable.writeProcedure(Procedure);
963}
964
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000965TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef) {
966 const DIType *Ty = TypeRef.resolve();
967
968 // The null DIType is the void type. Don't try to hash it.
969 if (!Ty)
970 return TypeIndex::Void();
971
972 // Check if we've already translated this type.
973 auto I = TypeIndices.find(Ty);
974 if (I != TypeIndices.end())
975 return I->second;
976
977 TypeIndex TI = lowerType(Ty);
978
979 auto InsertResult = TypeIndices.insert({Ty, TI});
Reid Kleckner846edb62016-06-01 17:31:24 +0000980 (void)InsertResult;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000981 assert(InsertResult.second && "DIType lowered twice");
982 return TI;
983}
984
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000985void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
986 // LocalSym record, see SymbolRecord.h for more info.
987 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
988 *LocalEnd = MMI->getContext().createTempSymbol();
989 OS.AddComment("Record length");
990 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
991 OS.EmitLabel(LocalBegin);
992
993 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +0000994 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000995
Zachary Turner63a28462016-05-17 23:50:21 +0000996 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000997 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +0000998 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +0000999 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00001000 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001001
1002 OS.AddComment("TypeIndex");
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001003 TypeIndex TI = getTypeIndex(Var.DIVar->getType());
1004 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001005 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00001006 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00001007 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00001008 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001009 OS.EmitLabel(LocalEnd);
1010
Reid Kleckner876330d2016-02-12 21:48:30 +00001011 // Calculate the on disk prefix of the appropriate def range record. The
1012 // records and on disk formats are described in SymbolRecords.h. BytePrefix
1013 // should be big enough to hold all forms without memory allocation.
1014 SmallString<20> BytePrefix;
1015 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
1016 BytePrefix.clear();
1017 // FIXME: Handle bitpieces.
1018 if (DefRange.StructOffset != 0)
1019 continue;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001020
Reid Kleckner876330d2016-02-12 21:48:30 +00001021 if (DefRange.InMemory) {
Zachary Turnera78ecd12016-05-23 18:49:06 +00001022 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
1023 0, 0, ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001024 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00001025 BytePrefix +=
1026 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001027 BytePrefix +=
1028 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1029 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001030 } else {
1031 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Zachary Turnera78ecd12016-05-23 18:49:06 +00001032 // Unclear what matters here.
1033 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
1034 ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001035 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
Reid Kleckner876330d2016-02-12 21:48:30 +00001036 BytePrefix +=
1037 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001038 BytePrefix +=
1039 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1040 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001041 }
1042 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
1043 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001044}
1045
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001046void CodeViewDebug::endFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001047 if (!Asm || !CurFn) // We haven't created any debug info for this function.
1048 return;
1049
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001050 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00001051 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001052 assert(CurFn == &FnDebugInfo[GV]);
1053
Pete Cooperadebb932016-03-11 02:14:16 +00001054 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00001055
1056 DebugHandlerBase::endFunction(MF);
1057
Reid Kleckner2214ed82016-01-29 00:49:42 +00001058 // Don't emit anything if we don't have any line tables.
1059 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001060 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001061 CurFn = nullptr;
1062 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00001063 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001064
1065 CurFn->End = Asm->getFunctionEnd();
1066
Craig Topper353eda42014-04-24 06:44:33 +00001067 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001068}
1069
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001070void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001071 DebugHandlerBase::beginInstruction(MI);
1072
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001073 // Ignore DBG_VALUE locations and function prologue.
1074 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
1075 return;
1076 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001077 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001078 return;
1079 maybeRecordLocation(DL, Asm->MF);
1080}