blob: 2571f6869651634a1ee6ef1f0e69b31e45e29b51 [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"
Zachary Turnera9054dd2017-01-11 00:35:43 +000016#include "llvm/DebugInfo/CodeView/CVTypeDumper.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000017#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000018#include "llvm/DebugInfo/CodeView/CodeView.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"
Zachary Turnerc640b762017-01-11 00:35:08 +000021#include "llvm/DebugInfo/CodeView/TypeDatabase.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000022#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000023#include "llvm/DebugInfo/CodeView/TypeIndex.h"
24#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000025#include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000026#include "llvm/IR/Constants.h"
Reid Kleckner46cb48c2016-07-27 16:03:57 +000027#include "llvm/MC/MCAsmInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000028#include "llvm/MC/MCExpr.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000029#include "llvm/MC/MCSectionCOFF.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000030#include "llvm/MC/MCSymbol.h"
Zachary Turnerd9dc2822017-03-02 20:52:51 +000031#include "llvm/Support/BinaryByteStream.h"
32#include "llvm/Support/BinaryStreamReader.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000033#include "llvm/Support/COFF.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000034#include "llvm/Support/ScopedPrinter.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000035#include "llvm/Target/TargetFrameLowering.h"
Amjad Aboud76c9eb92016-06-18 10:25:07 +000036#include "llvm/Target/TargetRegisterInfo.h"
37#include "llvm/Target/TargetSubtargetInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000038
Reid Klecknerf9c275f2016-02-10 20:55:49 +000039using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000040using namespace llvm::codeview;
41
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);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000225 StringIdRecord SID(TypeIndex(), ScopeName);
226 auto TI = TypeTable.writeKnownType(SID);
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.
Adrian Prantlaa1d6022017-04-26 23:49:30 +0000240 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
Zachary Turner629cb7d2017-01-11 23:24:22 +0000471 TypeDatabase TypeDB;
472 CVTypeDumper CVTD(TypeDB);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000473 TypeTable.ForEachRecord([&](TypeIndex Index, ArrayRef<uint8_t> 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);
Zachary Turner629cb7d2017-01-11 23:24:22 +0000480 TypeDumpVisitor TDV(TypeDB, &SP, false);
481 Error E = CVTD.dump(Record, TDV);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000482 if (E) {
483 logAllUnhandledErrors(std::move(E), errs(), "error: ");
484 llvm_unreachable("produced malformed type record");
485 }
486 // 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());
491 } else {
Reid Klecknerc92e9462016-07-01 18:05:56 +0000492#ifndef NDEBUG
Zachary Turner4efa0a42016-11-08 22:24:53 +0000493 // 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 Turner695ed562017-02-28 00:04:07 +0000497 BinaryByteStream Stream(Record, llvm::support::little);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000498 CVTypeArray Types;
Zachary Turner120faca2017-02-27 22:11:43 +0000499 BinaryStreamReader Reader(Stream);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000500 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 }
Reid Klecknerc92e9462016-07-01 18:05:56 +0000509#endif
Zachary Turner4efa0a42016-11-08 22:24:53 +0000510 }
511 StringRef S(reinterpret_cast<const char *>(Record.data()), Record.size());
512 OS.EmitBinaryData(S);
513 });
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000514}
515
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000516namespace {
517
518static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
519 switch (DWLang) {
520 case dwarf::DW_LANG_C:
521 case dwarf::DW_LANG_C89:
522 case dwarf::DW_LANG_C99:
523 case dwarf::DW_LANG_C11:
524 case dwarf::DW_LANG_ObjC:
525 return SourceLanguage::C;
526 case dwarf::DW_LANG_C_plus_plus:
527 case dwarf::DW_LANG_C_plus_plus_03:
528 case dwarf::DW_LANG_C_plus_plus_11:
529 case dwarf::DW_LANG_C_plus_plus_14:
530 return SourceLanguage::Cpp;
531 case dwarf::DW_LANG_Fortran77:
532 case dwarf::DW_LANG_Fortran90:
533 case dwarf::DW_LANG_Fortran03:
534 case dwarf::DW_LANG_Fortran08:
535 return SourceLanguage::Fortran;
536 case dwarf::DW_LANG_Pascal83:
537 return SourceLanguage::Pascal;
538 case dwarf::DW_LANG_Cobol74:
539 case dwarf::DW_LANG_Cobol85:
540 return SourceLanguage::Cobol;
541 case dwarf::DW_LANG_Java:
542 return SourceLanguage::Java;
543 default:
544 // There's no CodeView representation for this language, and CV doesn't
545 // have an "unknown" option for the language field, so we'll use MASM,
546 // as it's very low level.
547 return SourceLanguage::Masm;
548 }
549}
550
551struct Version {
552 int Part[4];
553};
554
555// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
556// the version number.
557static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000558 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000559 int N = 0;
560 for (const char C : Name) {
561 if (isdigit(C)) {
562 V.Part[N] *= 10;
563 V.Part[N] += C - '0';
564 } else if (C == '.') {
565 ++N;
566 if (N >= 4)
567 return V;
568 } else if (N > 0)
569 return V;
570 }
571 return V;
572}
573
574static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
575 switch (Type) {
576 case Triple::ArchType::x86:
577 return CPUType::Pentium3;
578 case Triple::ArchType::x86_64:
579 return CPUType::X64;
580 case Triple::ArchType::thumb:
581 return CPUType::Thumb;
582 default:
583 report_fatal_error("target architecture doesn't map to a CodeView "
584 "CPUType");
585 }
586}
587
588} // anonymous namespace
589
590void CodeViewDebug::emitCompilerInformation() {
591 MCContext &Context = MMI->getContext();
592 MCSymbol *CompilerBegin = Context.createTempSymbol(),
593 *CompilerEnd = Context.createTempSymbol();
594 OS.AddComment("Record length");
595 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
596 OS.EmitLabel(CompilerBegin);
597 OS.AddComment("Record kind: S_COMPILE3");
598 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
599 uint32_t Flags = 0;
600
601 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
602 const MDNode *Node = *CUs->operands().begin();
603 const auto *CU = cast<DICompileUnit>(Node);
604
605 // The low byte of the flags indicates the source language.
606 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
607 // TODO: Figure out which other flags need to be set.
608
609 OS.AddComment("Flags and language");
610 OS.EmitIntValue(Flags, 4);
611
612 OS.AddComment("CPUType");
613 CPUType CPU =
614 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
615 OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
616
617 StringRef CompilerVersion = CU->getProducer();
618 Version FrontVer = parseVersion(CompilerVersion);
619 OS.AddComment("Frontend version");
620 for (int N = 0; N < 4; ++N)
621 OS.EmitIntValue(FrontVer.Part[N], 2);
622
623 // Some Microsoft tools, like Binscope, expect a backend version number of at
624 // least 8.something, so we'll coerce the LLVM version into a form that
625 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000626 int Major = 1000 * LLVM_VERSION_MAJOR +
627 10 * LLVM_VERSION_MINOR +
628 LLVM_VERSION_PATCH;
629 // Clamp it for builds that use unusually large version numbers.
630 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
631 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000632 OS.AddComment("Backend version");
633 for (int N = 0; N < 4; ++N)
634 OS.EmitIntValue(BackVer.Part[N], 2);
635
636 OS.AddComment("Null-terminated compiler version string");
637 emitNullTerminatedSymbolName(OS, CompilerVersion);
638
639 OS.EmitLabel(CompilerEnd);
640}
641
Reid Kleckner5d122f82016-05-25 23:16:12 +0000642void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000643 if (InlinedSubprograms.empty())
644 return;
645
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000646 OS.AddComment("Inlinee lines subsection");
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000647 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000648
649 // We don't provide any extra file info.
650 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000651 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000652 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
653
654 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000655 assert(TypeIndices.count({SP, nullptr}));
656 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000657
David Majnemer30579ec2016-02-02 23:18:23 +0000658 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000659 unsigned FileId = maybeRecordFile(SP->getFile());
Adrian Prantlaa1d6022017-04-26 23:49:30 +0000660 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000661 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000662 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000663 // The filechecksum table uses 8 byte entries for now, and file ids start at
664 // 1.
665 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000666 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000667 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000668 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000669 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000670 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000671 OS.EmitIntValue(SP->getLine(), 4);
672 }
673
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000674 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000675}
676
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000677void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
678 const DILocation *InlinedAt,
679 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000680 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
681 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000682
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000683 assert(TypeIndices.count({Site.Inlinee, nullptr}));
684 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000685
686 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000687 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000688 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000689 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000690 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000691 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000692
Reid Klecknerdac21b42016-02-03 21:15:48 +0000693 OS.AddComment("PtrParent");
694 OS.EmitIntValue(0, 4);
695 OS.AddComment("PtrEnd");
696 OS.EmitIntValue(0, 4);
697 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000698 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000699
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000700 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
701 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000702
703 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000704 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000705
706 OS.EmitLabel(InlineEnd);
707
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000708 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000709
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000710 // Recurse on child inlined call sites before closing the scope.
711 for (const DILocation *ChildSite : Site.ChildSites) {
712 auto I = FI.InlineSites.find(ChildSite);
713 assert(I != FI.InlineSites.end() &&
714 "child site not in function inline site map");
715 emitInlinedCallSite(FI, ChildSite, I->second);
716 }
717
718 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000719 OS.AddComment("Record length");
720 OS.EmitIntValue(2, 2); // RecordLength
721 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000722 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000723}
724
Reid Kleckner5d122f82016-05-25 23:16:12 +0000725void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
726 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
727 // comdat key. A section may be comdat because of -ffunction-sections or
728 // because it is comdat in the IR.
729 MCSectionCOFF *GVSec =
730 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
731 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
732
733 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
734 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
735 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
736
737 OS.SwitchSection(DebugSec);
738
739 // Emit the magic version number if this is the first time we've switched to
740 // this section.
741 if (ComdatDebugSections.insert(DebugSec).second)
742 emitCodeViewMagicVersion();
743}
744
Reid Kleckner2214ed82016-01-29 00:49:42 +0000745void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
746 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000747 // For each function there is a separate subsection
748 // which holds the PC to file:line table.
749 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000750 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000751
Reid Kleckner5d122f82016-05-25 23:16:12 +0000752 // Switch to the to a comdat section, if appropriate.
753 switchToDebugSectionForSymbol(Fn);
754
Reid Klecknerac945e22016-06-17 16:11:20 +0000755 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000756 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000757 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000758 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000759
760 // If we have a display name, build the fully qualified name by walking the
761 // chain of scopes.
Adrian Prantlaa1d6022017-04-26 23:49:30 +0000762 if (!SP->getDisplayName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000763 FuncName =
Adrian Prantlaa1d6022017-04-26 23:49:30 +0000764 getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000765
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000766 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000767 if (FuncName.empty())
768 FuncName = GlobalValue::getRealLinkageName(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000769
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000770 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000771 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000772 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000773 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000774 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
775 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000776 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000777 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000778 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000779
Reid Kleckner4ad127f2016-09-14 21:49:21 +0000780 if (GV->hasLocalLinkage()) {
781 OS.AddComment("Record kind: S_LPROC32_ID");
782 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
783 } else {
784 OS.AddComment("Record kind: S_GPROC32_ID");
785 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
786 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000787
David Majnemer30579ec2016-02-02 23:18:23 +0000788 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000789 OS.AddComment("PtrParent");
790 OS.EmitIntValue(0, 4);
791 OS.AddComment("PtrEnd");
792 OS.EmitIntValue(0, 4);
793 OS.AddComment("PtrNext");
794 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000795 // This is the important bit that tells the debugger where the function
796 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000797 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000798 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000799 OS.AddComment("Offset after prologue");
800 OS.EmitIntValue(0, 4);
801 OS.AddComment("Offset before epilogue");
802 OS.EmitIntValue(0, 4);
803 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000804 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000805 OS.AddComment("Function section relative address");
Keno Fischerf7d84ee2017-01-02 03:00:19 +0000806 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000807 OS.AddComment("Function section index");
808 OS.EmitCOFFSectionIndex(Fn);
809 OS.AddComment("Flags");
810 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000811 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000812 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000813 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000814 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000815 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000816
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000817 emitLocalVariableList(FI.Locals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000818
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000819 // Emit inlined call site information. Only emit functions inlined directly
820 // into the parent function. We'll emit the other sites recursively as part
821 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000822 for (const DILocation *InlinedAt : FI.ChildSites) {
823 auto I = FI.InlineSites.find(InlinedAt);
824 assert(I != FI.InlineSites.end() &&
825 "child site not in function inline site map");
826 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000827 }
828
David Majnemer3128b102016-06-15 18:00:01 +0000829 if (SP != nullptr)
830 emitDebugInfoForUDTs(LocalUDTs);
831
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000832 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000833 OS.AddComment("Record length");
834 OS.EmitIntValue(0x0002, 2);
835 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000836 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000837 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000838 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000839
Reid Kleckner2214ed82016-01-29 00:49:42 +0000840 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000841 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000842}
843
Reid Kleckner876330d2016-02-12 21:48:30 +0000844CodeViewDebug::LocalVarDefRange
845CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
846 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000847 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000848 DR.DataOffset = Offset;
849 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000850 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000851 DR.StructOffset = 0;
852 DR.CVRegister = CVRegister;
853 return DR;
854}
855
856CodeViewDebug::LocalVarDefRange
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000857CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
858 int Offset, bool IsSubfield,
859 uint16_t StructOffset) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000860 LocalVarDefRange DR;
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000861 DR.InMemory = InMemory;
862 DR.DataOffset = Offset;
863 DR.IsSubfield = IsSubfield;
864 DR.StructOffset = StructOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +0000865 DR.CVRegister = CVRegister;
866 return DR;
867}
868
Matthias Braunef331ef2016-11-30 23:48:50 +0000869void CodeViewDebug::collectVariableInfoFromMFTable(
Reid Kleckner876330d2016-02-12 21:48:30 +0000870 DenseSet<InlinedVariable> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +0000871 const MachineFunction &MF = *Asm->MF;
872 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +0000873 const TargetFrameLowering *TFI = TSI.getFrameLowering();
874 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
875
Matthias Braunef331ef2016-11-30 23:48:50 +0000876 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000877 if (!VI.Var)
878 continue;
879 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
880 "Expected inlined-at fields to agree");
881
Reid Kleckner876330d2016-02-12 21:48:30 +0000882 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000883 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
884
885 // If variable scope is not found then skip this variable.
886 if (!Scope)
887 continue;
888
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000889 // Get the frame register used and the offset.
890 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000891 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
892 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000893
894 // Calculate the label ranges.
Reid Kleckner876330d2016-02-12 21:48:30 +0000895 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000896 for (const InsnRange &Range : Scope->getRanges()) {
897 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
898 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000899 End = End ? End : Asm->getFunctionEnd();
900 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000901 }
902
Reid Kleckner876330d2016-02-12 21:48:30 +0000903 LocalVariable Var;
904 Var.DIVar = VI.Var;
905 Var.DefRanges.emplace_back(std::move(DefRange));
906 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
907 }
908}
909
910void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
911 DenseSet<InlinedVariable> Processed;
912 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +0000913 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +0000914
915 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
916
917 for (const auto &I : DbgValues) {
918 InlinedVariable IV = I.first;
919 if (Processed.count(IV))
920 continue;
921 const DILocalVariable *DIVar = IV.first;
922 const DILocation *InlinedAt = IV.second;
923
924 // Instruction ranges, specifying where IV is accessible.
925 const auto &Ranges = I.second;
926
927 LexicalScope *Scope = nullptr;
928 if (InlinedAt)
929 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
930 else
931 Scope = LScopes.findLexicalScope(DIVar->getScope());
932 // If variable scope is not found then skip this variable.
933 if (!Scope)
934 continue;
935
936 LocalVariable Var;
937 Var.DIVar = DIVar;
938
939 // Calculate the definition ranges.
940 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
941 const InsnRange &Range = *I;
942 const MachineInstr *DVInst = Range.first;
943 assert(DVInst->isDebugValue() && "Invalid History entry");
944 const DIExpression *DIExpr = DVInst->getDebugExpression();
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000945 bool IsSubfield = false;
946 unsigned StructOffset = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000947
Adrian Prantl941fa752016-12-05 18:04:47 +0000948 // Handle fragments.
Adrian Prantl49797ca2016-12-22 05:27:12 +0000949 auto Fragment = DIExpr->getFragmentInfo();
Adrian Prantle8450fd2017-03-27 17:36:31 +0000950 if (Fragment) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000951 IsSubfield = true;
Adrian Prantl49797ca2016-12-22 05:27:12 +0000952 StructOffset = Fragment->OffsetInBits / 8;
Adrian Prantle8450fd2017-03-27 17:36:31 +0000953 } else if (DIExpr->getNumElements() > 0) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000954 continue; // Ignore unrecognized exprs.
955 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000956
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000957 // Bail if operand 0 is not a valid register. This means the variable is a
958 // simple constant, or is described by a complex expression.
959 // FIXME: Find a way to represent constant variables, since they are
960 // relatively common.
961 unsigned Reg =
962 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
963 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000964 continue;
965
Reid Kleckner876330d2016-02-12 21:48:30 +0000966 // Handle the two cases we can handle: indirect in memory and in register.
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000967 unsigned CVReg = TRI->getCodeViewRegNum(Reg);
968 bool InMemory = DVInst->getOperand(1).isImm();
969 int Offset = InMemory ? DVInst->getOperand(1).getImm() : 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000970 {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000971 LocalVarDefRange DR;
972 DR.CVRegister = CVReg;
973 DR.InMemory = InMemory;
974 DR.DataOffset = Offset;
975 DR.IsSubfield = IsSubfield;
976 DR.StructOffset = StructOffset;
977
Reid Kleckner876330d2016-02-12 21:48:30 +0000978 if (Var.DefRanges.empty() ||
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000979 Var.DefRanges.back().isDifferentLocation(DR)) {
980 Var.DefRanges.emplace_back(std::move(DR));
Reid Kleckner876330d2016-02-12 21:48:30 +0000981 }
982 }
983
984 // Compute the label range.
985 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
986 const MCSymbol *End = getLabelAfterInsn(Range.second);
987 if (!End) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000988 // This range is valid until the next overlapping bitpiece. In the
989 // common case, ranges will not be bitpieces, so they will overlap.
990 auto J = std::next(I);
Adrian Prantl941fa752016-12-05 18:04:47 +0000991 while (J != E &&
992 !fragmentsOverlap(DIExpr, J->first->getDebugExpression()))
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000993 ++J;
994 if (J != E)
995 End = getLabelBeforeInsn(J->first);
Reid Kleckner876330d2016-02-12 21:48:30 +0000996 else
997 End = Asm->getFunctionEnd();
998 }
999
1000 // If the last range end is our begin, just extend the last range.
1001 // Otherwise make a new range.
1002 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
1003 Var.DefRanges.back().Ranges;
1004 if (!Ranges.empty() && Ranges.back().second == Begin)
1005 Ranges.back().second = End;
1006 else
1007 Ranges.emplace_back(Begin, End);
1008
1009 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001010 }
Reid Kleckner876330d2016-02-12 21:48:30 +00001011
1012 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001013 }
1014}
1015
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001016void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001017 const Function *GV = MF->getFunction();
1018 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001019 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +00001020 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001021 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001022
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001023 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1024
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001025 // Find the end of the function prolog. First known non-DBG_VALUE and
1026 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001027 // FIXME: is there a simpler a way to do this? Can we just search
1028 // for the first instruction of the function, not the last of the prolog?
1029 DebugLoc PrologEndLoc;
1030 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001031 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001032 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001033 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1034 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001035 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001036 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001037 } else if (!MI.isDebugValue()) {
1038 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001039 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001040 }
1041 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001042
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001043 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001044 if (PrologEndLoc && !EmptyPrologue) {
1045 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001046 maybeRecordLocation(FnStartDL, MF);
1047 }
1048}
1049
Hans Wennborg4b63a982016-06-23 22:57:25 +00001050void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001051 // Don't record empty UDTs.
1052 if (Ty->getName().empty())
1053 return;
1054
Hans Wennborg4b63a982016-06-23 22:57:25 +00001055 SmallVector<StringRef, 5> QualifiedNameComponents;
1056 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1057 Ty->getScope().resolve(), QualifiedNameComponents);
1058
1059 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001060 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001061
1062 if (ClosestSubprogram == nullptr)
1063 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1064 else if (ClosestSubprogram == CurrentSubprogram)
1065 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1066
1067 // TODO: What if the ClosestSubprogram is neither null or the current
1068 // subprogram? Currently, the UDT just gets dropped on the floor.
1069 //
1070 // The current behavior is not desirable. To get maximal fidelity, we would
1071 // need to perform all type translation before beginning emission of .debug$S
1072 // and then make LocalUDTs a member of FunctionInfo
1073}
1074
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001075TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001076 // Generic dispatch for lowering an unknown type.
1077 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001078 case dwarf::DW_TAG_array_type:
1079 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001080 case dwarf::DW_TAG_typedef:
1081 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001082 case dwarf::DW_TAG_base_type:
1083 return lowerTypeBasic(cast<DIBasicType>(Ty));
1084 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001085 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1086 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1087 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001088 case dwarf::DW_TAG_reference_type:
1089 case dwarf::DW_TAG_rvalue_reference_type:
1090 return lowerTypePointer(cast<DIDerivedType>(Ty));
1091 case dwarf::DW_TAG_ptr_to_member_type:
1092 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1093 case dwarf::DW_TAG_const_type:
1094 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001095 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001096 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001097 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001098 if (ClassTy) {
1099 // The member function type of a member function pointer has no
1100 // ThisAdjustment.
1101 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1102 /*ThisAdjustment=*/0);
1103 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001104 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001105 case dwarf::DW_TAG_enumeration_type:
1106 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001107 case dwarf::DW_TAG_class_type:
1108 case dwarf::DW_TAG_structure_type:
1109 return lowerTypeClass(cast<DICompositeType>(Ty));
1110 case dwarf::DW_TAG_union_type:
1111 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001112 default:
1113 // Use the null type index.
1114 return TypeIndex();
1115 }
1116}
1117
David Majnemerd065e232016-06-02 06:21:37 +00001118TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001119 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1120 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001121 StringRef TypeName = Ty->getName();
1122
Hans Wennborg4b63a982016-06-23 22:57:25 +00001123 addToUDTs(Ty, UnderlyingTypeIndex);
David Majnemer3128b102016-06-15 18:00:01 +00001124
David Majnemerd065e232016-06-02 06:21:37 +00001125 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001126 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001127 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001128 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001129 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001130 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001131
David Majnemerd065e232016-06-02 06:21:37 +00001132 return UnderlyingTypeIndex;
1133}
1134
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001135TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1136 DITypeRef ElementTypeRef = Ty->getBaseType();
1137 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1138 // IndexType is size_t, which depends on the bitness of the target.
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001139 TypeIndex IndexType = Asm->TM.getPointerSize() == 8
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001140 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1141 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001142
1143 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1144
Amjad Aboudacee5682016-07-12 12:06:34 +00001145 // Add subranges to array type.
1146 DINodeArray Elements = Ty->getElements();
1147 for (int i = Elements.size() - 1; i >= 0; --i) {
1148 const DINode *Element = Elements[i];
1149 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1150
1151 const DISubrange *Subrange = cast<DISubrange>(Element);
1152 assert(Subrange->getLowerBound() == 0 &&
1153 "codeview doesn't support subranges with lower bounds");
1154 int64_t Count = Subrange->getCount();
1155
1156 // Variable Length Array (VLA) has Count equal to '-1'.
1157 // Replace with Count '1', assume it is the minimum VLA length.
1158 // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
Reid Kleckner6b78e162017-03-24 23:28:42 +00001159 if (Count == -1)
Amjad Aboudacee5682016-07-12 12:06:34 +00001160 Count = 1;
Amjad Aboudacee5682016-07-12 12:06:34 +00001161
Amjad Aboudacee5682016-07-12 12:06:34 +00001162 // Update the element size and element type index for subsequent subranges.
1163 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001164
1165 // If this is the outermost array, use the size from the array. It will be
Reid Kleckner6b78e162017-03-24 23:28:42 +00001166 // more accurate if we had a VLA or an incomplete element type size.
Reid Kleckner10762882016-09-09 17:29:36 +00001167 uint64_t ArraySize =
1168 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1169
1170 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001171 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1172 ElementTypeIndex = TypeTable.writeKnownType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001173 }
1174
Amjad Aboudacee5682016-07-12 12:06:34 +00001175 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001176}
1177
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001178TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1179 TypeIndex Index;
1180 dwarf::TypeKind Kind;
1181 uint32_t ByteSize;
1182
1183 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001184 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001185
1186 SimpleTypeKind STK = SimpleTypeKind::None;
1187 switch (Kind) {
1188 case dwarf::DW_ATE_address:
1189 // FIXME: Translate
1190 break;
1191 case dwarf::DW_ATE_boolean:
1192 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001193 case 1: STK = SimpleTypeKind::Boolean8; break;
1194 case 2: STK = SimpleTypeKind::Boolean16; break;
1195 case 4: STK = SimpleTypeKind::Boolean32; break;
1196 case 8: STK = SimpleTypeKind::Boolean64; break;
1197 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001198 }
1199 break;
1200 case dwarf::DW_ATE_complex_float:
1201 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001202 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001203 case 4: STK = SimpleTypeKind::Complex32; break;
1204 case 8: STK = SimpleTypeKind::Complex64; break;
1205 case 10: STK = SimpleTypeKind::Complex80; break;
1206 case 16: STK = SimpleTypeKind::Complex128; break;
1207 }
1208 break;
1209 case dwarf::DW_ATE_float:
1210 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001211 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001212 case 4: STK = SimpleTypeKind::Float32; break;
1213 case 6: STK = SimpleTypeKind::Float48; break;
1214 case 8: STK = SimpleTypeKind::Float64; break;
1215 case 10: STK = SimpleTypeKind::Float80; break;
1216 case 16: STK = SimpleTypeKind::Float128; break;
1217 }
1218 break;
1219 case dwarf::DW_ATE_signed:
1220 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001221 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1222 case 2: STK = SimpleTypeKind::Int16Short; break;
1223 case 4: STK = SimpleTypeKind::Int32; break;
1224 case 8: STK = SimpleTypeKind::Int64Quad; break;
1225 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001226 }
1227 break;
1228 case dwarf::DW_ATE_unsigned:
1229 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001230 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1231 case 2: STK = SimpleTypeKind::UInt16Short; break;
1232 case 4: STK = SimpleTypeKind::UInt32; break;
1233 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1234 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001235 }
1236 break;
1237 case dwarf::DW_ATE_UTF:
1238 switch (ByteSize) {
1239 case 2: STK = SimpleTypeKind::Character16; break;
1240 case 4: STK = SimpleTypeKind::Character32; break;
1241 }
1242 break;
1243 case dwarf::DW_ATE_signed_char:
1244 if (ByteSize == 1)
1245 STK = SimpleTypeKind::SignedCharacter;
1246 break;
1247 case dwarf::DW_ATE_unsigned_char:
1248 if (ByteSize == 1)
1249 STK = SimpleTypeKind::UnsignedCharacter;
1250 break;
1251 default:
1252 break;
1253 }
1254
1255 // Apply some fixups based on the source-level type name.
1256 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1257 STK = SimpleTypeKind::Int32Long;
1258 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1259 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001260 if (STK == SimpleTypeKind::UInt16Short &&
1261 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001262 STK = SimpleTypeKind::WideCharacter;
1263 if ((STK == SimpleTypeKind::SignedCharacter ||
1264 STK == SimpleTypeKind::UnsignedCharacter) &&
1265 Ty->getName() == "char")
1266 STK = SimpleTypeKind::NarrowCharacter;
1267
1268 return TypeIndex(STK);
1269}
1270
1271TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1272 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1273
1274 // Pointers to simple types can use SimpleTypeMode, rather than having a
1275 // dedicated pointer type record.
1276 if (PointeeTI.isSimple() &&
1277 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1278 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1279 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1280 ? SimpleTypeMode::NearPointer64
1281 : SimpleTypeMode::NearPointer32;
1282 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1283 }
1284
1285 PointerKind PK =
1286 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1287 PointerMode PM = PointerMode::Pointer;
1288 switch (Ty->getTag()) {
1289 default: llvm_unreachable("not a pointer tag type");
1290 case dwarf::DW_TAG_pointer_type:
1291 PM = PointerMode::Pointer;
1292 break;
1293 case dwarf::DW_TAG_reference_type:
1294 PM = PointerMode::LValueReference;
1295 break;
1296 case dwarf::DW_TAG_rvalue_reference_type:
1297 PM = PointerMode::RValueReference;
1298 break;
1299 }
1300 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1301 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1302 // do.
1303 PointerOptions PO = PointerOptions::None;
1304 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001305 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001306}
1307
Reid Kleckner6fa15462016-06-17 22:14:39 +00001308static PointerToMemberRepresentation
1309translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1310 // SizeInBytes being zero generally implies that the member pointer type was
1311 // incomplete, which can happen if it is part of a function prototype. In this
1312 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001313 if (IsPMF) {
1314 switch (Flags & DINode::FlagPtrToMemberRep) {
1315 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001316 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1317 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001318 case DINode::FlagSingleInheritance:
1319 return PointerToMemberRepresentation::SingleInheritanceFunction;
1320 case DINode::FlagMultipleInheritance:
1321 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1322 case DINode::FlagVirtualInheritance:
1323 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1324 }
1325 } else {
1326 switch (Flags & DINode::FlagPtrToMemberRep) {
1327 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001328 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1329 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001330 case DINode::FlagSingleInheritance:
1331 return PointerToMemberRepresentation::SingleInheritanceData;
1332 case DINode::FlagMultipleInheritance:
1333 return PointerToMemberRepresentation::MultipleInheritanceData;
1334 case DINode::FlagVirtualInheritance:
1335 return PointerToMemberRepresentation::VirtualInheritanceData;
1336 }
1337 }
1338 llvm_unreachable("invalid ptr to member representation");
1339}
1340
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001341TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1342 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1343 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001344 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001345 PointerKind PK = Asm->TM.getPointerSize() == 8 ? PointerKind::Near64
1346 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001347 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1348 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1349 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001350 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001351 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1352 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1353 MemberPointerInfo MPI(
1354 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001355 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001356 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001357}
1358
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001359/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1360/// have a translation, use the NearC convention.
1361static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1362 switch (DwarfCC) {
1363 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1364 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1365 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1366 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1367 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1368 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1369 }
1370 return CallingConvention::NearC;
1371}
1372
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001373TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1374 ModifierOptions Mods = ModifierOptions::None;
1375 bool IsModifier = true;
1376 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001377 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001378 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001379 switch (BaseTy->getTag()) {
1380 case dwarf::DW_TAG_const_type:
1381 Mods |= ModifierOptions::Const;
1382 break;
1383 case dwarf::DW_TAG_volatile_type:
1384 Mods |= ModifierOptions::Volatile;
1385 break;
1386 default:
1387 IsModifier = false;
1388 break;
1389 }
1390 if (IsModifier)
1391 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1392 }
1393 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001394 ModifierRecord MR(ModifiedTI, Mods);
1395 return TypeTable.writeKnownType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001396}
1397
David Majnemer75c3ebf2016-06-02 17:13:53 +00001398TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1399 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1400 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1401 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1402
1403 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1404 ArrayRef<TypeIndex> ArgTypeIndices = None;
1405 if (!ReturnAndArgTypeIndices.empty()) {
1406 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1407 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1408 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1409 }
1410
1411 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001412 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001413
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001414 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1415
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001416 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1417 ArgTypeIndices.size(), ArgListIndex);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001418 return TypeTable.writeKnownType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001419}
1420
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001421TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001422 const DIType *ClassTy,
1423 int ThisAdjustment) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001424 // Lower the containing class type.
1425 TypeIndex ClassType = getTypeIndex(ClassTy);
1426
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001427 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1428 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1429 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1430
1431 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1432 ArrayRef<TypeIndex> ArgTypeIndices = None;
1433 if (!ReturnAndArgTypeIndices.empty()) {
1434 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1435 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1436 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1437 }
1438 TypeIndex ThisTypeIndex = TypeIndex::Void();
1439 if (!ArgTypeIndices.empty()) {
1440 ThisTypeIndex = ArgTypeIndices.front();
1441 ArgTypeIndices = ArgTypeIndices.drop_front();
1442 }
1443
1444 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001445 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001446
1447 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1448
1449 // TODO: Need to use the correct values for:
1450 // FunctionOptions
1451 // ThisPointerAdjustment.
Zachary Turner4efa0a42016-11-08 22:24:53 +00001452 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1453 FunctionOptions::None, ArgTypeIndices.size(),
1454 ArgListIndex, ThisAdjustment);
1455 TypeIndex TI = TypeTable.writeKnownType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001456
1457 return TI;
1458}
1459
Reid Kleckner9dac4732016-08-31 15:59:30 +00001460TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001461 unsigned VSlotCount =
1462 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
Reid Kleckner9dac4732016-08-31 15:59:30 +00001463 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001464
1465 VFTableShapeRecord VFTSR(Slots);
1466 return TypeTable.writeKnownType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001467}
1468
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001469static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1470 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001471 case DINode::FlagPrivate: return MemberAccess::Private;
1472 case DINode::FlagPublic: return MemberAccess::Public;
1473 case DINode::FlagProtected: return MemberAccess::Protected;
1474 case 0:
1475 // If there was no explicit access control, provide the default for the tag.
1476 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1477 : MemberAccess::Public;
1478 }
1479 llvm_unreachable("access flags are exclusive");
1480}
1481
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001482static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1483 if (SP->isArtificial())
1484 return MethodOptions::CompilerGenerated;
1485
1486 // FIXME: Handle other MethodOptions.
1487
1488 return MethodOptions::None;
1489}
1490
1491static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1492 bool Introduced) {
1493 switch (SP->getVirtuality()) {
1494 case dwarf::DW_VIRTUALITY_none:
1495 break;
1496 case dwarf::DW_VIRTUALITY_virtual:
1497 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1498 case dwarf::DW_VIRTUALITY_pure_virtual:
1499 return Introduced ? MethodKind::PureIntroducingVirtual
1500 : MethodKind::PureVirtual;
1501 default:
1502 llvm_unreachable("unhandled virtuality case");
1503 }
1504
1505 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1506
1507 return MethodKind::Vanilla;
1508}
1509
Reid Klecknera8d57402016-06-03 15:58:20 +00001510static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1511 switch (Ty->getTag()) {
1512 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1513 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1514 }
1515 llvm_unreachable("unexpected tag");
1516}
1517
Reid Klecknere092dad2016-07-02 00:11:07 +00001518/// Return ClassOptions that should be present on both the forward declaration
1519/// and the defintion of a tag type.
1520static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1521 ClassOptions CO = ClassOptions::None;
1522
1523 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001524 // appear to give every type a linkage name, which may be problematic for us.
1525 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001526 if (!Ty->getIdentifier().empty())
1527 CO |= ClassOptions::HasUniqueName;
1528
1529 // Put the Nested flag on a type if it appears immediately inside a tag type.
1530 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1531 // here. That flag is only set on definitions, and not forward declarations.
1532 const DIScope *ImmediateScope = Ty->getScope().resolve();
1533 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1534 CO |= ClassOptions::Nested;
1535
1536 // Put the Scoped flag on function-local types.
1537 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1538 Scope = Scope->getScope().resolve()) {
1539 if (isa<DISubprogram>(Scope)) {
1540 CO |= ClassOptions::Scoped;
1541 break;
1542 }
1543 }
1544
1545 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001546}
1547
David Majnemer979cb882016-06-16 21:32:16 +00001548TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001549 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001550 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001551 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001552
David Majnemerda9548f2016-06-17 16:13:21 +00001553 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001554 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001555 } else {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001556 FieldListRecordBuilder FLRB(TypeTable);
1557
1558 FLRB.begin();
David Majnemerda9548f2016-06-17 16:13:21 +00001559 for (const DINode *Element : Ty->getElements()) {
1560 // We assume that the frontend provides all members in source declaration
1561 // order, which is what MSVC does.
1562 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001563 EnumeratorRecord ER(MemberAccess::Public,
1564 APSInt::getUnsigned(Enumerator->getValue()),
1565 Enumerator->getName());
1566 FLRB.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00001567 EnumeratorCount++;
1568 }
1569 }
Zachary Turner4efa0a42016-11-08 22:24:53 +00001570 FTI = FLRB.end();
David Majnemerda9548f2016-06-17 16:13:21 +00001571 }
David Majnemer979cb882016-06-16 21:32:16 +00001572
David Majnemer6bdc24e2016-07-01 23:12:45 +00001573 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001574
Zachary Turner4efa0a42016-11-08 22:24:53 +00001575 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1576 getTypeIndex(Ty->getBaseType()));
1577 return TypeTable.writeKnownType(ER);
David Majnemer979cb882016-06-16 21:32:16 +00001578}
1579
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001580//===----------------------------------------------------------------------===//
1581// ClassInfo
1582//===----------------------------------------------------------------------===//
1583
1584struct llvm::ClassInfo {
1585 struct MemberInfo {
1586 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001587 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001588 };
1589 // [MemberInfo]
1590 typedef std::vector<MemberInfo> MemberList;
1591
Reid Kleckner156a7232016-06-22 18:31:14 +00001592 typedef TinyPtrVector<const DISubprogram *> MethodsList;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001593 // MethodName -> MethodsList
1594 typedef MapVector<MDString *, MethodsList> MethodsMap;
1595
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001596 /// Base classes.
1597 std::vector<const DIDerivedType *> Inheritance;
1598
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001599 /// Direct members.
1600 MemberList Members;
1601 // Direct overloaded methods gathered by name.
1602 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001603
Reid Kleckner9dac4732016-08-31 15:59:30 +00001604 TypeIndex VShapeTI;
1605
Adrian McCarthy820ca542016-07-06 19:49:51 +00001606 std::vector<const DICompositeType *> NestedClasses;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001607};
1608
1609void CodeViewDebug::clear() {
1610 assert(CurFn == nullptr);
1611 FileIdMap.clear();
1612 FnDebugInfo.clear();
1613 FileToFilepathMap.clear();
1614 LocalUDTs.clear();
1615 GlobalUDTs.clear();
1616 TypeIndices.clear();
1617 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001618}
1619
1620void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1621 const DIDerivedType *DDTy) {
1622 if (!DDTy->getName().empty()) {
1623 Info.Members.push_back({DDTy, 0});
1624 return;
1625 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001626 // An unnamed member must represent a nested struct or union. Add all the
1627 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001628 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00001629 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001630 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001631 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001632 ClassInfo NestedInfo = collectClassInfo(DCTy);
1633 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001634 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001635 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001636}
1637
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001638ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1639 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001640 // Add elements to structure type.
1641 DINodeArray Elements = Ty->getElements();
1642 for (auto *Element : Elements) {
1643 // We assume that the frontend provides all members in source declaration
1644 // order, which is what MSVC does.
1645 if (!Element)
1646 continue;
1647 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001648 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001649 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001650 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001651 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001652 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1653 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001654 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1655 DDTy->getName() == "__vtbl_ptr_type") {
1656 Info.VShapeTI = getTypeIndex(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001657 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1658 // Ignore friend members. It appears that MSVC emitted info about
1659 // friends in the past, but modern versions do not.
1660 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001661 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1662 Info.NestedClasses.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001663 }
1664 // Skip other unrecognized kinds of elements.
1665 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001666 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001667}
1668
Reid Klecknera8d57402016-06-03 15:58:20 +00001669TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1670 // First, construct the forward decl. Don't look into Ty to compute the
1671 // forward decl options, since it might not be available in all TUs.
1672 TypeRecordKind Kind = getRecordKind(Ty);
1673 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001674 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001675 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001676 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
1677 FullName, Ty->getIdentifier());
1678 TypeIndex FwdDeclTI = TypeTable.writeKnownType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001679 if (!Ty->isForwardDecl())
1680 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001681 return FwdDeclTI;
1682}
1683
1684TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1685 // Construct the field list and complete type record.
1686 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00001687 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001688 TypeIndex FieldTI;
1689 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001690 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001691 bool ContainsNestedClass;
1692 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1693 lowerRecordFieldList(Ty);
1694
1695 if (ContainsNestedClass)
1696 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00001697
David Majnemer6bdc24e2016-07-01 23:12:45 +00001698 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001699
Reid Klecknera8d57402016-06-03 15:58:20 +00001700 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001701
Zachary Turner4efa0a42016-11-08 22:24:53 +00001702 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
1703 SizeInBytes, FullName, Ty->getIdentifier());
1704 TypeIndex ClassTI = TypeTable.writeKnownType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001705
Zachary Turner4efa0a42016-11-08 22:24:53 +00001706 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1707 TypeIndex SIDI = TypeTable.writeKnownType(SIDR);
1708 UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine());
1709 TypeTable.writeKnownType(USLR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001710
Hans Wennborg4b63a982016-06-23 22:57:25 +00001711 addToUDTs(Ty, ClassTI);
1712
Hans Wennborg9a519a02016-06-22 21:22:13 +00001713 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001714}
1715
1716TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1717 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001718 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001719 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001720 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
1721 TypeIndex FwdDeclTI = TypeTable.writeKnownType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001722 if (!Ty->isForwardDecl())
1723 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001724 return FwdDeclTI;
1725}
1726
1727TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00001728 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001729 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001730 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001731 bool ContainsNestedClass;
1732 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1733 lowerRecordFieldList(Ty);
1734
1735 if (ContainsNestedClass)
1736 CO |= ClassOptions::ContainsNestedClass;
1737
Reid Klecknera8d57402016-06-03 15:58:20 +00001738 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00001739 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001740
Zachary Turner4efa0a42016-11-08 22:24:53 +00001741 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
1742 Ty->getIdentifier());
1743 TypeIndex UnionTI = TypeTable.writeKnownType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001744
Zachary Turner4efa0a42016-11-08 22:24:53 +00001745 StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1746 TypeIndex SIRI = TypeTable.writeKnownType(SIR);
1747 UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine());
1748 TypeTable.writeKnownType(USLR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001749
Hans Wennborg4b63a982016-06-23 22:57:25 +00001750 addToUDTs(Ty, UnionTI);
1751
Hans Wennborg9a519a02016-06-22 21:22:13 +00001752 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001753}
1754
Adrian McCarthy820ca542016-07-06 19:49:51 +00001755std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00001756CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1757 // Manually count members. MSVC appears to count everything that generates a
1758 // field list record. Each individual overload in a method overload group
1759 // contributes to this count, even though the overload group is a single field
1760 // list record.
1761 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001762 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001763 FieldListRecordBuilder FLBR(TypeTable);
1764 FLBR.begin();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001765
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001766 // Create base classes.
1767 for (const DIDerivedType *I : Info.Inheritance) {
1768 if (I->getFlags() & DINode::FlagVirtual) {
1769 // Virtual base.
1770 // FIXME: Emit VBPtrOffset when the frontend provides it.
1771 unsigned VBPtrOffset = 0;
1772 // FIXME: Despite the accessor name, the offset is really in bytes.
1773 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00001774 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
1775 ? TypeRecordKind::IndirectVirtualBaseClass
1776 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001777 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00001778 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001779 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00001780 VBTableIndex);
1781
1782 FLBR.writeMemberType(VBCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001783 } else {
1784 assert(I->getOffsetInBits() % 8 == 0 &&
1785 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00001786 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
1787 getTypeIndex(I->getBaseType()),
1788 I->getOffsetInBits() / 8);
1789 FLBR.writeMemberType(BCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001790 }
1791 }
1792
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001793 // Create members.
1794 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1795 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1796 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00001797 StringRef MemberName = Member->getName();
1798 MemberAccess Access =
1799 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001800
1801 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001802 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
1803 FLBR.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001804 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001805 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001806 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001807
Reid Kleckner9dac4732016-08-31 15:59:30 +00001808 // Virtual function pointer member.
1809 if ((Member->getFlags() & DINode::FlagArtificial) &&
1810 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001811 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
1812 FLBR.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001813 MemberCount++;
1814 continue;
1815 }
1816
David Majnemer9319cbc2016-06-30 03:00:20 +00001817 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00001818 uint64_t MemberOffsetInBits =
1819 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001820 if (Member->isBitField()) {
1821 uint64_t StartBitOffset = MemberOffsetInBits;
1822 if (const auto *CI =
1823 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00001824 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001825 }
1826 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001827 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
1828 StartBitOffset);
1829 MemberBaseType = TypeTable.writeKnownType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00001830 }
1831 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001832 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
1833 MemberName);
1834 FLBR.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001835 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001836 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001837
1838 // Create methods
1839 for (auto &MethodItr : Info.Methods) {
1840 StringRef Name = MethodItr.first->getString();
1841
1842 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00001843 for (const DISubprogram *SP : MethodItr.second) {
1844 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1845 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001846
1847 unsigned VFTableOffset = -1;
1848 if (Introduced)
1849 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1850
Zachary Turner7251ede2016-11-02 17:05:19 +00001851 Methods.push_back(OneMethodRecord(
1852 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
1853 translateMethodKindFlags(SP, Introduced),
1854 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001855 MemberCount++;
1856 }
1857 assert(Methods.size() > 0 && "Empty methods map entry");
1858 if (Methods.size() == 1)
Zachary Turner4efa0a42016-11-08 22:24:53 +00001859 FLBR.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001860 else {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001861 MethodOverloadListRecord MOLR(Methods);
1862 TypeIndex MethodList = TypeTable.writeKnownType(MOLR);
1863 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
1864 FLBR.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001865 }
1866 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001867
1868 // Create nested classes.
1869 for (const DICompositeType *Nested : Info.NestedClasses) {
1870 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner4efa0a42016-11-08 22:24:53 +00001871 FLBR.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00001872 MemberCount++;
1873 }
1874
Zachary Turner4efa0a42016-11-08 22:24:53 +00001875 TypeIndex FieldTI = FLBR.end();
Reid Kleckner9dac4732016-08-31 15:59:30 +00001876 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Adrian McCarthy820ca542016-07-06 19:49:51 +00001877 !Info.NestedClasses.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00001878}
1879
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001880TypeIndex CodeViewDebug::getVBPTypeIndex() {
1881 if (!VBPType.getIndex()) {
1882 // Make a 'const int *' type.
1883 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001884 TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001885
1886 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1887 : PointerKind::Near32;
1888 PointerMode PM = PointerMode::Pointer;
1889 PointerOptions PO = PointerOptions::None;
1890 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1891
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001892 VBPType = TypeTable.writeKnownType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001893 }
1894
1895 return VBPType;
1896}
1897
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001898TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001899 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001900 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001901
1902 // The null DIType is the void type. Don't try to hash it.
1903 if (!Ty)
1904 return TypeIndex::Void();
1905
Reid Klecknera8d57402016-06-03 15:58:20 +00001906 // Check if we've already translated this type. Don't try to do a
1907 // get-or-create style insertion that caches the hash lookup across the
1908 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001909 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001910 if (I != TypeIndices.end())
1911 return I->second;
1912
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001913 TypeLoweringScope S(*this);
1914 TypeIndex TI = lowerType(Ty, ClassTy);
1915 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00001916}
1917
1918TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1919 const DIType *Ty = TypeRef.resolve();
1920
1921 // The null DIType is the void type. Don't try to hash it.
1922 if (!Ty)
1923 return TypeIndex::Void();
1924
1925 // If this is a non-record type, the complete type index is the same as the
1926 // normal type index. Just call getTypeIndex.
1927 switch (Ty->getTag()) {
1928 case dwarf::DW_TAG_class_type:
1929 case dwarf::DW_TAG_structure_type:
1930 case dwarf::DW_TAG_union_type:
1931 break;
1932 default:
1933 return getTypeIndex(Ty);
1934 }
1935
1936 // Check if we've already translated the complete record type. Lowering a
1937 // complete type should never trigger lowering another complete type, so we
1938 // can reuse the hash table lookup result.
1939 const auto *CTy = cast<DICompositeType>(Ty);
1940 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1941 if (!InsertResult.second)
1942 return InsertResult.first->second;
1943
Reid Kleckner643dd832016-06-22 17:15:28 +00001944 TypeLoweringScope S(*this);
1945
Reid Klecknera8d57402016-06-03 15:58:20 +00001946 // Make sure the forward declaration is emitted first. It's unclear if this
1947 // is necessary, but MSVC does it, and we should follow suit until we can show
1948 // otherwise.
1949 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1950
1951 // Just use the forward decl if we don't have complete type info. This might
1952 // happen if the frontend is using modules and expects the complete definition
1953 // to be emitted elsewhere.
1954 if (CTy->isForwardDecl())
1955 return FwdDeclTI;
1956
1957 TypeIndex TI;
1958 switch (CTy->getTag()) {
1959 case dwarf::DW_TAG_class_type:
1960 case dwarf::DW_TAG_structure_type:
1961 TI = lowerCompleteTypeClass(CTy);
1962 break;
1963 case dwarf::DW_TAG_union_type:
1964 TI = lowerCompleteTypeUnion(CTy);
1965 break;
1966 default:
1967 llvm_unreachable("not a record");
1968 }
1969
1970 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001971 return TI;
1972}
1973
Reid Kleckner643dd832016-06-22 17:15:28 +00001974/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00001975/// and do this until fixpoint, as each complete record type typically
1976/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00001977/// many other record types.
1978void CodeViewDebug::emitDeferredCompleteTypes() {
1979 SmallVector<const DICompositeType *, 4> TypesToEmit;
1980 while (!DeferredCompleteTypes.empty()) {
1981 std::swap(DeferredCompleteTypes, TypesToEmit);
1982 for (const DICompositeType *RecordTy : TypesToEmit)
1983 getCompleteTypeIndex(RecordTy);
1984 TypesToEmit.clear();
1985 }
1986}
1987
Reid Kleckner10dd55c2016-06-24 17:55:40 +00001988void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
1989 // Get the sorted list of parameters and emit them first.
1990 SmallVector<const LocalVariable *, 6> Params;
1991 for (const LocalVariable &L : Locals)
1992 if (L.DIVar->isParameter())
1993 Params.push_back(&L);
1994 std::sort(Params.begin(), Params.end(),
1995 [](const LocalVariable *L, const LocalVariable *R) {
1996 return L->DIVar->getArg() < R->DIVar->getArg();
1997 });
1998 for (const LocalVariable *L : Params)
1999 emitLocalVariable(*L);
2000
2001 // Next emit all non-parameters in the order that we found them.
2002 for (const LocalVariable &L : Locals)
2003 if (!L.DIVar->isParameter())
2004 emitLocalVariable(L);
2005}
2006
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002007void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2008 // LocalSym record, see SymbolRecord.h for more info.
2009 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2010 *LocalEnd = MMI->getContext().createTempSymbol();
2011 OS.AddComment("Record length");
2012 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2013 OS.EmitLabel(LocalBegin);
2014
2015 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00002016 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002017
Zachary Turner63a28462016-05-17 23:50:21 +00002018 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002019 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002020 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002021 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002022 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002023
2024 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00002025 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002026 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002027 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002028 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002029 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002030 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002031 OS.EmitLabel(LocalEnd);
2032
Reid Kleckner876330d2016-02-12 21:48:30 +00002033 // Calculate the on disk prefix of the appropriate def range record. The
2034 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2035 // should be big enough to hold all forms without memory allocation.
2036 SmallString<20> BytePrefix;
2037 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2038 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002039 if (DefRange.InMemory) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002040 uint16_t RegRelFlags = 0;
2041 if (DefRange.IsSubfield) {
2042 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2043 (DefRange.StructOffset
2044 << DefRangeRegisterRelSym::OffsetInParentShift);
2045 }
Zachary Turner46225b12016-12-16 22:48:14 +00002046 DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
2047 Sym.Hdr.Register = DefRange.CVRegister;
2048 Sym.Hdr.Flags = RegRelFlags;
2049 Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +00002050 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00002051 BytePrefix +=
2052 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00002053 BytePrefix +=
Zachary Turner46225b12016-12-16 22:48:14 +00002054 StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
Reid Kleckner876330d2016-02-12 21:48:30 +00002055 } else {
2056 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002057 if (DefRange.IsSubfield) {
2058 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002059 DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2060 Sym.Hdr.Register = DefRange.CVRegister;
2061 Sym.Hdr.MayHaveNoName = 0;
2062 Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2063
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002064 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2065 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2066 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002067 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2068 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002069 } else {
2070 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002071 DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2072 Sym.Hdr.Register = DefRange.CVRegister;
2073 Sym.Hdr.MayHaveNoName = 0;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002074 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2075 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2076 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002077 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2078 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002079 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002080 }
2081 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2082 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002083}
2084
David Blaikieb2fbb4b2017-02-16 18:48:33 +00002085void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002086 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00002087 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002088 assert(CurFn == &FnDebugInfo[GV]);
2089
Pete Cooperadebb932016-03-11 02:14:16 +00002090 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002091
Reid Kleckner2214ed82016-01-29 00:49:42 +00002092 // Don't emit anything if we don't have any line tables.
2093 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002094 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002095 CurFn = nullptr;
2096 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002097 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002098
2099 CurFn->End = Asm->getFunctionEnd();
2100
Craig Topper353eda42014-04-24 06:44:33 +00002101 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002102}
2103
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002104void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002105 DebugHandlerBase::beginInstruction(MI);
2106
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002107 // Ignore DBG_VALUE locations and function prologue.
David Majnemer67f684e2016-07-28 05:03:22 +00002108 if (!Asm || !CurFn || MI->isDebugValue() ||
2109 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002110 return;
2111 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00002112 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002113 return;
2114 maybeRecordLocation(DL, Asm->MF);
2115}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002116
2117MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
2118 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2119 *EndLabel = MMI->getContext().createTempSymbol();
2120 OS.EmitIntValue(unsigned(Kind), 4);
2121 OS.AddComment("Subsection size");
2122 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2123 OS.EmitLabel(BeginLabel);
2124 return EndLabel;
2125}
2126
2127void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2128 OS.EmitLabel(EndLabel);
2129 // Every subsection must be aligned to a 4-byte boundary.
2130 OS.EmitValueToAlignment(4);
2131}
2132
David Majnemer3128b102016-06-15 18:00:01 +00002133void CodeViewDebug::emitDebugInfoForUDTs(
2134 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
2135 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
2136 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2137 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2138 OS.AddComment("Record length");
2139 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2140 OS.EmitLabel(UDTRecordBegin);
2141
2142 OS.AddComment("Record kind: S_UDT");
2143 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2144
2145 OS.AddComment("Type");
2146 OS.EmitIntValue(UDT.second.getIndex(), 4);
2147
2148 emitNullTerminatedSymbolName(OS, UDT.first);
2149 OS.EmitLabel(UDTRecordEnd);
2150 }
2151}
2152
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002153void CodeViewDebug::emitDebugInfoForGlobals() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002154 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2155 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002156 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002157 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2158 GV.getDebugInfo(GVEs);
2159 for (const auto *GVE : GVEs)
2160 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002161 }
2162
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002163 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2164 for (const MDNode *Node : CUs->operands()) {
2165 const auto *CU = cast<DICompileUnit>(Node);
2166
2167 // First, emit all globals that are not in a comdat in a single symbol
2168 // substream. MSVC doesn't like it if the substream is empty, so only open
2169 // it if we have at least one global to emit.
2170 switchToDebugSectionForSymbol(nullptr);
2171 MCSymbol *EndLabel = nullptr;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002172 for (const auto *GVE : CU->getGlobalVariables()) {
2173 if (const auto *GV = GlobalMap.lookup(GVE))
David Majnemer577be0f2016-06-15 00:19:52 +00002174 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002175 if (!EndLabel) {
2176 OS.AddComment("Symbol subsection for globals");
2177 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
2178 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002179 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2180 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002181 }
2182 }
2183 if (EndLabel)
2184 endCVSubsection(EndLabel);
2185
2186 // Second, emit each global that is in a comdat into its own .debug$S
2187 // section along with its own symbol substream.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002188 for (const auto *GVE : CU->getGlobalVariables()) {
2189 if (const auto *GV = GlobalMap.lookup(GVE)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002190 if (GV->hasComdat()) {
2191 MCSymbol *GVSym = Asm->getSymbol(GV);
2192 OS.AddComment("Symbol subsection for " +
2193 Twine(GlobalValue::getRealLinkageName(GV->getName())));
2194 switchToDebugSectionForSymbol(GVSym);
2195 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002196 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2197 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002198 endCVSubsection(EndLabel);
2199 }
2200 }
2201 }
2202 }
2203}
2204
Hans Wennborgb510b452016-06-23 16:33:53 +00002205void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2206 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2207 for (const MDNode *Node : CUs->operands()) {
2208 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2209 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2210 getTypeIndex(RT);
2211 // FIXME: Add to global/local DTU list.
2212 }
2213 }
2214 }
2215}
2216
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002217void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002218 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002219 MCSymbol *GVSym) {
2220 // DataSym record, see SymbolRecord.h for more info.
2221 // FIXME: Thread local data, etc
2222 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2223 *DataEnd = MMI->getContext().createTempSymbol();
2224 OS.AddComment("Record length");
2225 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2226 OS.EmitLabel(DataBegin);
David Majnemer7abd2692016-07-06 21:07:47 +00002227 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002228 if (GV->isThreadLocal()) {
2229 OS.AddComment("Record kind: S_LTHREAD32");
2230 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2231 } else {
2232 OS.AddComment("Record kind: S_LDATA32");
2233 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2234 }
David Majnemer7abd2692016-07-06 21:07:47 +00002235 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002236 if (GV->isThreadLocal()) {
2237 OS.AddComment("Record kind: S_GTHREAD32");
2238 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2239 } else {
2240 OS.AddComment("Record kind: S_GDATA32");
2241 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2242 }
David Majnemer7abd2692016-07-06 21:07:47 +00002243 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002244 OS.AddComment("Type");
2245 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2246 OS.AddComment("DataOffset");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00002247 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002248 OS.AddComment("Segment");
2249 OS.EmitCOFFSectionIndex(GVSym);
2250 OS.AddComment("Name");
2251 emitNullTerminatedSymbolName(OS, DIGV->getName());
2252 OS.EmitLabel(DataEnd);
2253}