blob: aa7a301687fd9a7135de28648e243bdce0cb9b33 [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/CVTypeVisitor.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000017#include "llvm/DebugInfo/CodeView/CodeView.h"
Reid Klecknera8d57402016-06-03 15:58:20 +000018#include "llvm/DebugInfo/CodeView/FieldListRecordBuilder.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000019#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000020#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000021#include "llvm/DebugInfo/CodeView/TypeDumper.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000022#include "llvm/DebugInfo/CodeView/TypeIndex.h"
23#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000024#include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
Zachary Turnera3225b02016-07-29 20:56:36 +000025#include "llvm/DebugInfo/MSF/ByteStream.h"
26#include "llvm/DebugInfo/MSF/StreamReader.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000027#include "llvm/IR/Constants.h"
Reid Kleckner46cb48c2016-07-27 16:03:57 +000028#include "llvm/MC/MCAsmInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000029#include "llvm/MC/MCExpr.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000030#include "llvm/MC/MCSectionCOFF.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000031#include "llvm/MC/MCSymbol.h"
32#include "llvm/Support/COFF.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000033#include "llvm/Support/ScopedPrinter.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000034#include "llvm/Target/TargetFrameLowering.h"
Amjad Aboud76c9eb92016-06-18 10:25:07 +000035#include "llvm/Target/TargetRegisterInfo.h"
36#include "llvm/Target/TargetSubtargetInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000037
Reid Klecknerf9c275f2016-02-10 20:55:49 +000038using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000039using namespace llvm::codeview;
Zachary Turnerbac69d32016-07-22 19:56:05 +000040using namespace llvm::msf;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000041
Reid Klecknerf9c275f2016-02-10 20:55:49 +000042CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
Zachary Turnerc6d54da2016-09-09 17:46:17 +000043 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), Allocator(),
44 TypeTable(Allocator), CurFn(nullptr) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +000045 // If module doesn't have named metadata anchors or COFF debug section
46 // is not available, skip any debug info related stuff.
47 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
48 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
49 Asm = nullptr;
50 return;
51 }
52
53 // Tell MMI that we have debug info.
54 MMI->setDebugInfoAvailability(true);
55}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000056
Reid Kleckner9533af42016-01-16 00:09:09 +000057StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
58 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000059 if (!Filepath.empty())
60 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000061
Reid Kleckner9533af42016-01-16 00:09:09 +000062 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
63
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000064 // Clang emits directory and relative filename info into the IR, but CodeView
65 // operates on full paths. We could change Clang to emit full paths too, but
66 // that would increase the IR size and probably not needed for other users.
67 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000068 if (Filename.find(':') == 1)
69 Filepath = Filename;
70 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +000071 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000072
73 // Canonicalize the path. We have to do it textually because we may no longer
74 // have access the file in the filesystem.
75 // First, replace all slashes with backslashes.
76 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
77
78 // Remove all "\.\" with "\".
79 size_t Cursor = 0;
80 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
81 Filepath.erase(Cursor, 2);
82
83 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
84 // path should be well-formatted, e.g. start with a drive letter, etc.
85 Cursor = 0;
86 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
87 // Something's wrong if the path starts with "\..\", abort.
88 if (Cursor == 0)
89 break;
90
91 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
92 if (PrevSlash == std::string::npos)
93 // Something's wrong, abort.
94 break;
95
96 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
97 // The next ".." might be following the one we've just erased.
98 Cursor = PrevSlash;
99 }
100
101 // Remove all duplicate backslashes.
102 Cursor = 0;
103 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
104 Filepath.erase(Cursor, 1);
105
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000106 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000107}
108
Reid Kleckner2214ed82016-01-29 00:49:42 +0000109unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
110 unsigned NextId = FileIdMap.size() + 1;
111 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
112 if (Insertion.second) {
113 // We have to compute the full filepath and emit a .cv_file directive.
114 StringRef FullPath = getFullFilepath(F);
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000115 bool Success = OS.EmitCVFileDirective(NextId, FullPath);
116 (void)Success;
117 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000118 }
119 return Insertion.first->second;
120}
121
Reid Kleckner876330d2016-02-12 21:48:30 +0000122CodeViewDebug::InlineSite &
123CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
124 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000125 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
126 InlineSite *Site = &SiteInsertion.first->second;
127 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000128 unsigned ParentFuncId = CurFn->FuncId;
129 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
130 ParentFuncId =
131 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
132 .SiteFuncId;
133
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000134 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000135 OS.EmitCVInlineSiteIdDirective(
136 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
137 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000138 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000139 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000140 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000141 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000142 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000143}
144
David Majnemer6bdc24e2016-07-01 23:12:45 +0000145static StringRef getPrettyScopeName(const DIScope *Scope) {
146 StringRef ScopeName = Scope->getName();
147 if (!ScopeName.empty())
148 return ScopeName;
149
150 switch (Scope->getTag()) {
151 case dwarf::DW_TAG_enumeration_type:
152 case dwarf::DW_TAG_class_type:
153 case dwarf::DW_TAG_structure_type:
154 case dwarf::DW_TAG_union_type:
155 return "<unnamed-tag>";
156 case dwarf::DW_TAG_namespace:
157 return "`anonymous namespace'";
158 }
159
160 return StringRef();
161}
162
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000163static const DISubprogram *getQualifiedNameComponents(
164 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
165 const DISubprogram *ClosestSubprogram = nullptr;
166 while (Scope != nullptr) {
167 if (ClosestSubprogram == nullptr)
168 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000169 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000170 if (!ScopeName.empty())
171 QualifiedNameComponents.push_back(ScopeName);
172 Scope = Scope->getScope().resolve();
173 }
174 return ClosestSubprogram;
175}
176
177static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
178 StringRef TypeName) {
179 std::string FullyQualifiedName;
180 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
181 FullyQualifiedName.append(QualifiedNameComponent);
182 FullyQualifiedName.append("::");
183 }
184 FullyQualifiedName.append(TypeName);
185 return FullyQualifiedName;
186}
187
188static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
189 SmallVector<StringRef, 5> QualifiedNameComponents;
190 getQualifiedNameComponents(Scope, QualifiedNameComponents);
191 return getQualifiedName(QualifiedNameComponents, Name);
192}
193
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000194struct CodeViewDebug::TypeLoweringScope {
195 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
196 ~TypeLoweringScope() {
197 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
198 // inner TypeLoweringScopes don't attempt to emit deferred types.
199 if (CVD.TypeEmissionLevel == 1)
200 CVD.emitDeferredCompleteTypes();
201 --CVD.TypeEmissionLevel;
202 }
203 CodeViewDebug &CVD;
204};
205
David Majnemer6bdc24e2016-07-01 23:12:45 +0000206static std::string getFullyQualifiedName(const DIScope *Ty) {
207 const DIScope *Scope = Ty->getScope().resolve();
208 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
209}
210
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000211TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
212 // No scope means global scope and that uses the zero index.
213 if (!Scope || isa<DIFile>(Scope))
214 return TypeIndex();
215
216 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
217
218 // Check if we've already translated this scope.
219 auto I = TypeIndices.find({Scope, nullptr});
220 if (I != TypeIndices.end())
221 return I->second;
222
223 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000224 std::string ScopeName = getFullyQualifiedName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000225 TypeIndex TI =
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000226 TypeTable.writeKnownType(StringIdRecord(TypeIndex(), ScopeName));
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000227 return recordTypeIndexForDINode(Scope, TI);
228}
229
David Majnemer75c3ebf2016-06-02 17:13:53 +0000230TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000231 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000232
David Majnemer75c3ebf2016-06-02 17:13:53 +0000233 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000234 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000235 if (I != TypeIndices.end())
236 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000237
Reid Klecknerac945e22016-06-17 16:11:20 +0000238 // The display name includes function template arguments. Drop them to match
239 // MSVC.
240 StringRef DisplayName = SP->getDisplayName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000241
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000242 const DIScope *Scope = SP->getScope().resolve();
243 TypeIndex TI;
244 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
245 // If the scope is a DICompositeType, then this must be a method. Member
246 // function types take some special handling, and require access to the
247 // subprogram.
248 TypeIndex ClassType = getTypeIndex(Class);
249 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
250 DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000251 TI = TypeTable.writeKnownType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000252 } else {
253 // Otherwise, this must be a free function.
254 TypeIndex ParentScope = getScopeIndex(Scope);
255 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000256 TI = TypeTable.writeKnownType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000257 }
258
259 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000260}
261
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000262TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
263 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000264 // Always use the method declaration as the key for the function type. The
265 // method declaration contains the this adjustment.
266 if (SP->getDeclaration())
267 SP = SP->getDeclaration();
268 assert(!SP->getDeclaration() && "should use declaration as key");
269
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000270 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
271 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000272 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000273 if (I != TypeIndices.end())
274 return I->second;
275
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000276 // Make sure complete type info for the class is emitted *after* the member
277 // function type, as the complete class type is likely to reference this
278 // member function type.
279 TypeLoweringScope S(*this);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000280 TypeIndex TI =
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000281 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000282 return recordTypeIndexForDINode(SP, TI, Class);
283}
284
Amjad Aboudacee5682016-07-12 12:06:34 +0000285TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
286 TypeIndex TI,
287 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000288 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000289 (void)InsertResult;
290 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000291 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000292}
293
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000294unsigned CodeViewDebug::getPointerSizeInBytes() {
295 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
296}
297
Reid Kleckner876330d2016-02-12 21:48:30 +0000298void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
299 const DILocation *InlinedAt) {
300 if (InlinedAt) {
301 // This variable was inlined. Associate it with the InlineSite.
302 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
303 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
304 Site.InlinedLocals.emplace_back(Var);
305 } else {
306 // This variable goes in the main ProcSym.
307 CurFn->Locals.emplace_back(Var);
308 }
309}
310
Reid Kleckner829365a2016-02-11 19:41:47 +0000311static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
312 const DILocation *Loc) {
313 auto B = Locs.begin(), E = Locs.end();
314 if (std::find(B, E, Loc) == E)
315 Locs.push_back(Loc);
316}
317
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000318void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000319 const MachineFunction *MF) {
320 // Skip this instruction if it has the same location as the previous one.
321 if (DL == CurFn->LastLoc)
322 return;
323
324 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000325 if (!Scope)
326 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000327
David Majnemerc3340db2016-01-13 01:05:23 +0000328 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000329 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
330 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
331 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000332 return;
333
Reid Kleckner2214ed82016-01-29 00:49:42 +0000334 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
335 if (CI.getStartColumn() != DL.getCol())
336 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000337
Reid Kleckner2214ed82016-01-29 00:49:42 +0000338 if (!CurFn->HaveLineInfo)
339 CurFn->HaveLineInfo = true;
340 unsigned FileId = 0;
341 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
342 FileId = CurFn->LastFileId;
343 else
344 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
345 CurFn->LastLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000346
347 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000348 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000349 const DILocation *Loc = DL.get();
350
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000351 // If this location was actually inlined from somewhere else, give it the ID
352 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000353 FuncId =
354 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000355
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000356 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000357 bool FirstLoc = true;
358 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000359 InlineSite &Site =
360 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000361 if (!FirstLoc)
362 addLocIfNotPresent(Site.ChildSites, Loc);
363 FirstLoc = false;
364 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000365 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000366 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000367 }
368
Reid Klecknerdac21b42016-02-03 21:15:48 +0000369 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000370 /*PrologueEnd=*/false, /*IsStmt=*/false,
371 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000372}
373
Reid Kleckner5d122f82016-05-25 23:16:12 +0000374void CodeViewDebug::emitCodeViewMagicVersion() {
375 OS.EmitValueToAlignment(4);
376 OS.AddComment("Debug section magic");
377 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
378}
379
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000380void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000381 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000382 return;
383
384 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000385
386 // The COFF .debug$S section consists of several subsections, each starting
387 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
388 // of the payload followed by the payload itself. The subsections are 4-byte
389 // aligned.
390
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000391 // Use the generic .debug$S section, and make a subsection for all the inlined
392 // subprograms.
393 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000394
395 MCSymbol *CompilerInfo = beginCVSubsection(ModuleSubstreamKind::Symbols);
396 emitCompilerInformation();
397 endCVSubsection(CompilerInfo);
398
Reid Kleckner5d122f82016-05-25 23:16:12 +0000399 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000400
Reid Kleckner2214ed82016-01-29 00:49:42 +0000401 // Emit per-function debug information.
402 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000403 if (!P.first->isDeclarationForLinker())
404 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000405
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000406 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000407 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000408 emitDebugInfoForGlobals();
409
Hans Wennborgb510b452016-06-23 16:33:53 +0000410 // Emit retained types.
411 emitDebugInfoForRetainedTypes();
412
Reid Kleckner5d122f82016-05-25 23:16:12 +0000413 // Switch back to the generic .debug$S section after potentially processing
414 // comdat symbol sections.
415 switchToDebugSectionForSymbol(nullptr);
416
David Majnemer3128b102016-06-15 18:00:01 +0000417 // Emit UDT records for any types used by global variables.
418 if (!GlobalUDTs.empty()) {
419 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
420 emitDebugInfoForUDTs(GlobalUDTs);
421 endCVSubsection(SymbolsEnd);
422 }
423
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000424 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000425 OS.AddComment("File index to string table offset subsection");
426 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000427
428 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000429 OS.AddComment("String table");
430 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000431
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000432 // Emit type information last, so that any types we translate while emitting
433 // function info are included.
434 emitTypeInformation();
435
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000436 clear();
437}
438
David Majnemerb9456a52016-03-14 05:15:09 +0000439static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000440 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
441 // after a fixed length portion of the record. The fixed length portion should
442 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
443 // overall record size is less than the maximum allowed.
444 unsigned MaxFixedRecordLength = 0xF00;
445 SmallString<32> NullTerminatedString(
446 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000447 NullTerminatedString.push_back('\0');
448 OS.EmitBytes(NullTerminatedString);
449}
450
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000451void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000452 // Do nothing if we have no debug info or if no non-trivial types were emitted
453 // to TypeTable during codegen.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000454 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
Reid Klecknerfbd77872016-03-18 18:54:32 +0000455 if (!CU_Nodes)
456 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000457 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000458 return;
459
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000460 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000461 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000462 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000463
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000464 SmallString<8> CommentPrefix;
465 if (OS.isVerboseAsm()) {
466 CommentPrefix += '\t';
467 CommentPrefix += Asm->MAI->getCommentString();
468 CommentPrefix += ' ';
469 }
470
471 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
Reid Kleckner2280f932016-05-23 20:23:46 +0000472 TypeTable.ForEachRecord(
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000473 [&](TypeIndex Index, StringRef Record) {
474 if (OS.isVerboseAsm()) {
475 // Emit a block comment describing the type record for readability.
476 SmallString<512> CommentBlock;
477 raw_svector_ostream CommentOS(CommentBlock);
478 ScopedPrinter SP(CommentOS);
479 SP.setPrefix(CommentPrefix);
480 CVTD.setPrinter(&SP);
Reid Klecknerc92e9462016-07-01 18:05:56 +0000481 Error E = CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
482 if (E) {
483 logAllUnhandledErrors(std::move(E), errs(), "error: ");
484 llvm_unreachable("produced malformed type record");
485 }
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000486 // emitRawComment will insert its own tab and comment string before
487 // the first line, so strip off our first one. It also prints its own
488 // newline.
489 OS.emitRawComment(
490 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Reid Klecknerc92e9462016-07-01 18:05:56 +0000491 } else {
492#ifndef NDEBUG
493 // Assert that the type data is valid even if we aren't dumping
494 // comments. The MSVC linker doesn't do much type record validation,
495 // so the first link of an invalid type record can succeed while
496 // subsequent links will fail with LNK1285.
Zachary Turnerd66889c2016-07-28 19:12:28 +0000497 ByteStream Stream({Record.bytes_begin(), Record.bytes_end()});
Reid Klecknerc92e9462016-07-01 18:05:56 +0000498 CVTypeArray Types;
499 StreamReader Reader(Stream);
500 Error E = Reader.readArray(Types, Reader.getLength());
501 if (!E) {
502 TypeVisitorCallbacks C;
503 E = CVTypeVisitor(C).visitTypeStream(Types);
504 }
505 if (E) {
506 logAllUnhandledErrors(std::move(E), errs(), "error: ");
507 llvm_unreachable("produced malformed type record");
508 }
509#endif
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000510 }
511 OS.EmitBinaryData(Record);
Reid Kleckner2280f932016-05-23 20:23:46 +0000512 });
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000513}
514
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000515namespace {
516
517static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
518 switch (DWLang) {
519 case dwarf::DW_LANG_C:
520 case dwarf::DW_LANG_C89:
521 case dwarf::DW_LANG_C99:
522 case dwarf::DW_LANG_C11:
523 case dwarf::DW_LANG_ObjC:
524 return SourceLanguage::C;
525 case dwarf::DW_LANG_C_plus_plus:
526 case dwarf::DW_LANG_C_plus_plus_03:
527 case dwarf::DW_LANG_C_plus_plus_11:
528 case dwarf::DW_LANG_C_plus_plus_14:
529 return SourceLanguage::Cpp;
530 case dwarf::DW_LANG_Fortran77:
531 case dwarf::DW_LANG_Fortran90:
532 case dwarf::DW_LANG_Fortran03:
533 case dwarf::DW_LANG_Fortran08:
534 return SourceLanguage::Fortran;
535 case dwarf::DW_LANG_Pascal83:
536 return SourceLanguage::Pascal;
537 case dwarf::DW_LANG_Cobol74:
538 case dwarf::DW_LANG_Cobol85:
539 return SourceLanguage::Cobol;
540 case dwarf::DW_LANG_Java:
541 return SourceLanguage::Java;
542 default:
543 // There's no CodeView representation for this language, and CV doesn't
544 // have an "unknown" option for the language field, so we'll use MASM,
545 // as it's very low level.
546 return SourceLanguage::Masm;
547 }
548}
549
550struct Version {
551 int Part[4];
552};
553
554// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
555// the version number.
556static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000557 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000558 int N = 0;
559 for (const char C : Name) {
560 if (isdigit(C)) {
561 V.Part[N] *= 10;
562 V.Part[N] += C - '0';
563 } else if (C == '.') {
564 ++N;
565 if (N >= 4)
566 return V;
567 } else if (N > 0)
568 return V;
569 }
570 return V;
571}
572
573static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
574 switch (Type) {
575 case Triple::ArchType::x86:
576 return CPUType::Pentium3;
577 case Triple::ArchType::x86_64:
578 return CPUType::X64;
579 case Triple::ArchType::thumb:
580 return CPUType::Thumb;
581 default:
582 report_fatal_error("target architecture doesn't map to a CodeView "
583 "CPUType");
584 }
585}
586
587} // anonymous namespace
588
589void CodeViewDebug::emitCompilerInformation() {
590 MCContext &Context = MMI->getContext();
591 MCSymbol *CompilerBegin = Context.createTempSymbol(),
592 *CompilerEnd = Context.createTempSymbol();
593 OS.AddComment("Record length");
594 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
595 OS.EmitLabel(CompilerBegin);
596 OS.AddComment("Record kind: S_COMPILE3");
597 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
598 uint32_t Flags = 0;
599
600 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
601 const MDNode *Node = *CUs->operands().begin();
602 const auto *CU = cast<DICompileUnit>(Node);
603
604 // The low byte of the flags indicates the source language.
605 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
606 // TODO: Figure out which other flags need to be set.
607
608 OS.AddComment("Flags and language");
609 OS.EmitIntValue(Flags, 4);
610
611 OS.AddComment("CPUType");
612 CPUType CPU =
613 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
614 OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
615
616 StringRef CompilerVersion = CU->getProducer();
617 Version FrontVer = parseVersion(CompilerVersion);
618 OS.AddComment("Frontend version");
619 for (int N = 0; N < 4; ++N)
620 OS.EmitIntValue(FrontVer.Part[N], 2);
621
622 // Some Microsoft tools, like Binscope, expect a backend version number of at
623 // least 8.something, so we'll coerce the LLVM version into a form that
624 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000625 int Major = 1000 * LLVM_VERSION_MAJOR +
626 10 * LLVM_VERSION_MINOR +
627 LLVM_VERSION_PATCH;
628 // Clamp it for builds that use unusually large version numbers.
629 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
630 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000631 OS.AddComment("Backend version");
632 for (int N = 0; N < 4; ++N)
633 OS.EmitIntValue(BackVer.Part[N], 2);
634
635 OS.AddComment("Null-terminated compiler version string");
636 emitNullTerminatedSymbolName(OS, CompilerVersion);
637
638 OS.EmitLabel(CompilerEnd);
639}
640
Reid Kleckner5d122f82016-05-25 23:16:12 +0000641void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000642 if (InlinedSubprograms.empty())
643 return;
644
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000645 OS.AddComment("Inlinee lines subsection");
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000646 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000647
648 // We don't provide any extra file info.
649 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000650 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000651 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
652
653 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000654 assert(TypeIndices.count({SP, nullptr}));
655 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000656
David Majnemer30579ec2016-02-02 23:18:23 +0000657 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000658 unsigned FileId = maybeRecordFile(SP->getFile());
659 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
660 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000661 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000662 // The filechecksum table uses 8 byte entries for now, and file ids start at
663 // 1.
664 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000665 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000666 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000667 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000668 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000669 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000670 OS.EmitIntValue(SP->getLine(), 4);
671 }
672
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000673 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000674}
675
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000676void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
677 const DILocation *InlinedAt,
678 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000679 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
680 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000681
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000682 assert(TypeIndices.count({Site.Inlinee, nullptr}));
683 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000684
685 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000686 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000687 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000688 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000689 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000690 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000691
Reid Klecknerdac21b42016-02-03 21:15:48 +0000692 OS.AddComment("PtrParent");
693 OS.EmitIntValue(0, 4);
694 OS.AddComment("PtrEnd");
695 OS.EmitIntValue(0, 4);
696 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000697 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000698
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000699 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
700 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000701
702 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000703 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000704
705 OS.EmitLabel(InlineEnd);
706
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000707 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000708
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000709 // Recurse on child inlined call sites before closing the scope.
710 for (const DILocation *ChildSite : Site.ChildSites) {
711 auto I = FI.InlineSites.find(ChildSite);
712 assert(I != FI.InlineSites.end() &&
713 "child site not in function inline site map");
714 emitInlinedCallSite(FI, ChildSite, I->second);
715 }
716
717 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000718 OS.AddComment("Record length");
719 OS.EmitIntValue(2, 2); // RecordLength
720 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000721 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000722}
723
Reid Kleckner5d122f82016-05-25 23:16:12 +0000724void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
725 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
726 // comdat key. A section may be comdat because of -ffunction-sections or
727 // because it is comdat in the IR.
728 MCSectionCOFF *GVSec =
729 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
730 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
731
732 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
733 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
734 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
735
736 OS.SwitchSection(DebugSec);
737
738 // Emit the magic version number if this is the first time we've switched to
739 // this section.
740 if (ComdatDebugSections.insert(DebugSec).second)
741 emitCodeViewMagicVersion();
742}
743
Reid Kleckner2214ed82016-01-29 00:49:42 +0000744void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
745 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000746 // For each function there is a separate subsection
747 // which holds the PC to file:line table.
748 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000749 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000750
Reid Kleckner5d122f82016-05-25 23:16:12 +0000751 // Switch to the to a comdat section, if appropriate.
752 switchToDebugSectionForSymbol(Fn);
753
Reid Klecknerac945e22016-06-17 16:11:20 +0000754 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000755 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000756 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000757 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000758
759 // If we have a display name, build the fully qualified name by walking the
760 // chain of scopes.
David Majnemer67f684e2016-07-28 05:03:22 +0000761 if (!SP->getDisplayName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000762 FuncName =
763 getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000764
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000765 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000766 if (FuncName.empty())
767 FuncName = GlobalValue::getRealLinkageName(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000768
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000769 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000770 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000771 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000772 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000773 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
774 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000775 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000776 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000777 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000778
Reid Kleckner4ad127f2016-09-14 21:49:21 +0000779 if (GV->hasLocalLinkage()) {
780 OS.AddComment("Record kind: S_LPROC32_ID");
781 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
782 } else {
783 OS.AddComment("Record kind: S_GPROC32_ID");
784 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
785 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000786
David Majnemer30579ec2016-02-02 23:18:23 +0000787 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000788 OS.AddComment("PtrParent");
789 OS.EmitIntValue(0, 4);
790 OS.AddComment("PtrEnd");
791 OS.EmitIntValue(0, 4);
792 OS.AddComment("PtrNext");
793 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000794 // This is the important bit that tells the debugger where the function
795 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000796 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000797 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000798 OS.AddComment("Offset after prologue");
799 OS.EmitIntValue(0, 4);
800 OS.AddComment("Offset before epilogue");
801 OS.EmitIntValue(0, 4);
802 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000803 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000804 OS.AddComment("Function section relative address");
805 OS.EmitCOFFSecRel32(Fn);
806 OS.AddComment("Function section index");
807 OS.EmitCOFFSectionIndex(Fn);
808 OS.AddComment("Flags");
809 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000810 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000811 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000812 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000813 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000814 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000815
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000816 emitLocalVariableList(FI.Locals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000817
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000818 // Emit inlined call site information. Only emit functions inlined directly
819 // into the parent function. We'll emit the other sites recursively as part
820 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000821 for (const DILocation *InlinedAt : FI.ChildSites) {
822 auto I = FI.InlineSites.find(InlinedAt);
823 assert(I != FI.InlineSites.end() &&
824 "child site not in function inline site map");
825 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000826 }
827
David Majnemer3128b102016-06-15 18:00:01 +0000828 if (SP != nullptr)
829 emitDebugInfoForUDTs(LocalUDTs);
830
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000831 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000832 OS.AddComment("Record length");
833 OS.EmitIntValue(0x0002, 2);
834 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000835 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000836 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000837 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000838
Reid Kleckner2214ed82016-01-29 00:49:42 +0000839 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000840 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000841}
842
Reid Kleckner876330d2016-02-12 21:48:30 +0000843CodeViewDebug::LocalVarDefRange
844CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
845 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000846 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000847 DR.DataOffset = Offset;
848 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000849 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000850 DR.StructOffset = 0;
851 DR.CVRegister = CVRegister;
852 return DR;
853}
854
855CodeViewDebug::LocalVarDefRange
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000856CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
857 int Offset, bool IsSubfield,
858 uint16_t StructOffset) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000859 LocalVarDefRange DR;
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000860 DR.InMemory = InMemory;
861 DR.DataOffset = Offset;
862 DR.IsSubfield = IsSubfield;
863 DR.StructOffset = StructOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +0000864 DR.CVRegister = CVRegister;
865 return DR;
866}
867
868void CodeViewDebug::collectVariableInfoFromMMITable(
869 DenseSet<InlinedVariable> &Processed) {
870 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
871 const TargetFrameLowering *TFI = TSI.getFrameLowering();
872 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
873
874 for (const MachineModuleInfo::VariableDbgInfo &VI :
875 MMI->getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000876 if (!VI.Var)
877 continue;
878 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
879 "Expected inlined-at fields to agree");
880
Reid Kleckner876330d2016-02-12 21:48:30 +0000881 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000882 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
883
884 // If variable scope is not found then skip this variable.
885 if (!Scope)
886 continue;
887
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000888 // Get the frame register used and the offset.
889 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000890 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
891 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000892
893 // Calculate the label ranges.
Reid Kleckner876330d2016-02-12 21:48:30 +0000894 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000895 for (const InsnRange &Range : Scope->getRanges()) {
896 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
897 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000898 End = End ? End : Asm->getFunctionEnd();
899 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000900 }
901
Reid Kleckner876330d2016-02-12 21:48:30 +0000902 LocalVariable Var;
903 Var.DIVar = VI.Var;
904 Var.DefRanges.emplace_back(std::move(DefRange));
905 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
906 }
907}
908
909void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
910 DenseSet<InlinedVariable> Processed;
911 // Grab the variable info that was squirreled away in the MMI side-table.
912 collectVariableInfoFromMMITable(Processed);
913
914 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
915
916 for (const auto &I : DbgValues) {
917 InlinedVariable IV = I.first;
918 if (Processed.count(IV))
919 continue;
920 const DILocalVariable *DIVar = IV.first;
921 const DILocation *InlinedAt = IV.second;
922
923 // Instruction ranges, specifying where IV is accessible.
924 const auto &Ranges = I.second;
925
926 LexicalScope *Scope = nullptr;
927 if (InlinedAt)
928 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
929 else
930 Scope = LScopes.findLexicalScope(DIVar->getScope());
931 // If variable scope is not found then skip this variable.
932 if (!Scope)
933 continue;
934
935 LocalVariable Var;
936 Var.DIVar = DIVar;
937
938 // Calculate the definition ranges.
939 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
940 const InsnRange &Range = *I;
941 const MachineInstr *DVInst = Range.first;
942 assert(DVInst->isDebugValue() && "Invalid History entry");
943 const DIExpression *DIExpr = DVInst->getDebugExpression();
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000944 bool IsSubfield = false;
945 unsigned StructOffset = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000946
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000947 // Handle bitpieces.
948 if (DIExpr && DIExpr->isBitPiece()) {
949 IsSubfield = true;
950 StructOffset = DIExpr->getBitPieceOffset() / 8;
951 } else if (DIExpr && DIExpr->getNumElements() > 0) {
952 continue; // Ignore unrecognized exprs.
953 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000954
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000955 // Bail if operand 0 is not a valid register. This means the variable is a
956 // simple constant, or is described by a complex expression.
957 // FIXME: Find a way to represent constant variables, since they are
958 // relatively common.
959 unsigned Reg =
960 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
961 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000962 continue;
963
Reid Kleckner876330d2016-02-12 21:48:30 +0000964 // Handle the two cases we can handle: indirect in memory and in register.
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000965 unsigned CVReg = TRI->getCodeViewRegNum(Reg);
966 bool InMemory = DVInst->getOperand(1).isImm();
967 int Offset = InMemory ? DVInst->getOperand(1).getImm() : 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000968 {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000969 LocalVarDefRange DR;
970 DR.CVRegister = CVReg;
971 DR.InMemory = InMemory;
972 DR.DataOffset = Offset;
973 DR.IsSubfield = IsSubfield;
974 DR.StructOffset = StructOffset;
975
Reid Kleckner876330d2016-02-12 21:48:30 +0000976 if (Var.DefRanges.empty() ||
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000977 Var.DefRanges.back().isDifferentLocation(DR)) {
978 Var.DefRanges.emplace_back(std::move(DR));
Reid Kleckner876330d2016-02-12 21:48:30 +0000979 }
980 }
981
982 // Compute the label range.
983 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
984 const MCSymbol *End = getLabelAfterInsn(Range.second);
985 if (!End) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000986 // This range is valid until the next overlapping bitpiece. In the
987 // common case, ranges will not be bitpieces, so they will overlap.
988 auto J = std::next(I);
989 while (J != E && !piecesOverlap(DIExpr, J->first->getDebugExpression()))
990 ++J;
991 if (J != E)
992 End = getLabelBeforeInsn(J->first);
Reid Kleckner876330d2016-02-12 21:48:30 +0000993 else
994 End = Asm->getFunctionEnd();
995 }
996
997 // If the last range end is our begin, just extend the last range.
998 // Otherwise make a new range.
999 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
1000 Var.DefRanges.back().Ranges;
1001 if (!Ranges.empty() && Ranges.back().second == Begin)
1002 Ranges.back().second = End;
1003 else
1004 Ranges.emplace_back(Begin, End);
1005
1006 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001007 }
Reid Kleckner876330d2016-02-12 21:48:30 +00001008
1009 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001010 }
1011}
1012
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001013void CodeViewDebug::beginFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001014 assert(!CurFn && "Can't process two functions at once!");
1015
David Majnemer67f684e2016-07-28 05:03:22 +00001016 if (!Asm || !MMI->hasDebugInfo() || !MF->getFunction()->getSubprogram())
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001017 return;
1018
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001019 DebugHandlerBase::beginFunction(MF);
1020
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001021 const Function *GV = MF->getFunction();
1022 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001023 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +00001024 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001025 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001026
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001027 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1028
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001029 // Find the end of the function prolog. First known non-DBG_VALUE and
1030 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001031 // FIXME: is there a simpler a way to do this? Can we just search
1032 // for the first instruction of the function, not the last of the prolog?
1033 DebugLoc PrologEndLoc;
1034 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001035 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001036 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001037 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1038 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001039 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001040 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001041 } else if (!MI.isDebugValue()) {
1042 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001043 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001044 }
1045 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001046
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001047 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001048 if (PrologEndLoc && !EmptyPrologue) {
1049 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001050 maybeRecordLocation(FnStartDL, MF);
1051 }
1052}
1053
Hans Wennborg4b63a982016-06-23 22:57:25 +00001054void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001055 // Don't record empty UDTs.
1056 if (Ty->getName().empty())
1057 return;
1058
Hans Wennborg4b63a982016-06-23 22:57:25 +00001059 SmallVector<StringRef, 5> QualifiedNameComponents;
1060 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1061 Ty->getScope().resolve(), QualifiedNameComponents);
1062
1063 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001064 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001065
1066 if (ClosestSubprogram == nullptr)
1067 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1068 else if (ClosestSubprogram == CurrentSubprogram)
1069 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1070
1071 // TODO: What if the ClosestSubprogram is neither null or the current
1072 // subprogram? Currently, the UDT just gets dropped on the floor.
1073 //
1074 // The current behavior is not desirable. To get maximal fidelity, we would
1075 // need to perform all type translation before beginning emission of .debug$S
1076 // and then make LocalUDTs a member of FunctionInfo
1077}
1078
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001079TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001080 // Generic dispatch for lowering an unknown type.
1081 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001082 case dwarf::DW_TAG_array_type:
1083 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001084 case dwarf::DW_TAG_typedef:
1085 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001086 case dwarf::DW_TAG_base_type:
1087 return lowerTypeBasic(cast<DIBasicType>(Ty));
1088 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001089 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1090 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1091 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001092 case dwarf::DW_TAG_reference_type:
1093 case dwarf::DW_TAG_rvalue_reference_type:
1094 return lowerTypePointer(cast<DIDerivedType>(Ty));
1095 case dwarf::DW_TAG_ptr_to_member_type:
1096 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1097 case dwarf::DW_TAG_const_type:
1098 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001099 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001100 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001101 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001102 if (ClassTy) {
1103 // The member function type of a member function pointer has no
1104 // ThisAdjustment.
1105 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1106 /*ThisAdjustment=*/0);
1107 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001108 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001109 case dwarf::DW_TAG_enumeration_type:
1110 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001111 case dwarf::DW_TAG_class_type:
1112 case dwarf::DW_TAG_structure_type:
1113 return lowerTypeClass(cast<DICompositeType>(Ty));
1114 case dwarf::DW_TAG_union_type:
1115 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001116 default:
1117 // Use the null type index.
1118 return TypeIndex();
1119 }
1120}
1121
David Majnemerd065e232016-06-02 06:21:37 +00001122TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001123 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1124 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001125 StringRef TypeName = Ty->getName();
1126
Hans Wennborg4b63a982016-06-23 22:57:25 +00001127 addToUDTs(Ty, UnderlyingTypeIndex);
David Majnemer3128b102016-06-15 18:00:01 +00001128
David Majnemerd065e232016-06-02 06:21:37 +00001129 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001130 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001131 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001132 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001133 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001134 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001135
David Majnemerd065e232016-06-02 06:21:37 +00001136 return UnderlyingTypeIndex;
1137}
1138
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001139TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1140 DITypeRef ElementTypeRef = Ty->getBaseType();
1141 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1142 // IndexType is size_t, which depends on the bitness of the target.
1143 TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
1144 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1145 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001146
1147 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1148
Amjad Aboudacee5682016-07-12 12:06:34 +00001149
Reid Kleckner10762882016-09-09 17:29:36 +00001150 // We want to assert that the element type multiplied by the array lengths
1151 // match the size of the overall array. However, if we don't have complete
1152 // type information for the base type, we can't make this assertion. This
1153 // happens if limited debug info is enabled in this case:
1154 // struct VTableOptzn { VTableOptzn(); virtual ~VTableOptzn(); };
1155 // VTableOptzn array[3];
1156 // The DICompositeType of VTableOptzn will have size zero, and the array will
1157 // have size 3 * sizeof(void*), and we should avoid asserting.
1158 //
1159 // There is a related bug in the front-end where an array of a structure,
1160 // which was declared as incomplete structure first, ends up not getting a
1161 // size assigned to it. (PR28303)
Amjad Aboudacee5682016-07-12 12:06:34 +00001162 // Example:
1163 // struct A(*p)[3];
1164 // struct A { int f; } a[3];
Reid Kleckner10762882016-09-09 17:29:36 +00001165 bool PartiallyIncomplete = false;
1166 if (Ty->getSizeInBits() == 0 || ElementSize == 0) {
1167 PartiallyIncomplete = true;
Amjad Aboudacee5682016-07-12 12:06:34 +00001168 }
1169
1170 // Add subranges to array type.
1171 DINodeArray Elements = Ty->getElements();
1172 for (int i = Elements.size() - 1; i >= 0; --i) {
1173 const DINode *Element = Elements[i];
1174 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1175
1176 const DISubrange *Subrange = cast<DISubrange>(Element);
1177 assert(Subrange->getLowerBound() == 0 &&
1178 "codeview doesn't support subranges with lower bounds");
1179 int64_t Count = Subrange->getCount();
1180
1181 // Variable Length Array (VLA) has Count equal to '-1'.
1182 // Replace with Count '1', assume it is the minimum VLA length.
1183 // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
1184 if (Count == -1) {
1185 Count = 1;
Reid Kleckner10762882016-09-09 17:29:36 +00001186 PartiallyIncomplete = true;
Amjad Aboudacee5682016-07-12 12:06:34 +00001187 }
1188
Amjad Aboudacee5682016-07-12 12:06:34 +00001189 // Update the element size and element type index for subsequent subranges.
1190 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001191
1192 // If this is the outermost array, use the size from the array. It will be
1193 // more accurate if PartiallyIncomplete is true.
1194 uint64_t ArraySize =
1195 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1196
1197 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001198 ElementTypeIndex = TypeTable.writeKnownType(
Reid Kleckner10762882016-09-09 17:29:36 +00001199 ArrayRecord(ElementTypeIndex, IndexType, ArraySize, Name));
Amjad Aboudacee5682016-07-12 12:06:34 +00001200 }
1201
Reid Kleckner10762882016-09-09 17:29:36 +00001202 (void)PartiallyIncomplete;
1203 assert(PartiallyIncomplete || ElementSize == (Ty->getSizeInBits() / 8));
Amjad Aboudacee5682016-07-12 12:06:34 +00001204
1205 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001206}
1207
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001208TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1209 TypeIndex Index;
1210 dwarf::TypeKind Kind;
1211 uint32_t ByteSize;
1212
1213 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001214 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001215
1216 SimpleTypeKind STK = SimpleTypeKind::None;
1217 switch (Kind) {
1218 case dwarf::DW_ATE_address:
1219 // FIXME: Translate
1220 break;
1221 case dwarf::DW_ATE_boolean:
1222 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001223 case 1: STK = SimpleTypeKind::Boolean8; break;
1224 case 2: STK = SimpleTypeKind::Boolean16; break;
1225 case 4: STK = SimpleTypeKind::Boolean32; break;
1226 case 8: STK = SimpleTypeKind::Boolean64; break;
1227 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001228 }
1229 break;
1230 case dwarf::DW_ATE_complex_float:
1231 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001232 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001233 case 4: STK = SimpleTypeKind::Complex32; break;
1234 case 8: STK = SimpleTypeKind::Complex64; break;
1235 case 10: STK = SimpleTypeKind::Complex80; break;
1236 case 16: STK = SimpleTypeKind::Complex128; break;
1237 }
1238 break;
1239 case dwarf::DW_ATE_float:
1240 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001241 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001242 case 4: STK = SimpleTypeKind::Float32; break;
1243 case 6: STK = SimpleTypeKind::Float48; break;
1244 case 8: STK = SimpleTypeKind::Float64; break;
1245 case 10: STK = SimpleTypeKind::Float80; break;
1246 case 16: STK = SimpleTypeKind::Float128; break;
1247 }
1248 break;
1249 case dwarf::DW_ATE_signed:
1250 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001251 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1252 case 2: STK = SimpleTypeKind::Int16Short; break;
1253 case 4: STK = SimpleTypeKind::Int32; break;
1254 case 8: STK = SimpleTypeKind::Int64Quad; break;
1255 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001256 }
1257 break;
1258 case dwarf::DW_ATE_unsigned:
1259 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001260 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1261 case 2: STK = SimpleTypeKind::UInt16Short; break;
1262 case 4: STK = SimpleTypeKind::UInt32; break;
1263 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1264 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001265 }
1266 break;
1267 case dwarf::DW_ATE_UTF:
1268 switch (ByteSize) {
1269 case 2: STK = SimpleTypeKind::Character16; break;
1270 case 4: STK = SimpleTypeKind::Character32; break;
1271 }
1272 break;
1273 case dwarf::DW_ATE_signed_char:
1274 if (ByteSize == 1)
1275 STK = SimpleTypeKind::SignedCharacter;
1276 break;
1277 case dwarf::DW_ATE_unsigned_char:
1278 if (ByteSize == 1)
1279 STK = SimpleTypeKind::UnsignedCharacter;
1280 break;
1281 default:
1282 break;
1283 }
1284
1285 // Apply some fixups based on the source-level type name.
1286 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1287 STK = SimpleTypeKind::Int32Long;
1288 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1289 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001290 if (STK == SimpleTypeKind::UInt16Short &&
1291 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001292 STK = SimpleTypeKind::WideCharacter;
1293 if ((STK == SimpleTypeKind::SignedCharacter ||
1294 STK == SimpleTypeKind::UnsignedCharacter) &&
1295 Ty->getName() == "char")
1296 STK = SimpleTypeKind::NarrowCharacter;
1297
1298 return TypeIndex(STK);
1299}
1300
1301TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1302 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1303
1304 // Pointers to simple types can use SimpleTypeMode, rather than having a
1305 // dedicated pointer type record.
1306 if (PointeeTI.isSimple() &&
1307 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1308 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1309 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1310 ? SimpleTypeMode::NearPointer64
1311 : SimpleTypeMode::NearPointer32;
1312 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1313 }
1314
1315 PointerKind PK =
1316 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1317 PointerMode PM = PointerMode::Pointer;
1318 switch (Ty->getTag()) {
1319 default: llvm_unreachable("not a pointer tag type");
1320 case dwarf::DW_TAG_pointer_type:
1321 PM = PointerMode::Pointer;
1322 break;
1323 case dwarf::DW_TAG_reference_type:
1324 PM = PointerMode::LValueReference;
1325 break;
1326 case dwarf::DW_TAG_rvalue_reference_type:
1327 PM = PointerMode::RValueReference;
1328 break;
1329 }
1330 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1331 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1332 // do.
1333 PointerOptions PO = PointerOptions::None;
1334 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001335 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001336}
1337
Reid Kleckner6fa15462016-06-17 22:14:39 +00001338static PointerToMemberRepresentation
1339translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1340 // SizeInBytes being zero generally implies that the member pointer type was
1341 // incomplete, which can happen if it is part of a function prototype. In this
1342 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001343 if (IsPMF) {
1344 switch (Flags & DINode::FlagPtrToMemberRep) {
1345 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001346 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1347 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001348 case DINode::FlagSingleInheritance:
1349 return PointerToMemberRepresentation::SingleInheritanceFunction;
1350 case DINode::FlagMultipleInheritance:
1351 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1352 case DINode::FlagVirtualInheritance:
1353 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1354 }
1355 } else {
1356 switch (Flags & DINode::FlagPtrToMemberRep) {
1357 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001358 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1359 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001360 case DINode::FlagSingleInheritance:
1361 return PointerToMemberRepresentation::SingleInheritanceData;
1362 case DINode::FlagMultipleInheritance:
1363 return PointerToMemberRepresentation::MultipleInheritanceData;
1364 case DINode::FlagVirtualInheritance:
1365 return PointerToMemberRepresentation::VirtualInheritanceData;
1366 }
1367 }
1368 llvm_unreachable("invalid ptr to member representation");
1369}
1370
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001371TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1372 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1373 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001374 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001375 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
1376 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001377 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1378 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1379 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001380 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001381 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1382 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1383 MemberPointerInfo MPI(
1384 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001385 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001386 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001387}
1388
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001389/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1390/// have a translation, use the NearC convention.
1391static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1392 switch (DwarfCC) {
1393 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1394 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1395 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1396 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1397 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1398 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1399 }
1400 return CallingConvention::NearC;
1401}
1402
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001403TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1404 ModifierOptions Mods = ModifierOptions::None;
1405 bool IsModifier = true;
1406 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001407 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001408 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001409 switch (BaseTy->getTag()) {
1410 case dwarf::DW_TAG_const_type:
1411 Mods |= ModifierOptions::Const;
1412 break;
1413 case dwarf::DW_TAG_volatile_type:
1414 Mods |= ModifierOptions::Volatile;
1415 break;
1416 default:
1417 IsModifier = false;
1418 break;
1419 }
1420 if (IsModifier)
1421 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1422 }
1423 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Reid Klecknerdbaa61c2016-08-30 21:48:14 +00001424 return TypeTable.writeKnownType(ModifierRecord(ModifiedTI, Mods));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001425}
1426
David Majnemer75c3ebf2016-06-02 17:13:53 +00001427TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1428 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1429 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1430 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1431
1432 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1433 ArrayRef<TypeIndex> ArgTypeIndices = None;
1434 if (!ReturnAndArgTypeIndices.empty()) {
1435 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1436 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1437 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1438 }
1439
1440 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001441 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001442
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001443 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1444
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001445 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1446 ArgTypeIndices.size(), ArgListIndex);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001447 return TypeTable.writeKnownType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001448}
1449
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001450TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001451 const DIType *ClassTy,
1452 int ThisAdjustment) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001453 // Lower the containing class type.
1454 TypeIndex ClassType = getTypeIndex(ClassTy);
1455
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001456 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1457 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1458 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1459
1460 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1461 ArrayRef<TypeIndex> ArgTypeIndices = None;
1462 if (!ReturnAndArgTypeIndices.empty()) {
1463 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1464 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1465 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1466 }
1467 TypeIndex ThisTypeIndex = TypeIndex::Void();
1468 if (!ArgTypeIndices.empty()) {
1469 ThisTypeIndex = ArgTypeIndices.front();
1470 ArgTypeIndices = ArgTypeIndices.drop_front();
1471 }
1472
1473 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001474 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001475
1476 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1477
1478 // TODO: Need to use the correct values for:
1479 // FunctionOptions
1480 // ThisPointerAdjustment.
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001481 TypeIndex TI = TypeTable.writeKnownType(MemberFunctionRecord(
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001482 ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001483 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001484
1485 return TI;
1486}
1487
Reid Kleckner9dac4732016-08-31 15:59:30 +00001488TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
1489 unsigned VSlotCount = Ty->getSizeInBits() / (8 * Asm->MAI->getPointerSize());
1490 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
1491 return TypeTable.writeKnownType(VFTableShapeRecord(Slots));
1492}
1493
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001494static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1495 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001496 case DINode::FlagPrivate: return MemberAccess::Private;
1497 case DINode::FlagPublic: return MemberAccess::Public;
1498 case DINode::FlagProtected: return MemberAccess::Protected;
1499 case 0:
1500 // If there was no explicit access control, provide the default for the tag.
1501 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1502 : MemberAccess::Public;
1503 }
1504 llvm_unreachable("access flags are exclusive");
1505}
1506
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001507static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1508 if (SP->isArtificial())
1509 return MethodOptions::CompilerGenerated;
1510
1511 // FIXME: Handle other MethodOptions.
1512
1513 return MethodOptions::None;
1514}
1515
1516static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1517 bool Introduced) {
1518 switch (SP->getVirtuality()) {
1519 case dwarf::DW_VIRTUALITY_none:
1520 break;
1521 case dwarf::DW_VIRTUALITY_virtual:
1522 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1523 case dwarf::DW_VIRTUALITY_pure_virtual:
1524 return Introduced ? MethodKind::PureIntroducingVirtual
1525 : MethodKind::PureVirtual;
1526 default:
1527 llvm_unreachable("unhandled virtuality case");
1528 }
1529
1530 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1531
1532 return MethodKind::Vanilla;
1533}
1534
Reid Klecknera8d57402016-06-03 15:58:20 +00001535static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1536 switch (Ty->getTag()) {
1537 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1538 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1539 }
1540 llvm_unreachable("unexpected tag");
1541}
1542
Reid Klecknere092dad2016-07-02 00:11:07 +00001543/// Return ClassOptions that should be present on both the forward declaration
1544/// and the defintion of a tag type.
1545static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1546 ClassOptions CO = ClassOptions::None;
1547
1548 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001549 // appear to give every type a linkage name, which may be problematic for us.
1550 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001551 if (!Ty->getIdentifier().empty())
1552 CO |= ClassOptions::HasUniqueName;
1553
1554 // Put the Nested flag on a type if it appears immediately inside a tag type.
1555 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1556 // here. That flag is only set on definitions, and not forward declarations.
1557 const DIScope *ImmediateScope = Ty->getScope().resolve();
1558 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1559 CO |= ClassOptions::Nested;
1560
1561 // Put the Scoped flag on function-local types.
1562 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1563 Scope = Scope->getScope().resolve()) {
1564 if (isa<DISubprogram>(Scope)) {
1565 CO |= ClassOptions::Scoped;
1566 break;
1567 }
1568 }
1569
1570 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001571}
1572
David Majnemer979cb882016-06-16 21:32:16 +00001573TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001574 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001575 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001576 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001577
David Majnemerda9548f2016-06-17 16:13:21 +00001578 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001579 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001580 } else {
1581 FieldListRecordBuilder Fields;
1582 for (const DINode *Element : Ty->getElements()) {
1583 // We assume that the frontend provides all members in source declaration
1584 // order, which is what MSVC does.
1585 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001586 Fields.writeMemberType(EnumeratorRecord(
David Majnemerda9548f2016-06-17 16:13:21 +00001587 MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()),
1588 Enumerator->getName()));
1589 EnumeratorCount++;
1590 }
1591 }
1592 FTI = TypeTable.writeFieldList(Fields);
1593 }
David Majnemer979cb882016-06-16 21:32:16 +00001594
David Majnemer6bdc24e2016-07-01 23:12:45 +00001595 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001596
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001597 return TypeTable.writeKnownType(EnumRecord(EnumeratorCount, CO, FTI, FullName,
1598 Ty->getIdentifier(),
1599 getTypeIndex(Ty->getBaseType())));
David Majnemer979cb882016-06-16 21:32:16 +00001600}
1601
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001602//===----------------------------------------------------------------------===//
1603// ClassInfo
1604//===----------------------------------------------------------------------===//
1605
1606struct llvm::ClassInfo {
1607 struct MemberInfo {
1608 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001609 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001610 };
1611 // [MemberInfo]
1612 typedef std::vector<MemberInfo> MemberList;
1613
Reid Kleckner156a7232016-06-22 18:31:14 +00001614 typedef TinyPtrVector<const DISubprogram *> MethodsList;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001615 // MethodName -> MethodsList
1616 typedef MapVector<MDString *, MethodsList> MethodsMap;
1617
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001618 /// Base classes.
1619 std::vector<const DIDerivedType *> Inheritance;
1620
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001621 /// Direct members.
1622 MemberList Members;
1623 // Direct overloaded methods gathered by name.
1624 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001625
Reid Kleckner9dac4732016-08-31 15:59:30 +00001626 TypeIndex VShapeTI;
1627
Adrian McCarthy820ca542016-07-06 19:49:51 +00001628 std::vector<const DICompositeType *> NestedClasses;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001629};
1630
1631void CodeViewDebug::clear() {
1632 assert(CurFn == nullptr);
1633 FileIdMap.clear();
1634 FnDebugInfo.clear();
1635 FileToFilepathMap.clear();
1636 LocalUDTs.clear();
1637 GlobalUDTs.clear();
1638 TypeIndices.clear();
1639 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001640}
1641
1642void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1643 const DIDerivedType *DDTy) {
1644 if (!DDTy->getName().empty()) {
1645 Info.Members.push_back({DDTy, 0});
1646 return;
1647 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001648 // An unnamed member must represent a nested struct or union. Add all the
1649 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001650 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00001651 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001652 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001653 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001654 ClassInfo NestedInfo = collectClassInfo(DCTy);
1655 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001656 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001657 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001658}
1659
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001660ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1661 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001662 // Add elements to structure type.
1663 DINodeArray Elements = Ty->getElements();
1664 for (auto *Element : Elements) {
1665 // We assume that the frontend provides all members in source declaration
1666 // order, which is what MSVC does.
1667 if (!Element)
1668 continue;
1669 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001670 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001671 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001672 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001673 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001674 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1675 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001676 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1677 DDTy->getName() == "__vtbl_ptr_type") {
1678 Info.VShapeTI = getTypeIndex(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001679 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1680 // Ignore friend members. It appears that MSVC emitted info about
1681 // friends in the past, but modern versions do not.
1682 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001683 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1684 Info.NestedClasses.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001685 }
1686 // Skip other unrecognized kinds of elements.
1687 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001688 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001689}
1690
Reid Klecknera8d57402016-06-03 15:58:20 +00001691TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1692 // First, construct the forward decl. Don't look into Ty to compute the
1693 // forward decl options, since it might not be available in all TUs.
1694 TypeRecordKind Kind = getRecordKind(Ty);
1695 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001696 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001697 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner7251ede2016-11-02 17:05:19 +00001698 TypeIndex FwdDeclTI = TypeTable.writeKnownType(
1699 ClassRecord(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
1700 FullName, Ty->getIdentifier()));
Reid Kleckner643dd832016-06-22 17:15:28 +00001701 if (!Ty->isForwardDecl())
1702 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001703 return FwdDeclTI;
1704}
1705
1706TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1707 // Construct the field list and complete type record.
1708 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00001709 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001710 TypeIndex FieldTI;
1711 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001712 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001713 bool ContainsNestedClass;
1714 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1715 lowerRecordFieldList(Ty);
1716
1717 if (ContainsNestedClass)
1718 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00001719
David Majnemer6bdc24e2016-07-01 23:12:45 +00001720 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001721
Reid Klecknera8d57402016-06-03 15:58:20 +00001722 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001723
Zachary Turner7251ede2016-11-02 17:05:19 +00001724 TypeIndex ClassTI = TypeTable.writeKnownType(
1725 ClassRecord(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
1726 SizeInBytes, FullName, Ty->getIdentifier()));
Hans Wennborg9a519a02016-06-22 21:22:13 +00001727
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001728 TypeTable.writeKnownType(UdtSourceLineRecord(
1729 ClassTI, TypeTable.writeKnownType(StringIdRecord(
Hans Wennborg9a519a02016-06-22 21:22:13 +00001730 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1731 Ty->getLine()));
1732
Hans Wennborg4b63a982016-06-23 22:57:25 +00001733 addToUDTs(Ty, ClassTI);
1734
Hans Wennborg9a519a02016-06-22 21:22:13 +00001735 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001736}
1737
1738TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1739 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001740 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001741 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner7251ede2016-11-02 17:05:19 +00001742 TypeIndex FwdDeclTI = TypeTable.writeKnownType(
1743 UnionRecord(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier()));
Reid Kleckner643dd832016-06-22 17:15:28 +00001744 if (!Ty->isForwardDecl())
1745 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001746 return FwdDeclTI;
1747}
1748
1749TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00001750 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001751 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001752 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001753 bool ContainsNestedClass;
1754 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1755 lowerRecordFieldList(Ty);
1756
1757 if (ContainsNestedClass)
1758 CO |= ClassOptions::ContainsNestedClass;
1759
Reid Klecknera8d57402016-06-03 15:58:20 +00001760 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00001761 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001762
Zachary Turner7251ede2016-11-02 17:05:19 +00001763 TypeIndex UnionTI = TypeTable.writeKnownType(UnionRecord(
1764 FieldCount, CO, FieldTI, SizeInBytes, FullName, Ty->getIdentifier()));
Hans Wennborg9a519a02016-06-22 21:22:13 +00001765
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001766 TypeTable.writeKnownType(UdtSourceLineRecord(
1767 UnionTI, TypeTable.writeKnownType(StringIdRecord(
Hans Wennborg9a519a02016-06-22 21:22:13 +00001768 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1769 Ty->getLine()));
1770
Hans Wennborg4b63a982016-06-23 22:57:25 +00001771 addToUDTs(Ty, UnionTI);
1772
Hans Wennborg9a519a02016-06-22 21:22:13 +00001773 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001774}
1775
Adrian McCarthy820ca542016-07-06 19:49:51 +00001776std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00001777CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1778 // Manually count members. MSVC appears to count everything that generates a
1779 // field list record. Each individual overload in a method overload group
1780 // contributes to this count, even though the overload group is a single field
1781 // list record.
1782 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001783 ClassInfo Info = collectClassInfo(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001784 FieldListRecordBuilder Fields;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001785
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001786 // Create base classes.
1787 for (const DIDerivedType *I : Info.Inheritance) {
1788 if (I->getFlags() & DINode::FlagVirtual) {
1789 // Virtual base.
1790 // FIXME: Emit VBPtrOffset when the frontend provides it.
1791 unsigned VBPtrOffset = 0;
1792 // FIXME: Despite the accessor name, the offset is really in bytes.
1793 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00001794 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
1795 ? TypeRecordKind::IndirectVirtualBaseClass
1796 : TypeRecordKind::VirtualBaseClass;
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001797 Fields.writeMemberType(VirtualBaseClassRecord(
Bob Haarman26a87bd2016-10-25 22:11:52 +00001798 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001799 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
1800 VBTableIndex));
1801 } else {
1802 assert(I->getOffsetInBits() % 8 == 0 &&
1803 "bases must be on byte boundaries");
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001804 Fields.writeMemberType(BaseClassRecord(
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001805 translateAccessFlags(Ty->getTag(), I->getFlags()),
1806 getTypeIndex(I->getBaseType()), I->getOffsetInBits() / 8));
1807 }
1808 }
1809
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001810 // Create members.
1811 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1812 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1813 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00001814 StringRef MemberName = Member->getName();
1815 MemberAccess Access =
1816 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001817
1818 if (Member->isStaticMember()) {
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001819 Fields.writeMemberType(
David Majnemer9319cbc2016-06-30 03:00:20 +00001820 StaticDataMemberRecord(Access, MemberBaseType, MemberName));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001821 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001822 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001823 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001824
Reid Kleckner9dac4732016-08-31 15:59:30 +00001825 // Virtual function pointer member.
1826 if ((Member->getFlags() & DINode::FlagArtificial) &&
1827 Member->getName().startswith("_vptr$")) {
1828 Fields.writeMemberType(VFPtrRecord(getTypeIndex(Member->getBaseType())));
1829 MemberCount++;
1830 continue;
1831 }
1832
David Majnemer9319cbc2016-06-30 03:00:20 +00001833 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00001834 uint64_t MemberOffsetInBits =
1835 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001836 if (Member->isBitField()) {
1837 uint64_t StartBitOffset = MemberOffsetInBits;
1838 if (const auto *CI =
1839 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00001840 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001841 }
1842 StartBitOffset -= MemberOffsetInBits;
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001843 MemberBaseType = TypeTable.writeKnownType(BitFieldRecord(
David Majnemer9319cbc2016-06-30 03:00:20 +00001844 MemberBaseType, Member->getSizeInBits(), StartBitOffset));
1845 }
1846 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001847 Fields.writeMemberType(DataMemberRecord(Access, MemberBaseType,
David Majnemer9319cbc2016-06-30 03:00:20 +00001848 MemberOffsetInBytes, MemberName));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001849 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001850 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001851
1852 // Create methods
1853 for (auto &MethodItr : Info.Methods) {
1854 StringRef Name = MethodItr.first->getString();
1855
1856 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00001857 for (const DISubprogram *SP : MethodItr.second) {
1858 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1859 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001860
1861 unsigned VFTableOffset = -1;
1862 if (Introduced)
1863 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1864
Zachary Turner7251ede2016-11-02 17:05:19 +00001865 Methods.push_back(OneMethodRecord(
1866 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
1867 translateMethodKindFlags(SP, Introduced),
1868 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001869 MemberCount++;
1870 }
1871 assert(Methods.size() > 0 && "Empty methods map entry");
1872 if (Methods.size() == 1)
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001873 Fields.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001874 else {
1875 TypeIndex MethodList =
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001876 TypeTable.writeKnownType(MethodOverloadListRecord(Methods));
1877 Fields.writeMemberType(
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001878 OverloadedMethodRecord(Methods.size(), MethodList, Name));
1879 }
1880 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001881
1882 // Create nested classes.
1883 for (const DICompositeType *Nested : Info.NestedClasses) {
1884 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001885 Fields.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00001886 MemberCount++;
1887 }
1888
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001889 TypeIndex FieldTI = TypeTable.writeFieldList(Fields);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001890 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Adrian McCarthy820ca542016-07-06 19:49:51 +00001891 !Info.NestedClasses.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00001892}
1893
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001894TypeIndex CodeViewDebug::getVBPTypeIndex() {
1895 if (!VBPType.getIndex()) {
1896 // Make a 'const int *' type.
1897 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001898 TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001899
1900 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1901 : PointerKind::Near32;
1902 PointerMode PM = PointerMode::Pointer;
1903 PointerOptions PO = PointerOptions::None;
1904 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1905
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001906 VBPType = TypeTable.writeKnownType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001907 }
1908
1909 return VBPType;
1910}
1911
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001912TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001913 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001914 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001915
1916 // The null DIType is the void type. Don't try to hash it.
1917 if (!Ty)
1918 return TypeIndex::Void();
1919
Reid Klecknera8d57402016-06-03 15:58:20 +00001920 // Check if we've already translated this type. Don't try to do a
1921 // get-or-create style insertion that caches the hash lookup across the
1922 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001923 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001924 if (I != TypeIndices.end())
1925 return I->second;
1926
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001927 TypeLoweringScope S(*this);
1928 TypeIndex TI = lowerType(Ty, ClassTy);
1929 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00001930}
1931
1932TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1933 const DIType *Ty = TypeRef.resolve();
1934
1935 // The null DIType is the void type. Don't try to hash it.
1936 if (!Ty)
1937 return TypeIndex::Void();
1938
1939 // If this is a non-record type, the complete type index is the same as the
1940 // normal type index. Just call getTypeIndex.
1941 switch (Ty->getTag()) {
1942 case dwarf::DW_TAG_class_type:
1943 case dwarf::DW_TAG_structure_type:
1944 case dwarf::DW_TAG_union_type:
1945 break;
1946 default:
1947 return getTypeIndex(Ty);
1948 }
1949
1950 // Check if we've already translated the complete record type. Lowering a
1951 // complete type should never trigger lowering another complete type, so we
1952 // can reuse the hash table lookup result.
1953 const auto *CTy = cast<DICompositeType>(Ty);
1954 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1955 if (!InsertResult.second)
1956 return InsertResult.first->second;
1957
Reid Kleckner643dd832016-06-22 17:15:28 +00001958 TypeLoweringScope S(*this);
1959
Reid Klecknera8d57402016-06-03 15:58:20 +00001960 // Make sure the forward declaration is emitted first. It's unclear if this
1961 // is necessary, but MSVC does it, and we should follow suit until we can show
1962 // otherwise.
1963 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1964
1965 // Just use the forward decl if we don't have complete type info. This might
1966 // happen if the frontend is using modules and expects the complete definition
1967 // to be emitted elsewhere.
1968 if (CTy->isForwardDecl())
1969 return FwdDeclTI;
1970
1971 TypeIndex TI;
1972 switch (CTy->getTag()) {
1973 case dwarf::DW_TAG_class_type:
1974 case dwarf::DW_TAG_structure_type:
1975 TI = lowerCompleteTypeClass(CTy);
1976 break;
1977 case dwarf::DW_TAG_union_type:
1978 TI = lowerCompleteTypeUnion(CTy);
1979 break;
1980 default:
1981 llvm_unreachable("not a record");
1982 }
1983
1984 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001985 return TI;
1986}
1987
Reid Kleckner643dd832016-06-22 17:15:28 +00001988/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00001989/// and do this until fixpoint, as each complete record type typically
1990/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00001991/// many other record types.
1992void CodeViewDebug::emitDeferredCompleteTypes() {
1993 SmallVector<const DICompositeType *, 4> TypesToEmit;
1994 while (!DeferredCompleteTypes.empty()) {
1995 std::swap(DeferredCompleteTypes, TypesToEmit);
1996 for (const DICompositeType *RecordTy : TypesToEmit)
1997 getCompleteTypeIndex(RecordTy);
1998 TypesToEmit.clear();
1999 }
2000}
2001
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002002void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
2003 // Get the sorted list of parameters and emit them first.
2004 SmallVector<const LocalVariable *, 6> Params;
2005 for (const LocalVariable &L : Locals)
2006 if (L.DIVar->isParameter())
2007 Params.push_back(&L);
2008 std::sort(Params.begin(), Params.end(),
2009 [](const LocalVariable *L, const LocalVariable *R) {
2010 return L->DIVar->getArg() < R->DIVar->getArg();
2011 });
2012 for (const LocalVariable *L : Params)
2013 emitLocalVariable(*L);
2014
2015 // Next emit all non-parameters in the order that we found them.
2016 for (const LocalVariable &L : Locals)
2017 if (!L.DIVar->isParameter())
2018 emitLocalVariable(L);
2019}
2020
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002021void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2022 // LocalSym record, see SymbolRecord.h for more info.
2023 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2024 *LocalEnd = MMI->getContext().createTempSymbol();
2025 OS.AddComment("Record length");
2026 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2027 OS.EmitLabel(LocalBegin);
2028
2029 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00002030 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002031
Zachary Turner63a28462016-05-17 23:50:21 +00002032 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002033 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002034 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002035 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002036 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002037
2038 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00002039 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002040 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002041 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002042 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002043 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002044 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002045 OS.EmitLabel(LocalEnd);
2046
Reid Kleckner876330d2016-02-12 21:48:30 +00002047 // Calculate the on disk prefix of the appropriate def range record. The
2048 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2049 // should be big enough to hold all forms without memory allocation.
2050 SmallString<20> BytePrefix;
2051 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2052 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002053 if (DefRange.InMemory) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002054 uint16_t RegRelFlags = 0;
2055 if (DefRange.IsSubfield) {
2056 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2057 (DefRange.StructOffset
2058 << DefRangeRegisterRelSym::OffsetInParentShift);
2059 }
2060 DefRangeRegisterRelSym Sym(DefRange.CVRegister, RegRelFlags,
2061 DefRange.DataOffset, None);
Reid Kleckner876330d2016-02-12 21:48:30 +00002062 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00002063 BytePrefix +=
2064 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00002065 BytePrefix +=
2066 StringRef(reinterpret_cast<const char *>(&Sym.Header),
2067 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00002068 } else {
2069 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002070 if (DefRange.IsSubfield) {
2071 // Unclear what matters here.
2072 DefRangeSubfieldRegisterSym Sym(DefRange.CVRegister, 0,
2073 DefRange.StructOffset, None);
2074 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2075 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2076 sizeof(SymKind));
2077 BytePrefix +=
2078 StringRef(reinterpret_cast<const char *>(&Sym.Header),
2079 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
2080 } else {
2081 // Unclear what matters here.
2082 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, None);
2083 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2084 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2085 sizeof(SymKind));
2086 BytePrefix +=
2087 StringRef(reinterpret_cast<const char *>(&Sym.Header),
2088 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
2089 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002090 }
2091 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2092 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002093}
2094
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002095void CodeViewDebug::endFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002096 if (!Asm || !CurFn) // We haven't created any debug info for this function.
2097 return;
2098
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002099 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00002100 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002101 assert(CurFn == &FnDebugInfo[GV]);
2102
Pete Cooperadebb932016-03-11 02:14:16 +00002103 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002104
2105 DebugHandlerBase::endFunction(MF);
2106
Reid Kleckner2214ed82016-01-29 00:49:42 +00002107 // Don't emit anything if we don't have any line tables.
2108 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002109 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002110 CurFn = nullptr;
2111 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002112 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002113
2114 CurFn->End = Asm->getFunctionEnd();
2115
Craig Topper353eda42014-04-24 06:44:33 +00002116 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002117}
2118
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002119void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002120 DebugHandlerBase::beginInstruction(MI);
2121
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002122 // Ignore DBG_VALUE locations and function prologue.
David Majnemer67f684e2016-07-28 05:03:22 +00002123 if (!Asm || !CurFn || MI->isDebugValue() ||
2124 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002125 return;
2126 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00002127 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002128 return;
2129 maybeRecordLocation(DL, Asm->MF);
2130}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002131
2132MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
2133 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2134 *EndLabel = MMI->getContext().createTempSymbol();
2135 OS.EmitIntValue(unsigned(Kind), 4);
2136 OS.AddComment("Subsection size");
2137 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2138 OS.EmitLabel(BeginLabel);
2139 return EndLabel;
2140}
2141
2142void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2143 OS.EmitLabel(EndLabel);
2144 // Every subsection must be aligned to a 4-byte boundary.
2145 OS.EmitValueToAlignment(4);
2146}
2147
David Majnemer3128b102016-06-15 18:00:01 +00002148void CodeViewDebug::emitDebugInfoForUDTs(
2149 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
2150 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
2151 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2152 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2153 OS.AddComment("Record length");
2154 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2155 OS.EmitLabel(UDTRecordBegin);
2156
2157 OS.AddComment("Record kind: S_UDT");
2158 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2159
2160 OS.AddComment("Type");
2161 OS.EmitIntValue(UDT.second.getIndex(), 4);
2162
2163 emitNullTerminatedSymbolName(OS, UDT.first);
2164 OS.EmitLabel(UDTRecordEnd);
2165 }
2166}
2167
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002168void CodeViewDebug::emitDebugInfoForGlobals() {
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002169 DenseMap<const DIGlobalVariable *, const GlobalVariable *> GlobalMap;
2170 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
2171 SmallVector<MDNode *, 1> MDs;
2172 GV.getMetadata(LLVMContext::MD_dbg, MDs);
2173 for (MDNode *MD : MDs)
2174 GlobalMap[cast<DIGlobalVariable>(MD)] = &GV;
2175 }
2176
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002177 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2178 for (const MDNode *Node : CUs->operands()) {
2179 const auto *CU = cast<DICompileUnit>(Node);
2180
2181 // First, emit all globals that are not in a comdat in a single symbol
2182 // substream. MSVC doesn't like it if the substream is empty, so only open
2183 // it if we have at least one global to emit.
2184 switchToDebugSectionForSymbol(nullptr);
2185 MCSymbol *EndLabel = nullptr;
2186 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002187 if (const auto *GV = GlobalMap.lookup(G))
David Majnemer577be0f2016-06-15 00:19:52 +00002188 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002189 if (!EndLabel) {
2190 OS.AddComment("Symbol subsection for globals");
2191 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
2192 }
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002193 emitDebugInfoForGlobal(G, GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002194 }
2195 }
2196 if (EndLabel)
2197 endCVSubsection(EndLabel);
2198
2199 // Second, emit each global that is in a comdat into its own .debug$S
2200 // section along with its own symbol substream.
2201 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002202 if (const auto *GV = GlobalMap.lookup(G)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002203 if (GV->hasComdat()) {
2204 MCSymbol *GVSym = Asm->getSymbol(GV);
2205 OS.AddComment("Symbol subsection for " +
2206 Twine(GlobalValue::getRealLinkageName(GV->getName())));
2207 switchToDebugSectionForSymbol(GVSym);
2208 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002209 emitDebugInfoForGlobal(G, GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002210 endCVSubsection(EndLabel);
2211 }
2212 }
2213 }
2214 }
2215}
2216
Hans Wennborgb510b452016-06-23 16:33:53 +00002217void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2218 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2219 for (const MDNode *Node : CUs->operands()) {
2220 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2221 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2222 getTypeIndex(RT);
2223 // FIXME: Add to global/local DTU list.
2224 }
2225 }
2226 }
2227}
2228
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002229void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002230 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002231 MCSymbol *GVSym) {
2232 // DataSym record, see SymbolRecord.h for more info.
2233 // FIXME: Thread local data, etc
2234 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2235 *DataEnd = MMI->getContext().createTempSymbol();
2236 OS.AddComment("Record length");
2237 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2238 OS.EmitLabel(DataBegin);
David Majnemer7abd2692016-07-06 21:07:47 +00002239 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002240 if (GV->isThreadLocal()) {
2241 OS.AddComment("Record kind: S_LTHREAD32");
2242 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2243 } else {
2244 OS.AddComment("Record kind: S_LDATA32");
2245 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2246 }
David Majnemer7abd2692016-07-06 21:07:47 +00002247 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002248 if (GV->isThreadLocal()) {
2249 OS.AddComment("Record kind: S_GTHREAD32");
2250 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2251 } else {
2252 OS.AddComment("Record kind: S_GDATA32");
2253 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2254 }
David Majnemer7abd2692016-07-06 21:07:47 +00002255 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002256 OS.AddComment("Type");
2257 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2258 OS.AddComment("DataOffset");
2259 OS.EmitCOFFSecRel32(GVSym);
2260 OS.AddComment("Segment");
2261 OS.EmitCOFFSectionIndex(GVSym);
2262 OS.AddComment("Name");
2263 emitNullTerminatedSymbolName(OS, DIGV->getName());
2264 OS.EmitLabel(DataEnd);
2265}