blob: 98163bffb60b20d675b02ff4667013cef9f06928 [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"
Zachary Turneredef1452017-05-02 16:56:09 +000020#include "llvm/DebugInfo/CodeView/ModuleDebugInlineeLinesFragment.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000021#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Zachary Turnerc640b762017-01-11 00:35:08 +000022#include "llvm/DebugInfo/CodeView/TypeDatabase.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000023#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000024#include "llvm/DebugInfo/CodeView/TypeIndex.h"
25#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000026#include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000027#include "llvm/IR/Constants.h"
Reid Kleckner46cb48c2016-07-27 16:03:57 +000028#include "llvm/MC/MCAsmInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000029#include "llvm/MC/MCExpr.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000030#include "llvm/MC/MCSectionCOFF.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000031#include "llvm/MC/MCSymbol.h"
Zachary Turnerd9dc2822017-03-02 20:52:51 +000032#include "llvm/Support/BinaryByteStream.h"
33#include "llvm/Support/BinaryStreamReader.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000034#include "llvm/Support/COFF.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000035#include "llvm/Support/ScopedPrinter.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000036#include "llvm/Target/TargetFrameLowering.h"
Amjad Aboud76c9eb92016-06-18 10:25:07 +000037#include "llvm/Target/TargetRegisterInfo.h"
38#include "llvm/Target/TargetSubtargetInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000039
Reid Klecknerf9c275f2016-02-10 20:55:49 +000040using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000041using namespace llvm::codeview;
42
Reid Klecknerf9c275f2016-02-10 20:55:49 +000043CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
Zachary Turnerc6d54da2016-09-09 17:46:17 +000044 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), Allocator(),
45 TypeTable(Allocator), CurFn(nullptr) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +000046 // If module doesn't have named metadata anchors or COFF debug section
47 // is not available, skip any debug info related stuff.
48 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
49 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
50 Asm = nullptr;
51 return;
52 }
53
54 // Tell MMI that we have debug info.
55 MMI->setDebugInfoAvailability(true);
56}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000057
Reid Kleckner9533af42016-01-16 00:09:09 +000058StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
59 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000060 if (!Filepath.empty())
61 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000062
Reid Kleckner9533af42016-01-16 00:09:09 +000063 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
64
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000065 // Clang emits directory and relative filename info into the IR, but CodeView
66 // operates on full paths. We could change Clang to emit full paths too, but
67 // that would increase the IR size and probably not needed for other users.
68 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000069 if (Filename.find(':') == 1)
70 Filepath = Filename;
71 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +000072 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000073
74 // Canonicalize the path. We have to do it textually because we may no longer
75 // have access the file in the filesystem.
76 // First, replace all slashes with backslashes.
77 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
78
79 // Remove all "\.\" with "\".
80 size_t Cursor = 0;
81 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
82 Filepath.erase(Cursor, 2);
83
84 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
85 // path should be well-formatted, e.g. start with a drive letter, etc.
86 Cursor = 0;
87 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
88 // Something's wrong if the path starts with "\..\", abort.
89 if (Cursor == 0)
90 break;
91
92 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
93 if (PrevSlash == std::string::npos)
94 // Something's wrong, abort.
95 break;
96
97 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
98 // The next ".." might be following the one we've just erased.
99 Cursor = PrevSlash;
100 }
101
102 // Remove all duplicate backslashes.
103 Cursor = 0;
104 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
105 Filepath.erase(Cursor, 1);
106
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000107 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000108}
109
Reid Kleckner2214ed82016-01-29 00:49:42 +0000110unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
111 unsigned NextId = FileIdMap.size() + 1;
112 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
113 if (Insertion.second) {
114 // We have to compute the full filepath and emit a .cv_file directive.
115 StringRef FullPath = getFullFilepath(F);
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000116 bool Success = OS.EmitCVFileDirective(NextId, FullPath);
117 (void)Success;
118 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000119 }
120 return Insertion.first->second;
121}
122
Reid Kleckner876330d2016-02-12 21:48:30 +0000123CodeViewDebug::InlineSite &
124CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
125 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000126 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
127 InlineSite *Site = &SiteInsertion.first->second;
128 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000129 unsigned ParentFuncId = CurFn->FuncId;
130 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
131 ParentFuncId =
132 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
133 .SiteFuncId;
134
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000135 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000136 OS.EmitCVInlineSiteIdDirective(
137 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
138 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000139 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000140 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000141 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000142 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000143 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000144}
145
David Majnemer6bdc24e2016-07-01 23:12:45 +0000146static StringRef getPrettyScopeName(const DIScope *Scope) {
147 StringRef ScopeName = Scope->getName();
148 if (!ScopeName.empty())
149 return ScopeName;
150
151 switch (Scope->getTag()) {
152 case dwarf::DW_TAG_enumeration_type:
153 case dwarf::DW_TAG_class_type:
154 case dwarf::DW_TAG_structure_type:
155 case dwarf::DW_TAG_union_type:
156 return "<unnamed-tag>";
157 case dwarf::DW_TAG_namespace:
158 return "`anonymous namespace'";
159 }
160
161 return StringRef();
162}
163
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000164static const DISubprogram *getQualifiedNameComponents(
165 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
166 const DISubprogram *ClosestSubprogram = nullptr;
167 while (Scope != nullptr) {
168 if (ClosestSubprogram == nullptr)
169 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000170 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000171 if (!ScopeName.empty())
172 QualifiedNameComponents.push_back(ScopeName);
173 Scope = Scope->getScope().resolve();
174 }
175 return ClosestSubprogram;
176}
177
178static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
179 StringRef TypeName) {
180 std::string FullyQualifiedName;
181 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
182 FullyQualifiedName.append(QualifiedNameComponent);
183 FullyQualifiedName.append("::");
184 }
185 FullyQualifiedName.append(TypeName);
186 return FullyQualifiedName;
187}
188
189static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
190 SmallVector<StringRef, 5> QualifiedNameComponents;
191 getQualifiedNameComponents(Scope, QualifiedNameComponents);
192 return getQualifiedName(QualifiedNameComponents, Name);
193}
194
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000195struct CodeViewDebug::TypeLoweringScope {
196 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
197 ~TypeLoweringScope() {
198 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
199 // inner TypeLoweringScopes don't attempt to emit deferred types.
200 if (CVD.TypeEmissionLevel == 1)
201 CVD.emitDeferredCompleteTypes();
202 --CVD.TypeEmissionLevel;
203 }
204 CodeViewDebug &CVD;
205};
206
David Majnemer6bdc24e2016-07-01 23:12:45 +0000207static std::string getFullyQualifiedName(const DIScope *Ty) {
208 const DIScope *Scope = Ty->getScope().resolve();
209 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
210}
211
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000212TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
213 // No scope means global scope and that uses the zero index.
214 if (!Scope || isa<DIFile>(Scope))
215 return TypeIndex();
216
217 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
218
219 // Check if we've already translated this scope.
220 auto I = TypeIndices.find({Scope, nullptr});
221 if (I != TypeIndices.end())
222 return I->second;
223
224 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000225 std::string ScopeName = getFullyQualifiedName(Scope);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000226 StringIdRecord SID(TypeIndex(), ScopeName);
227 auto TI = TypeTable.writeKnownType(SID);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000228 return recordTypeIndexForDINode(Scope, TI);
229}
230
David Majnemer75c3ebf2016-06-02 17:13:53 +0000231TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000232 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000233
David Majnemer75c3ebf2016-06-02 17:13:53 +0000234 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000235 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000236 if (I != TypeIndices.end())
237 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000238
Reid Klecknerac945e22016-06-17 16:11:20 +0000239 // The display name includes function template arguments. Drop them to match
240 // MSVC.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000241 StringRef DisplayName = SP->getName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000242
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000243 const DIScope *Scope = SP->getScope().resolve();
244 TypeIndex TI;
245 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
246 // If the scope is a DICompositeType, then this must be a method. Member
247 // function types take some special handling, and require access to the
248 // subprogram.
249 TypeIndex ClassType = getTypeIndex(Class);
250 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
251 DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000252 TI = TypeTable.writeKnownType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000253 } else {
254 // Otherwise, this must be a free function.
255 TypeIndex ParentScope = getScopeIndex(Scope);
256 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000257 TI = TypeTable.writeKnownType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000258 }
259
260 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000261}
262
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000263TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
264 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000265 // Always use the method declaration as the key for the function type. The
266 // method declaration contains the this adjustment.
267 if (SP->getDeclaration())
268 SP = SP->getDeclaration();
269 assert(!SP->getDeclaration() && "should use declaration as key");
270
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000271 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
272 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000273 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000274 if (I != TypeIndices.end())
275 return I->second;
276
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000277 // Make sure complete type info for the class is emitted *after* the member
278 // function type, as the complete class type is likely to reference this
279 // member function type.
280 TypeLoweringScope S(*this);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000281 TypeIndex TI =
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000282 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000283 return recordTypeIndexForDINode(SP, TI, Class);
284}
285
Amjad Aboudacee5682016-07-12 12:06:34 +0000286TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
287 TypeIndex TI,
288 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000289 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000290 (void)InsertResult;
291 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000292 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000293}
294
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000295unsigned CodeViewDebug::getPointerSizeInBytes() {
296 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
297}
298
Reid Kleckner876330d2016-02-12 21:48:30 +0000299void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
300 const DILocation *InlinedAt) {
301 if (InlinedAt) {
302 // This variable was inlined. Associate it with the InlineSite.
303 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
304 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
305 Site.InlinedLocals.emplace_back(Var);
306 } else {
307 // This variable goes in the main ProcSym.
308 CurFn->Locals.emplace_back(Var);
309 }
310}
311
Reid Kleckner829365a2016-02-11 19:41:47 +0000312static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
313 const DILocation *Loc) {
314 auto B = Locs.begin(), E = Locs.end();
315 if (std::find(B, E, Loc) == E)
316 Locs.push_back(Loc);
317}
318
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000319void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000320 const MachineFunction *MF) {
321 // Skip this instruction if it has the same location as the previous one.
322 if (DL == CurFn->LastLoc)
323 return;
324
325 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000326 if (!Scope)
327 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000328
David Majnemerc3340db2016-01-13 01:05:23 +0000329 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000330 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
331 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
332 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000333 return;
334
Reid Kleckner2214ed82016-01-29 00:49:42 +0000335 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
336 if (CI.getStartColumn() != DL.getCol())
337 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000338
Reid Kleckner2214ed82016-01-29 00:49:42 +0000339 if (!CurFn->HaveLineInfo)
340 CurFn->HaveLineInfo = true;
341 unsigned FileId = 0;
342 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
343 FileId = CurFn->LastFileId;
344 else
345 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
346 CurFn->LastLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000347
348 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000349 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000350 const DILocation *Loc = DL.get();
351
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000352 // If this location was actually inlined from somewhere else, give it the ID
353 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000354 FuncId =
355 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000356
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000357 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000358 bool FirstLoc = true;
359 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000360 InlineSite &Site =
361 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000362 if (!FirstLoc)
363 addLocIfNotPresent(Site.ChildSites, Loc);
364 FirstLoc = false;
365 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000366 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000367 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000368 }
369
Reid Klecknerdac21b42016-02-03 21:15:48 +0000370 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000371 /*PrologueEnd=*/false, /*IsStmt=*/false,
372 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000373}
374
Reid Kleckner5d122f82016-05-25 23:16:12 +0000375void CodeViewDebug::emitCodeViewMagicVersion() {
376 OS.EmitValueToAlignment(4);
377 OS.AddComment("Debug section magic");
378 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
379}
380
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000381void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000382 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000383 return;
384
385 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000386
387 // The COFF .debug$S section consists of several subsections, each starting
388 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
389 // of the payload followed by the payload itself. The subsections are 4-byte
390 // aligned.
391
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000392 // Use the generic .debug$S section, and make a subsection for all the inlined
393 // subprograms.
394 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000395
Zachary Turner67c56012017-04-27 16:11:19 +0000396 MCSymbol *CompilerInfo = beginCVSubsection(ModuleDebugFragmentKind::Symbols);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000397 emitCompilerInformation();
398 endCVSubsection(CompilerInfo);
399
Reid Kleckner5d122f82016-05-25 23:16:12 +0000400 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000401
Reid Kleckner2214ed82016-01-29 00:49:42 +0000402 // Emit per-function debug information.
403 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000404 if (!P.first->isDeclarationForLinker())
405 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000406
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000407 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000408 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000409 emitDebugInfoForGlobals();
410
Hans Wennborgb510b452016-06-23 16:33:53 +0000411 // Emit retained types.
412 emitDebugInfoForRetainedTypes();
413
Reid Kleckner5d122f82016-05-25 23:16:12 +0000414 // Switch back to the generic .debug$S section after potentially processing
415 // comdat symbol sections.
416 switchToDebugSectionForSymbol(nullptr);
417
David Majnemer3128b102016-06-15 18:00:01 +0000418 // Emit UDT records for any types used by global variables.
419 if (!GlobalUDTs.empty()) {
Zachary Turner67c56012017-04-27 16:11:19 +0000420 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleDebugFragmentKind::Symbols);
David Majnemer3128b102016-06-15 18:00:01 +0000421 emitDebugInfoForUDTs(GlobalUDTs);
422 endCVSubsection(SymbolsEnd);
423 }
424
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000425 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000426 OS.AddComment("File index to string table offset subsection");
427 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000428
429 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000430 OS.AddComment("String table");
431 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000432
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000433 // Emit type information last, so that any types we translate while emitting
434 // function info are included.
435 emitTypeInformation();
436
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000437 clear();
438}
439
David Majnemerb9456a52016-03-14 05:15:09 +0000440static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000441 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
442 // after a fixed length portion of the record. The fixed length portion should
443 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
444 // overall record size is less than the maximum allowed.
445 unsigned MaxFixedRecordLength = 0xF00;
446 SmallString<32> NullTerminatedString(
447 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000448 NullTerminatedString.push_back('\0');
449 OS.EmitBytes(NullTerminatedString);
450}
451
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000452void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000453 // Do nothing if we have no debug info or if no non-trivial types were emitted
454 // to TypeTable during codegen.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000455 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
Reid Klecknerfbd77872016-03-18 18:54:32 +0000456 if (!CU_Nodes)
457 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000458 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000459 return;
460
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000461 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000462 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000463 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000464
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000465 SmallString<8> CommentPrefix;
466 if (OS.isVerboseAsm()) {
467 CommentPrefix += '\t';
468 CommentPrefix += Asm->MAI->getCommentString();
469 CommentPrefix += ' ';
470 }
471
Zachary Turner8c746732017-05-05 22:02:37 +0000472 TypeDatabase TypeDB(TypeTable.records().size());
Zachary Turner629cb7d2017-01-11 23:24:22 +0000473 CVTypeDumper CVTD(TypeDB);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000474 TypeTable.ForEachRecord([&](TypeIndex Index, ArrayRef<uint8_t> Record) {
475 if (OS.isVerboseAsm()) {
476 // Emit a block comment describing the type record for readability.
477 SmallString<512> CommentBlock;
478 raw_svector_ostream CommentOS(CommentBlock);
479 ScopedPrinter SP(CommentOS);
480 SP.setPrefix(CommentPrefix);
Zachary Turner629cb7d2017-01-11 23:24:22 +0000481 TypeDumpVisitor TDV(TypeDB, &SP, false);
482 Error E = CVTD.dump(Record, TDV);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000483 if (E) {
484 logAllUnhandledErrors(std::move(E), errs(), "error: ");
485 llvm_unreachable("produced malformed type record");
486 }
487 // emitRawComment will insert its own tab and comment string before
488 // the first line, so strip off our first one. It also prints its own
489 // newline.
490 OS.emitRawComment(
491 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
492 } else {
Reid Klecknerc92e9462016-07-01 18:05:56 +0000493#ifndef NDEBUG
Zachary Turner4efa0a42016-11-08 22:24:53 +0000494 // Assert that the type data is valid even if we aren't dumping
495 // comments. The MSVC linker doesn't do much type record validation,
496 // so the first link of an invalid type record can succeed while
497 // subsequent links will fail with LNK1285.
Zachary Turner695ed562017-02-28 00:04:07 +0000498 BinaryByteStream Stream(Record, llvm::support::little);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000499 CVTypeArray Types;
Zachary Turner120faca2017-02-27 22:11:43 +0000500 BinaryStreamReader Reader(Stream);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000501 Error E = Reader.readArray(Types, Reader.getLength());
502 if (!E) {
503 TypeVisitorCallbacks C;
504 E = CVTypeVisitor(C).visitTypeStream(Types);
505 }
506 if (E) {
507 logAllUnhandledErrors(std::move(E), errs(), "error: ");
508 llvm_unreachable("produced malformed type record");
509 }
Reid Klecknerc92e9462016-07-01 18:05:56 +0000510#endif
Zachary Turner4efa0a42016-11-08 22:24:53 +0000511 }
512 StringRef S(reinterpret_cast<const char *>(Record.data()), Record.size());
513 OS.EmitBinaryData(S);
514 });
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000515}
516
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000517namespace {
518
519static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
520 switch (DWLang) {
521 case dwarf::DW_LANG_C:
522 case dwarf::DW_LANG_C89:
523 case dwarf::DW_LANG_C99:
524 case dwarf::DW_LANG_C11:
525 case dwarf::DW_LANG_ObjC:
526 return SourceLanguage::C;
527 case dwarf::DW_LANG_C_plus_plus:
528 case dwarf::DW_LANG_C_plus_plus_03:
529 case dwarf::DW_LANG_C_plus_plus_11:
530 case dwarf::DW_LANG_C_plus_plus_14:
531 return SourceLanguage::Cpp;
532 case dwarf::DW_LANG_Fortran77:
533 case dwarf::DW_LANG_Fortran90:
534 case dwarf::DW_LANG_Fortran03:
535 case dwarf::DW_LANG_Fortran08:
536 return SourceLanguage::Fortran;
537 case dwarf::DW_LANG_Pascal83:
538 return SourceLanguage::Pascal;
539 case dwarf::DW_LANG_Cobol74:
540 case dwarf::DW_LANG_Cobol85:
541 return SourceLanguage::Cobol;
542 case dwarf::DW_LANG_Java:
543 return SourceLanguage::Java;
544 default:
545 // There's no CodeView representation for this language, and CV doesn't
546 // have an "unknown" option for the language field, so we'll use MASM,
547 // as it's very low level.
548 return SourceLanguage::Masm;
549 }
550}
551
552struct Version {
553 int Part[4];
554};
555
556// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
557// the version number.
558static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000559 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000560 int N = 0;
561 for (const char C : Name) {
562 if (isdigit(C)) {
563 V.Part[N] *= 10;
564 V.Part[N] += C - '0';
565 } else if (C == '.') {
566 ++N;
567 if (N >= 4)
568 return V;
569 } else if (N > 0)
570 return V;
571 }
572 return V;
573}
574
575static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
576 switch (Type) {
577 case Triple::ArchType::x86:
578 return CPUType::Pentium3;
579 case Triple::ArchType::x86_64:
580 return CPUType::X64;
581 case Triple::ArchType::thumb:
582 return CPUType::Thumb;
583 default:
584 report_fatal_error("target architecture doesn't map to a CodeView "
585 "CPUType");
586 }
587}
588
589} // anonymous namespace
590
591void CodeViewDebug::emitCompilerInformation() {
592 MCContext &Context = MMI->getContext();
593 MCSymbol *CompilerBegin = Context.createTempSymbol(),
594 *CompilerEnd = Context.createTempSymbol();
595 OS.AddComment("Record length");
596 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
597 OS.EmitLabel(CompilerBegin);
598 OS.AddComment("Record kind: S_COMPILE3");
599 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
600 uint32_t Flags = 0;
601
602 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
603 const MDNode *Node = *CUs->operands().begin();
604 const auto *CU = cast<DICompileUnit>(Node);
605
606 // The low byte of the flags indicates the source language.
607 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
608 // TODO: Figure out which other flags need to be set.
609
610 OS.AddComment("Flags and language");
611 OS.EmitIntValue(Flags, 4);
612
613 OS.AddComment("CPUType");
614 CPUType CPU =
615 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
616 OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
617
618 StringRef CompilerVersion = CU->getProducer();
619 Version FrontVer = parseVersion(CompilerVersion);
620 OS.AddComment("Frontend version");
621 for (int N = 0; N < 4; ++N)
622 OS.EmitIntValue(FrontVer.Part[N], 2);
623
624 // Some Microsoft tools, like Binscope, expect a backend version number of at
625 // least 8.something, so we'll coerce the LLVM version into a form that
626 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000627 int Major = 1000 * LLVM_VERSION_MAJOR +
628 10 * LLVM_VERSION_MINOR +
629 LLVM_VERSION_PATCH;
630 // Clamp it for builds that use unusually large version numbers.
631 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
632 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000633 OS.AddComment("Backend version");
634 for (int N = 0; N < 4; ++N)
635 OS.EmitIntValue(BackVer.Part[N], 2);
636
637 OS.AddComment("Null-terminated compiler version string");
638 emitNullTerminatedSymbolName(OS, CompilerVersion);
639
640 OS.EmitLabel(CompilerEnd);
641}
642
Reid Kleckner5d122f82016-05-25 23:16:12 +0000643void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000644 if (InlinedSubprograms.empty())
645 return;
646
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000647 OS.AddComment("Inlinee lines subsection");
Zachary Turner67c56012017-04-27 16:11:19 +0000648 MCSymbol *InlineEnd =
649 beginCVSubsection(ModuleDebugFragmentKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000650
651 // We don't provide any extra file info.
652 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000653 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000654 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
655
656 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000657 assert(TypeIndices.count({SP, nullptr}));
658 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000659
David Majnemer30579ec2016-02-02 23:18:23 +0000660 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000661 unsigned FileId = maybeRecordFile(SP->getFile());
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000662 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000663 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000664 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000665 // The filechecksum table uses 8 byte entries for now, and file ids start at
666 // 1.
667 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000668 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000669 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000670 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000671 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000672 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000673 OS.EmitIntValue(SP->getLine(), 4);
674 }
675
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000676 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000677}
678
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000679void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
680 const DILocation *InlinedAt,
681 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000682 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
683 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000684
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000685 assert(TypeIndices.count({Site.Inlinee, nullptr}));
686 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000687
688 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000689 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000690 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000691 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000692 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000693 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000694
Reid Klecknerdac21b42016-02-03 21:15:48 +0000695 OS.AddComment("PtrParent");
696 OS.EmitIntValue(0, 4);
697 OS.AddComment("PtrEnd");
698 OS.EmitIntValue(0, 4);
699 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000700 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000701
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000702 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
703 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000704
705 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000706 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000707
708 OS.EmitLabel(InlineEnd);
709
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000710 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000711
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000712 // Recurse on child inlined call sites before closing the scope.
713 for (const DILocation *ChildSite : Site.ChildSites) {
714 auto I = FI.InlineSites.find(ChildSite);
715 assert(I != FI.InlineSites.end() &&
716 "child site not in function inline site map");
717 emitInlinedCallSite(FI, ChildSite, I->second);
718 }
719
720 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000721 OS.AddComment("Record length");
722 OS.EmitIntValue(2, 2); // RecordLength
723 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000724 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000725}
726
Reid Kleckner5d122f82016-05-25 23:16:12 +0000727void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
728 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
729 // comdat key. A section may be comdat because of -ffunction-sections or
730 // because it is comdat in the IR.
731 MCSectionCOFF *GVSec =
732 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
733 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
734
735 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
736 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
737 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
738
739 OS.SwitchSection(DebugSec);
740
741 // Emit the magic version number if this is the first time we've switched to
742 // this section.
743 if (ComdatDebugSections.insert(DebugSec).second)
744 emitCodeViewMagicVersion();
745}
746
Reid Kleckner2214ed82016-01-29 00:49:42 +0000747void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
748 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000749 // For each function there is a separate subsection
750 // which holds the PC to file:line table.
751 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000752 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000753
Reid Kleckner5d122f82016-05-25 23:16:12 +0000754 // Switch to the to a comdat section, if appropriate.
755 switchToDebugSectionForSymbol(Fn);
756
Reid Klecknerac945e22016-06-17 16:11:20 +0000757 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000758 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000759 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000760 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000761
762 // If we have a display name, build the fully qualified name by walking the
763 // chain of scopes.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000764 if (!SP->getName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000765 FuncName =
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000766 getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000767
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000768 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000769 if (FuncName.empty())
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +0000770 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000771
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000772 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000773 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Zachary Turner67c56012017-04-27 16:11:19 +0000774 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleDebugFragmentKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000775 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000776 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
777 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000778 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000779 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000780 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000781
Reid Kleckner4ad127f2016-09-14 21:49:21 +0000782 if (GV->hasLocalLinkage()) {
783 OS.AddComment("Record kind: S_LPROC32_ID");
784 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
785 } else {
786 OS.AddComment("Record kind: S_GPROC32_ID");
787 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
788 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000789
David Majnemer30579ec2016-02-02 23:18:23 +0000790 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000791 OS.AddComment("PtrParent");
792 OS.EmitIntValue(0, 4);
793 OS.AddComment("PtrEnd");
794 OS.EmitIntValue(0, 4);
795 OS.AddComment("PtrNext");
796 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000797 // This is the important bit that tells the debugger where the function
798 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000799 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000800 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000801 OS.AddComment("Offset after prologue");
802 OS.EmitIntValue(0, 4);
803 OS.AddComment("Offset before epilogue");
804 OS.EmitIntValue(0, 4);
805 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000806 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000807 OS.AddComment("Function section relative address");
Keno Fischerf7d84ee2017-01-02 03:00:19 +0000808 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000809 OS.AddComment("Function section index");
810 OS.EmitCOFFSectionIndex(Fn);
811 OS.AddComment("Flags");
812 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000813 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000814 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000815 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000816 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000817 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000818
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000819 emitLocalVariableList(FI.Locals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000820
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000821 // Emit inlined call site information. Only emit functions inlined directly
822 // into the parent function. We'll emit the other sites recursively as part
823 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000824 for (const DILocation *InlinedAt : FI.ChildSites) {
825 auto I = FI.InlineSites.find(InlinedAt);
826 assert(I != FI.InlineSites.end() &&
827 "child site not in function inline site map");
828 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000829 }
830
David Majnemer3128b102016-06-15 18:00:01 +0000831 if (SP != nullptr)
832 emitDebugInfoForUDTs(LocalUDTs);
833
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000834 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000835 OS.AddComment("Record length");
836 OS.EmitIntValue(0x0002, 2);
837 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000838 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000839 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000840 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000841
Reid Kleckner2214ed82016-01-29 00:49:42 +0000842 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000843 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000844}
845
Reid Kleckner876330d2016-02-12 21:48:30 +0000846CodeViewDebug::LocalVarDefRange
847CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
848 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000849 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000850 DR.DataOffset = Offset;
851 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000852 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000853 DR.StructOffset = 0;
854 DR.CVRegister = CVRegister;
855 return DR;
856}
857
858CodeViewDebug::LocalVarDefRange
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000859CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
860 int Offset, bool IsSubfield,
861 uint16_t StructOffset) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000862 LocalVarDefRange DR;
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000863 DR.InMemory = InMemory;
864 DR.DataOffset = Offset;
865 DR.IsSubfield = IsSubfield;
866 DR.StructOffset = StructOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +0000867 DR.CVRegister = CVRegister;
868 return DR;
869}
870
Matthias Braunef331ef2016-11-30 23:48:50 +0000871void CodeViewDebug::collectVariableInfoFromMFTable(
Reid Kleckner876330d2016-02-12 21:48:30 +0000872 DenseSet<InlinedVariable> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +0000873 const MachineFunction &MF = *Asm->MF;
874 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +0000875 const TargetFrameLowering *TFI = TSI.getFrameLowering();
876 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
877
Matthias Braunef331ef2016-11-30 23:48:50 +0000878 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000879 if (!VI.Var)
880 continue;
881 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
882 "Expected inlined-at fields to agree");
883
Reid Kleckner876330d2016-02-12 21:48:30 +0000884 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000885 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
886
887 // If variable scope is not found then skip this variable.
888 if (!Scope)
889 continue;
890
Reid Klecknerb5fced72017-05-09 19:59:29 +0000891 // If the variable has an attached offset expression, extract it.
892 // FIXME: Try to handle DW_OP_deref as well.
893 int64_t ExprOffset = 0;
894 if (VI.Expr)
895 if (!VI.Expr->extractIfOffset(ExprOffset))
896 continue;
897
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000898 // Get the frame register used and the offset.
899 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000900 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
901 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000902
903 // Calculate the label ranges.
Reid Klecknerb5fced72017-05-09 19:59:29 +0000904 LocalVarDefRange DefRange =
905 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000906 for (const InsnRange &Range : Scope->getRanges()) {
907 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
908 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000909 End = End ? End : Asm->getFunctionEnd();
910 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000911 }
912
Reid Kleckner876330d2016-02-12 21:48:30 +0000913 LocalVariable Var;
914 Var.DIVar = VI.Var;
915 Var.DefRanges.emplace_back(std::move(DefRange));
916 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
917 }
918}
919
920void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
921 DenseSet<InlinedVariable> Processed;
922 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +0000923 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +0000924
925 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
926
927 for (const auto &I : DbgValues) {
928 InlinedVariable IV = I.first;
929 if (Processed.count(IV))
930 continue;
931 const DILocalVariable *DIVar = IV.first;
932 const DILocation *InlinedAt = IV.second;
933
934 // Instruction ranges, specifying where IV is accessible.
935 const auto &Ranges = I.second;
936
937 LexicalScope *Scope = nullptr;
938 if (InlinedAt)
939 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
940 else
941 Scope = LScopes.findLexicalScope(DIVar->getScope());
942 // If variable scope is not found then skip this variable.
943 if (!Scope)
944 continue;
945
946 LocalVariable Var;
947 Var.DIVar = DIVar;
948
949 // Calculate the definition ranges.
950 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
951 const InsnRange &Range = *I;
952 const MachineInstr *DVInst = Range.first;
953 assert(DVInst->isDebugValue() && "Invalid History entry");
954 const DIExpression *DIExpr = DVInst->getDebugExpression();
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000955 bool IsSubfield = false;
956 unsigned StructOffset = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000957
Adrian Prantl941fa752016-12-05 18:04:47 +0000958 // Handle fragments.
Adrian Prantl49797ca2016-12-22 05:27:12 +0000959 auto Fragment = DIExpr->getFragmentInfo();
Adrian Prantle8450fd2017-03-27 17:36:31 +0000960 if (Fragment) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000961 IsSubfield = true;
Adrian Prantl49797ca2016-12-22 05:27:12 +0000962 StructOffset = Fragment->OffsetInBits / 8;
Adrian Prantle8450fd2017-03-27 17:36:31 +0000963 } else if (DIExpr->getNumElements() > 0) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000964 continue; // Ignore unrecognized exprs.
965 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000966
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000967 // Bail if operand 0 is not a valid register. This means the variable is a
968 // simple constant, or is described by a complex expression.
969 // FIXME: Find a way to represent constant variables, since they are
970 // relatively common.
971 unsigned Reg =
972 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
973 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000974 continue;
975
Reid Kleckner876330d2016-02-12 21:48:30 +0000976 // Handle the two cases we can handle: indirect in memory and in register.
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000977 unsigned CVReg = TRI->getCodeViewRegNum(Reg);
978 bool InMemory = DVInst->getOperand(1).isImm();
979 int Offset = InMemory ? DVInst->getOperand(1).getImm() : 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000980 {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000981 LocalVarDefRange DR;
982 DR.CVRegister = CVReg;
983 DR.InMemory = InMemory;
984 DR.DataOffset = Offset;
985 DR.IsSubfield = IsSubfield;
986 DR.StructOffset = StructOffset;
987
Reid Kleckner876330d2016-02-12 21:48:30 +0000988 if (Var.DefRanges.empty() ||
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000989 Var.DefRanges.back().isDifferentLocation(DR)) {
990 Var.DefRanges.emplace_back(std::move(DR));
Reid Kleckner876330d2016-02-12 21:48:30 +0000991 }
992 }
993
994 // Compute the label range.
995 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
996 const MCSymbol *End = getLabelAfterInsn(Range.second);
997 if (!End) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000998 // This range is valid until the next overlapping bitpiece. In the
999 // common case, ranges will not be bitpieces, so they will overlap.
1000 auto J = std::next(I);
Adrian Prantl941fa752016-12-05 18:04:47 +00001001 while (J != E &&
1002 !fragmentsOverlap(DIExpr, J->first->getDebugExpression()))
Reid Kleckner2b3e6422016-10-05 21:21:33 +00001003 ++J;
1004 if (J != E)
1005 End = getLabelBeforeInsn(J->first);
Reid Kleckner876330d2016-02-12 21:48:30 +00001006 else
1007 End = Asm->getFunctionEnd();
1008 }
1009
1010 // If the last range end is our begin, just extend the last range.
1011 // Otherwise make a new range.
1012 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
1013 Var.DefRanges.back().Ranges;
1014 if (!Ranges.empty() && Ranges.back().second == Begin)
1015 Ranges.back().second = End;
1016 else
1017 Ranges.emplace_back(Begin, End);
1018
1019 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001020 }
Reid Kleckner876330d2016-02-12 21:48:30 +00001021
1022 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001023 }
1024}
1025
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001026void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001027 const Function *GV = MF->getFunction();
1028 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001029 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +00001030 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001031 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001032
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001033 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1034
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001035 // Find the end of the function prolog. First known non-DBG_VALUE and
1036 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001037 // FIXME: is there a simpler a way to do this? Can we just search
1038 // for the first instruction of the function, not the last of the prolog?
1039 DebugLoc PrologEndLoc;
1040 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001041 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001042 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001043 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1044 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001045 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001046 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001047 } else if (!MI.isDebugValue()) {
1048 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001049 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001050 }
1051 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001052
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001053 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001054 if (PrologEndLoc && !EmptyPrologue) {
1055 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001056 maybeRecordLocation(FnStartDL, MF);
1057 }
1058}
1059
Hans Wennborg4b63a982016-06-23 22:57:25 +00001060void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001061 // Don't record empty UDTs.
1062 if (Ty->getName().empty())
1063 return;
1064
Hans Wennborg4b63a982016-06-23 22:57:25 +00001065 SmallVector<StringRef, 5> QualifiedNameComponents;
1066 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1067 Ty->getScope().resolve(), QualifiedNameComponents);
1068
1069 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001070 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001071
1072 if (ClosestSubprogram == nullptr)
1073 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1074 else if (ClosestSubprogram == CurrentSubprogram)
1075 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1076
1077 // TODO: What if the ClosestSubprogram is neither null or the current
1078 // subprogram? Currently, the UDT just gets dropped on the floor.
1079 //
1080 // The current behavior is not desirable. To get maximal fidelity, we would
1081 // need to perform all type translation before beginning emission of .debug$S
1082 // and then make LocalUDTs a member of FunctionInfo
1083}
1084
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001085TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001086 // Generic dispatch for lowering an unknown type.
1087 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001088 case dwarf::DW_TAG_array_type:
1089 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001090 case dwarf::DW_TAG_typedef:
1091 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001092 case dwarf::DW_TAG_base_type:
1093 return lowerTypeBasic(cast<DIBasicType>(Ty));
1094 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001095 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1096 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1097 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001098 case dwarf::DW_TAG_reference_type:
1099 case dwarf::DW_TAG_rvalue_reference_type:
1100 return lowerTypePointer(cast<DIDerivedType>(Ty));
1101 case dwarf::DW_TAG_ptr_to_member_type:
1102 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1103 case dwarf::DW_TAG_const_type:
1104 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001105 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001106 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001107 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001108 if (ClassTy) {
1109 // The member function type of a member function pointer has no
1110 // ThisAdjustment.
1111 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1112 /*ThisAdjustment=*/0);
1113 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001114 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001115 case dwarf::DW_TAG_enumeration_type:
1116 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001117 case dwarf::DW_TAG_class_type:
1118 case dwarf::DW_TAG_structure_type:
1119 return lowerTypeClass(cast<DICompositeType>(Ty));
1120 case dwarf::DW_TAG_union_type:
1121 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001122 default:
1123 // Use the null type index.
1124 return TypeIndex();
1125 }
1126}
1127
David Majnemerd065e232016-06-02 06:21:37 +00001128TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001129 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1130 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001131 StringRef TypeName = Ty->getName();
1132
Hans Wennborg4b63a982016-06-23 22:57:25 +00001133 addToUDTs(Ty, UnderlyingTypeIndex);
David Majnemer3128b102016-06-15 18:00:01 +00001134
David Majnemerd065e232016-06-02 06:21:37 +00001135 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001136 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001137 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001138 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001139 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001140 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001141
David Majnemerd065e232016-06-02 06:21:37 +00001142 return UnderlyingTypeIndex;
1143}
1144
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001145TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1146 DITypeRef ElementTypeRef = Ty->getBaseType();
1147 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1148 // IndexType is size_t, which depends on the bitness of the target.
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001149 TypeIndex IndexType = Asm->TM.getPointerSize() == 8
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001150 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1151 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001152
1153 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1154
Amjad Aboudacee5682016-07-12 12:06:34 +00001155 // Add subranges to array type.
1156 DINodeArray Elements = Ty->getElements();
1157 for (int i = Elements.size() - 1; i >= 0; --i) {
1158 const DINode *Element = Elements[i];
1159 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1160
1161 const DISubrange *Subrange = cast<DISubrange>(Element);
1162 assert(Subrange->getLowerBound() == 0 &&
1163 "codeview doesn't support subranges with lower bounds");
1164 int64_t Count = Subrange->getCount();
1165
1166 // Variable Length Array (VLA) has Count equal to '-1'.
1167 // Replace with Count '1', assume it is the minimum VLA length.
1168 // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
Reid Kleckner6b78e162017-03-24 23:28:42 +00001169 if (Count == -1)
Amjad Aboudacee5682016-07-12 12:06:34 +00001170 Count = 1;
Amjad Aboudacee5682016-07-12 12:06:34 +00001171
Amjad Aboudacee5682016-07-12 12:06:34 +00001172 // Update the element size and element type index for subsequent subranges.
1173 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001174
1175 // If this is the outermost array, use the size from the array. It will be
Reid Kleckner6b78e162017-03-24 23:28:42 +00001176 // more accurate if we had a VLA or an incomplete element type size.
Reid Kleckner10762882016-09-09 17:29:36 +00001177 uint64_t ArraySize =
1178 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1179
1180 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001181 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1182 ElementTypeIndex = TypeTable.writeKnownType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001183 }
1184
Amjad Aboudacee5682016-07-12 12:06:34 +00001185 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001186}
1187
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001188TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1189 TypeIndex Index;
1190 dwarf::TypeKind Kind;
1191 uint32_t ByteSize;
1192
1193 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001194 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001195
1196 SimpleTypeKind STK = SimpleTypeKind::None;
1197 switch (Kind) {
1198 case dwarf::DW_ATE_address:
1199 // FIXME: Translate
1200 break;
1201 case dwarf::DW_ATE_boolean:
1202 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001203 case 1: STK = SimpleTypeKind::Boolean8; break;
1204 case 2: STK = SimpleTypeKind::Boolean16; break;
1205 case 4: STK = SimpleTypeKind::Boolean32; break;
1206 case 8: STK = SimpleTypeKind::Boolean64; break;
1207 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001208 }
1209 break;
1210 case dwarf::DW_ATE_complex_float:
1211 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001212 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001213 case 4: STK = SimpleTypeKind::Complex32; break;
1214 case 8: STK = SimpleTypeKind::Complex64; break;
1215 case 10: STK = SimpleTypeKind::Complex80; break;
1216 case 16: STK = SimpleTypeKind::Complex128; break;
1217 }
1218 break;
1219 case dwarf::DW_ATE_float:
1220 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001221 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001222 case 4: STK = SimpleTypeKind::Float32; break;
1223 case 6: STK = SimpleTypeKind::Float48; break;
1224 case 8: STK = SimpleTypeKind::Float64; break;
1225 case 10: STK = SimpleTypeKind::Float80; break;
1226 case 16: STK = SimpleTypeKind::Float128; break;
1227 }
1228 break;
1229 case dwarf::DW_ATE_signed:
1230 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001231 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1232 case 2: STK = SimpleTypeKind::Int16Short; break;
1233 case 4: STK = SimpleTypeKind::Int32; break;
1234 case 8: STK = SimpleTypeKind::Int64Quad; break;
1235 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001236 }
1237 break;
1238 case dwarf::DW_ATE_unsigned:
1239 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001240 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1241 case 2: STK = SimpleTypeKind::UInt16Short; break;
1242 case 4: STK = SimpleTypeKind::UInt32; break;
1243 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1244 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001245 }
1246 break;
1247 case dwarf::DW_ATE_UTF:
1248 switch (ByteSize) {
1249 case 2: STK = SimpleTypeKind::Character16; break;
1250 case 4: STK = SimpleTypeKind::Character32; break;
1251 }
1252 break;
1253 case dwarf::DW_ATE_signed_char:
1254 if (ByteSize == 1)
1255 STK = SimpleTypeKind::SignedCharacter;
1256 break;
1257 case dwarf::DW_ATE_unsigned_char:
1258 if (ByteSize == 1)
1259 STK = SimpleTypeKind::UnsignedCharacter;
1260 break;
1261 default:
1262 break;
1263 }
1264
1265 // Apply some fixups based on the source-level type name.
1266 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1267 STK = SimpleTypeKind::Int32Long;
1268 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1269 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001270 if (STK == SimpleTypeKind::UInt16Short &&
1271 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001272 STK = SimpleTypeKind::WideCharacter;
1273 if ((STK == SimpleTypeKind::SignedCharacter ||
1274 STK == SimpleTypeKind::UnsignedCharacter) &&
1275 Ty->getName() == "char")
1276 STK = SimpleTypeKind::NarrowCharacter;
1277
1278 return TypeIndex(STK);
1279}
1280
1281TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1282 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1283
1284 // Pointers to simple types can use SimpleTypeMode, rather than having a
1285 // dedicated pointer type record.
1286 if (PointeeTI.isSimple() &&
1287 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1288 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1289 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1290 ? SimpleTypeMode::NearPointer64
1291 : SimpleTypeMode::NearPointer32;
1292 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1293 }
1294
1295 PointerKind PK =
1296 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1297 PointerMode PM = PointerMode::Pointer;
1298 switch (Ty->getTag()) {
1299 default: llvm_unreachable("not a pointer tag type");
1300 case dwarf::DW_TAG_pointer_type:
1301 PM = PointerMode::Pointer;
1302 break;
1303 case dwarf::DW_TAG_reference_type:
1304 PM = PointerMode::LValueReference;
1305 break;
1306 case dwarf::DW_TAG_rvalue_reference_type:
1307 PM = PointerMode::RValueReference;
1308 break;
1309 }
1310 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1311 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1312 // do.
1313 PointerOptions PO = PointerOptions::None;
1314 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001315 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001316}
1317
Reid Kleckner6fa15462016-06-17 22:14:39 +00001318static PointerToMemberRepresentation
1319translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1320 // SizeInBytes being zero generally implies that the member pointer type was
1321 // incomplete, which can happen if it is part of a function prototype. In this
1322 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001323 if (IsPMF) {
1324 switch (Flags & DINode::FlagPtrToMemberRep) {
1325 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001326 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1327 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001328 case DINode::FlagSingleInheritance:
1329 return PointerToMemberRepresentation::SingleInheritanceFunction;
1330 case DINode::FlagMultipleInheritance:
1331 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1332 case DINode::FlagVirtualInheritance:
1333 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1334 }
1335 } else {
1336 switch (Flags & DINode::FlagPtrToMemberRep) {
1337 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001338 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1339 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001340 case DINode::FlagSingleInheritance:
1341 return PointerToMemberRepresentation::SingleInheritanceData;
1342 case DINode::FlagMultipleInheritance:
1343 return PointerToMemberRepresentation::MultipleInheritanceData;
1344 case DINode::FlagVirtualInheritance:
1345 return PointerToMemberRepresentation::VirtualInheritanceData;
1346 }
1347 }
1348 llvm_unreachable("invalid ptr to member representation");
1349}
1350
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001351TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1352 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1353 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001354 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001355 PointerKind PK = Asm->TM.getPointerSize() == 8 ? PointerKind::Near64
1356 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001357 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1358 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1359 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001360 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001361 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1362 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1363 MemberPointerInfo MPI(
1364 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001365 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001366 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001367}
1368
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001369/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1370/// have a translation, use the NearC convention.
1371static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1372 switch (DwarfCC) {
1373 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1374 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1375 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1376 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1377 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1378 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1379 }
1380 return CallingConvention::NearC;
1381}
1382
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001383TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1384 ModifierOptions Mods = ModifierOptions::None;
1385 bool IsModifier = true;
1386 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001387 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001388 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001389 switch (BaseTy->getTag()) {
1390 case dwarf::DW_TAG_const_type:
1391 Mods |= ModifierOptions::Const;
1392 break;
1393 case dwarf::DW_TAG_volatile_type:
1394 Mods |= ModifierOptions::Volatile;
1395 break;
1396 default:
1397 IsModifier = false;
1398 break;
1399 }
1400 if (IsModifier)
1401 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1402 }
1403 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001404 ModifierRecord MR(ModifiedTI, Mods);
1405 return TypeTable.writeKnownType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001406}
1407
David Majnemer75c3ebf2016-06-02 17:13:53 +00001408TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1409 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1410 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1411 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1412
1413 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1414 ArrayRef<TypeIndex> ArgTypeIndices = None;
1415 if (!ReturnAndArgTypeIndices.empty()) {
1416 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1417 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1418 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1419 }
1420
1421 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001422 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001423
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001424 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1425
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001426 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1427 ArgTypeIndices.size(), ArgListIndex);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001428 return TypeTable.writeKnownType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001429}
1430
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001431TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001432 const DIType *ClassTy,
1433 int ThisAdjustment) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001434 // Lower the containing class type.
1435 TypeIndex ClassType = getTypeIndex(ClassTy);
1436
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001437 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1438 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1439 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1440
1441 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1442 ArrayRef<TypeIndex> ArgTypeIndices = None;
1443 if (!ReturnAndArgTypeIndices.empty()) {
1444 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1445 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1446 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1447 }
1448 TypeIndex ThisTypeIndex = TypeIndex::Void();
1449 if (!ArgTypeIndices.empty()) {
1450 ThisTypeIndex = ArgTypeIndices.front();
1451 ArgTypeIndices = ArgTypeIndices.drop_front();
1452 }
1453
1454 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001455 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001456
1457 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1458
1459 // TODO: Need to use the correct values for:
1460 // FunctionOptions
1461 // ThisPointerAdjustment.
Zachary Turner4efa0a42016-11-08 22:24:53 +00001462 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1463 FunctionOptions::None, ArgTypeIndices.size(),
1464 ArgListIndex, ThisAdjustment);
1465 TypeIndex TI = TypeTable.writeKnownType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001466
1467 return TI;
1468}
1469
Reid Kleckner9dac4732016-08-31 15:59:30 +00001470TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001471 unsigned VSlotCount =
1472 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
Reid Kleckner9dac4732016-08-31 15:59:30 +00001473 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001474
1475 VFTableShapeRecord VFTSR(Slots);
1476 return TypeTable.writeKnownType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001477}
1478
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001479static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1480 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001481 case DINode::FlagPrivate: return MemberAccess::Private;
1482 case DINode::FlagPublic: return MemberAccess::Public;
1483 case DINode::FlagProtected: return MemberAccess::Protected;
1484 case 0:
1485 // If there was no explicit access control, provide the default for the tag.
1486 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1487 : MemberAccess::Public;
1488 }
1489 llvm_unreachable("access flags are exclusive");
1490}
1491
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001492static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1493 if (SP->isArtificial())
1494 return MethodOptions::CompilerGenerated;
1495
1496 // FIXME: Handle other MethodOptions.
1497
1498 return MethodOptions::None;
1499}
1500
1501static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1502 bool Introduced) {
1503 switch (SP->getVirtuality()) {
1504 case dwarf::DW_VIRTUALITY_none:
1505 break;
1506 case dwarf::DW_VIRTUALITY_virtual:
1507 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1508 case dwarf::DW_VIRTUALITY_pure_virtual:
1509 return Introduced ? MethodKind::PureIntroducingVirtual
1510 : MethodKind::PureVirtual;
1511 default:
1512 llvm_unreachable("unhandled virtuality case");
1513 }
1514
1515 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1516
1517 return MethodKind::Vanilla;
1518}
1519
Reid Klecknera8d57402016-06-03 15:58:20 +00001520static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1521 switch (Ty->getTag()) {
1522 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1523 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1524 }
1525 llvm_unreachable("unexpected tag");
1526}
1527
Reid Klecknere092dad2016-07-02 00:11:07 +00001528/// Return ClassOptions that should be present on both the forward declaration
1529/// and the defintion of a tag type.
1530static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1531 ClassOptions CO = ClassOptions::None;
1532
1533 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001534 // appear to give every type a linkage name, which may be problematic for us.
1535 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001536 if (!Ty->getIdentifier().empty())
1537 CO |= ClassOptions::HasUniqueName;
1538
1539 // Put the Nested flag on a type if it appears immediately inside a tag type.
1540 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1541 // here. That flag is only set on definitions, and not forward declarations.
1542 const DIScope *ImmediateScope = Ty->getScope().resolve();
1543 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1544 CO |= ClassOptions::Nested;
1545
1546 // Put the Scoped flag on function-local types.
1547 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1548 Scope = Scope->getScope().resolve()) {
1549 if (isa<DISubprogram>(Scope)) {
1550 CO |= ClassOptions::Scoped;
1551 break;
1552 }
1553 }
1554
1555 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001556}
1557
David Majnemer979cb882016-06-16 21:32:16 +00001558TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001559 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001560 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001561 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001562
David Majnemerda9548f2016-06-17 16:13:21 +00001563 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001564 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001565 } else {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001566 FieldListRecordBuilder FLRB(TypeTable);
1567
1568 FLRB.begin();
David Majnemerda9548f2016-06-17 16:13:21 +00001569 for (const DINode *Element : Ty->getElements()) {
1570 // We assume that the frontend provides all members in source declaration
1571 // order, which is what MSVC does.
1572 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001573 EnumeratorRecord ER(MemberAccess::Public,
1574 APSInt::getUnsigned(Enumerator->getValue()),
1575 Enumerator->getName());
1576 FLRB.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00001577 EnumeratorCount++;
1578 }
1579 }
Zachary Turner4efa0a42016-11-08 22:24:53 +00001580 FTI = FLRB.end();
David Majnemerda9548f2016-06-17 16:13:21 +00001581 }
David Majnemer979cb882016-06-16 21:32:16 +00001582
David Majnemer6bdc24e2016-07-01 23:12:45 +00001583 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001584
Zachary Turner4efa0a42016-11-08 22:24:53 +00001585 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1586 getTypeIndex(Ty->getBaseType()));
1587 return TypeTable.writeKnownType(ER);
David Majnemer979cb882016-06-16 21:32:16 +00001588}
1589
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001590//===----------------------------------------------------------------------===//
1591// ClassInfo
1592//===----------------------------------------------------------------------===//
1593
1594struct llvm::ClassInfo {
1595 struct MemberInfo {
1596 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001597 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001598 };
1599 // [MemberInfo]
1600 typedef std::vector<MemberInfo> MemberList;
1601
Reid Kleckner156a7232016-06-22 18:31:14 +00001602 typedef TinyPtrVector<const DISubprogram *> MethodsList;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001603 // MethodName -> MethodsList
1604 typedef MapVector<MDString *, MethodsList> MethodsMap;
1605
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001606 /// Base classes.
1607 std::vector<const DIDerivedType *> Inheritance;
1608
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001609 /// Direct members.
1610 MemberList Members;
1611 // Direct overloaded methods gathered by name.
1612 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001613
Reid Kleckner9dac4732016-08-31 15:59:30 +00001614 TypeIndex VShapeTI;
1615
Adrian McCarthy820ca542016-07-06 19:49:51 +00001616 std::vector<const DICompositeType *> NestedClasses;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001617};
1618
1619void CodeViewDebug::clear() {
1620 assert(CurFn == nullptr);
1621 FileIdMap.clear();
1622 FnDebugInfo.clear();
1623 FileToFilepathMap.clear();
1624 LocalUDTs.clear();
1625 GlobalUDTs.clear();
1626 TypeIndices.clear();
1627 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001628}
1629
1630void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1631 const DIDerivedType *DDTy) {
1632 if (!DDTy->getName().empty()) {
1633 Info.Members.push_back({DDTy, 0});
1634 return;
1635 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001636 // An unnamed member must represent a nested struct or union. Add all the
1637 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001638 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00001639 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001640 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001641 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001642 ClassInfo NestedInfo = collectClassInfo(DCTy);
1643 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001644 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001645 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001646}
1647
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001648ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1649 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001650 // Add elements to structure type.
1651 DINodeArray Elements = Ty->getElements();
1652 for (auto *Element : Elements) {
1653 // We assume that the frontend provides all members in source declaration
1654 // order, which is what MSVC does.
1655 if (!Element)
1656 continue;
1657 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001658 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001659 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001660 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001661 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001662 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1663 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001664 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1665 DDTy->getName() == "__vtbl_ptr_type") {
1666 Info.VShapeTI = getTypeIndex(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001667 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1668 // Ignore friend members. It appears that MSVC emitted info about
1669 // friends in the past, but modern versions do not.
1670 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001671 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1672 Info.NestedClasses.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001673 }
1674 // Skip other unrecognized kinds of elements.
1675 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001676 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001677}
1678
Reid Klecknera8d57402016-06-03 15:58:20 +00001679TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1680 // First, construct the forward decl. Don't look into Ty to compute the
1681 // forward decl options, since it might not be available in all TUs.
1682 TypeRecordKind Kind = getRecordKind(Ty);
1683 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001684 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001685 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001686 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
1687 FullName, Ty->getIdentifier());
1688 TypeIndex FwdDeclTI = TypeTable.writeKnownType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001689 if (!Ty->isForwardDecl())
1690 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001691 return FwdDeclTI;
1692}
1693
1694TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1695 // Construct the field list and complete type record.
1696 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00001697 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001698 TypeIndex FieldTI;
1699 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001700 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001701 bool ContainsNestedClass;
1702 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1703 lowerRecordFieldList(Ty);
1704
1705 if (ContainsNestedClass)
1706 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00001707
David Majnemer6bdc24e2016-07-01 23:12:45 +00001708 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001709
Reid Klecknera8d57402016-06-03 15:58:20 +00001710 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001711
Zachary Turner4efa0a42016-11-08 22:24:53 +00001712 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
1713 SizeInBytes, FullName, Ty->getIdentifier());
1714 TypeIndex ClassTI = TypeTable.writeKnownType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001715
Saleem Abdulrasool87f03382017-05-03 21:39:01 +00001716 if (const auto *File = Ty->getFile()) {
1717 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
1718 TypeIndex SIDI = TypeTable.writeKnownType(SIDR);
1719 UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine());
1720 TypeTable.writeKnownType(USLR);
1721 }
Hans Wennborg9a519a02016-06-22 21:22:13 +00001722
Hans Wennborg4b63a982016-06-23 22:57:25 +00001723 addToUDTs(Ty, ClassTI);
1724
Hans Wennborg9a519a02016-06-22 21:22:13 +00001725 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001726}
1727
1728TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1729 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001730 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001731 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001732 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
1733 TypeIndex FwdDeclTI = TypeTable.writeKnownType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001734 if (!Ty->isForwardDecl())
1735 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001736 return FwdDeclTI;
1737}
1738
1739TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00001740 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001741 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001742 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001743 bool ContainsNestedClass;
1744 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1745 lowerRecordFieldList(Ty);
1746
1747 if (ContainsNestedClass)
1748 CO |= ClassOptions::ContainsNestedClass;
1749
Reid Klecknera8d57402016-06-03 15:58:20 +00001750 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00001751 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001752
Zachary Turner4efa0a42016-11-08 22:24:53 +00001753 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
1754 Ty->getIdentifier());
1755 TypeIndex UnionTI = TypeTable.writeKnownType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001756
Zachary Turner4efa0a42016-11-08 22:24:53 +00001757 StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1758 TypeIndex SIRI = TypeTable.writeKnownType(SIR);
1759 UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine());
1760 TypeTable.writeKnownType(USLR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001761
Hans Wennborg4b63a982016-06-23 22:57:25 +00001762 addToUDTs(Ty, UnionTI);
1763
Hans Wennborg9a519a02016-06-22 21:22:13 +00001764 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001765}
1766
Adrian McCarthy820ca542016-07-06 19:49:51 +00001767std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00001768CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1769 // Manually count members. MSVC appears to count everything that generates a
1770 // field list record. Each individual overload in a method overload group
1771 // contributes to this count, even though the overload group is a single field
1772 // list record.
1773 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001774 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001775 FieldListRecordBuilder FLBR(TypeTable);
1776 FLBR.begin();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001777
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001778 // Create base classes.
1779 for (const DIDerivedType *I : Info.Inheritance) {
1780 if (I->getFlags() & DINode::FlagVirtual) {
1781 // Virtual base.
1782 // FIXME: Emit VBPtrOffset when the frontend provides it.
1783 unsigned VBPtrOffset = 0;
1784 // FIXME: Despite the accessor name, the offset is really in bytes.
1785 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00001786 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
1787 ? TypeRecordKind::IndirectVirtualBaseClass
1788 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001789 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00001790 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001791 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00001792 VBTableIndex);
1793
1794 FLBR.writeMemberType(VBCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001795 } else {
1796 assert(I->getOffsetInBits() % 8 == 0 &&
1797 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00001798 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
1799 getTypeIndex(I->getBaseType()),
1800 I->getOffsetInBits() / 8);
1801 FLBR.writeMemberType(BCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001802 }
1803 }
1804
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001805 // Create members.
1806 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1807 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1808 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00001809 StringRef MemberName = Member->getName();
1810 MemberAccess Access =
1811 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001812
1813 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001814 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
1815 FLBR.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001816 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001817 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001818 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001819
Reid Kleckner9dac4732016-08-31 15:59:30 +00001820 // Virtual function pointer member.
1821 if ((Member->getFlags() & DINode::FlagArtificial) &&
1822 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001823 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
1824 FLBR.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001825 MemberCount++;
1826 continue;
1827 }
1828
David Majnemer9319cbc2016-06-30 03:00:20 +00001829 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00001830 uint64_t MemberOffsetInBits =
1831 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001832 if (Member->isBitField()) {
1833 uint64_t StartBitOffset = MemberOffsetInBits;
1834 if (const auto *CI =
1835 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00001836 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001837 }
1838 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001839 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
1840 StartBitOffset);
1841 MemberBaseType = TypeTable.writeKnownType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00001842 }
1843 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001844 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
1845 MemberName);
1846 FLBR.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001847 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001848 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001849
1850 // Create methods
1851 for (auto &MethodItr : Info.Methods) {
1852 StringRef Name = MethodItr.first->getString();
1853
1854 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00001855 for (const DISubprogram *SP : MethodItr.second) {
1856 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1857 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001858
1859 unsigned VFTableOffset = -1;
1860 if (Introduced)
1861 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1862
Zachary Turner7251ede2016-11-02 17:05:19 +00001863 Methods.push_back(OneMethodRecord(
1864 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
1865 translateMethodKindFlags(SP, Introduced),
1866 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001867 MemberCount++;
1868 }
1869 assert(Methods.size() > 0 && "Empty methods map entry");
1870 if (Methods.size() == 1)
Zachary Turner4efa0a42016-11-08 22:24:53 +00001871 FLBR.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001872 else {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001873 MethodOverloadListRecord MOLR(Methods);
1874 TypeIndex MethodList = TypeTable.writeKnownType(MOLR);
1875 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
1876 FLBR.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001877 }
1878 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001879
1880 // Create nested classes.
1881 for (const DICompositeType *Nested : Info.NestedClasses) {
1882 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner4efa0a42016-11-08 22:24:53 +00001883 FLBR.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00001884 MemberCount++;
1885 }
1886
Zachary Turner4efa0a42016-11-08 22:24:53 +00001887 TypeIndex FieldTI = FLBR.end();
Reid Kleckner9dac4732016-08-31 15:59:30 +00001888 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Adrian McCarthy820ca542016-07-06 19:49:51 +00001889 !Info.NestedClasses.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00001890}
1891
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001892TypeIndex CodeViewDebug::getVBPTypeIndex() {
1893 if (!VBPType.getIndex()) {
1894 // Make a 'const int *' type.
1895 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001896 TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001897
1898 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1899 : PointerKind::Near32;
1900 PointerMode PM = PointerMode::Pointer;
1901 PointerOptions PO = PointerOptions::None;
1902 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1903
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001904 VBPType = TypeTable.writeKnownType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001905 }
1906
1907 return VBPType;
1908}
1909
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001910TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001911 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001912 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001913
1914 // The null DIType is the void type. Don't try to hash it.
1915 if (!Ty)
1916 return TypeIndex::Void();
1917
Reid Klecknera8d57402016-06-03 15:58:20 +00001918 // Check if we've already translated this type. Don't try to do a
1919 // get-or-create style insertion that caches the hash lookup across the
1920 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001921 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001922 if (I != TypeIndices.end())
1923 return I->second;
1924
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001925 TypeLoweringScope S(*this);
1926 TypeIndex TI = lowerType(Ty, ClassTy);
1927 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00001928}
1929
1930TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1931 const DIType *Ty = TypeRef.resolve();
1932
1933 // The null DIType is the void type. Don't try to hash it.
1934 if (!Ty)
1935 return TypeIndex::Void();
1936
1937 // If this is a non-record type, the complete type index is the same as the
1938 // normal type index. Just call getTypeIndex.
1939 switch (Ty->getTag()) {
1940 case dwarf::DW_TAG_class_type:
1941 case dwarf::DW_TAG_structure_type:
1942 case dwarf::DW_TAG_union_type:
1943 break;
1944 default:
1945 return getTypeIndex(Ty);
1946 }
1947
1948 // Check if we've already translated the complete record type. Lowering a
1949 // complete type should never trigger lowering another complete type, so we
1950 // can reuse the hash table lookup result.
1951 const auto *CTy = cast<DICompositeType>(Ty);
1952 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1953 if (!InsertResult.second)
1954 return InsertResult.first->second;
1955
Reid Kleckner643dd832016-06-22 17:15:28 +00001956 TypeLoweringScope S(*this);
1957
Reid Klecknera8d57402016-06-03 15:58:20 +00001958 // Make sure the forward declaration is emitted first. It's unclear if this
1959 // is necessary, but MSVC does it, and we should follow suit until we can show
1960 // otherwise.
1961 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1962
1963 // Just use the forward decl if we don't have complete type info. This might
1964 // happen if the frontend is using modules and expects the complete definition
1965 // to be emitted elsewhere.
1966 if (CTy->isForwardDecl())
1967 return FwdDeclTI;
1968
1969 TypeIndex TI;
1970 switch (CTy->getTag()) {
1971 case dwarf::DW_TAG_class_type:
1972 case dwarf::DW_TAG_structure_type:
1973 TI = lowerCompleteTypeClass(CTy);
1974 break;
1975 case dwarf::DW_TAG_union_type:
1976 TI = lowerCompleteTypeUnion(CTy);
1977 break;
1978 default:
1979 llvm_unreachable("not a record");
1980 }
1981
1982 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001983 return TI;
1984}
1985
Reid Kleckner643dd832016-06-22 17:15:28 +00001986/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00001987/// and do this until fixpoint, as each complete record type typically
1988/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00001989/// many other record types.
1990void CodeViewDebug::emitDeferredCompleteTypes() {
1991 SmallVector<const DICompositeType *, 4> TypesToEmit;
1992 while (!DeferredCompleteTypes.empty()) {
1993 std::swap(DeferredCompleteTypes, TypesToEmit);
1994 for (const DICompositeType *RecordTy : TypesToEmit)
1995 getCompleteTypeIndex(RecordTy);
1996 TypesToEmit.clear();
1997 }
1998}
1999
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002000void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
2001 // Get the sorted list of parameters and emit them first.
2002 SmallVector<const LocalVariable *, 6> Params;
2003 for (const LocalVariable &L : Locals)
2004 if (L.DIVar->isParameter())
2005 Params.push_back(&L);
2006 std::sort(Params.begin(), Params.end(),
2007 [](const LocalVariable *L, const LocalVariable *R) {
2008 return L->DIVar->getArg() < R->DIVar->getArg();
2009 });
2010 for (const LocalVariable *L : Params)
2011 emitLocalVariable(*L);
2012
2013 // Next emit all non-parameters in the order that we found them.
2014 for (const LocalVariable &L : Locals)
2015 if (!L.DIVar->isParameter())
2016 emitLocalVariable(L);
2017}
2018
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002019void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2020 // LocalSym record, see SymbolRecord.h for more info.
2021 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2022 *LocalEnd = MMI->getContext().createTempSymbol();
2023 OS.AddComment("Record length");
2024 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2025 OS.EmitLabel(LocalBegin);
2026
2027 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00002028 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002029
Zachary Turner63a28462016-05-17 23:50:21 +00002030 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002031 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002032 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002033 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002034 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002035
2036 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00002037 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002038 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002039 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002040 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002041 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002042 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002043 OS.EmitLabel(LocalEnd);
2044
Reid Kleckner876330d2016-02-12 21:48:30 +00002045 // Calculate the on disk prefix of the appropriate def range record. The
2046 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2047 // should be big enough to hold all forms without memory allocation.
2048 SmallString<20> BytePrefix;
2049 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2050 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002051 if (DefRange.InMemory) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002052 uint16_t RegRelFlags = 0;
2053 if (DefRange.IsSubfield) {
2054 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2055 (DefRange.StructOffset
2056 << DefRangeRegisterRelSym::OffsetInParentShift);
2057 }
Zachary Turner46225b12016-12-16 22:48:14 +00002058 DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
2059 Sym.Hdr.Register = DefRange.CVRegister;
2060 Sym.Hdr.Flags = RegRelFlags;
2061 Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +00002062 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00002063 BytePrefix +=
2064 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00002065 BytePrefix +=
Zachary Turner46225b12016-12-16 22:48:14 +00002066 StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
Reid Kleckner876330d2016-02-12 21:48:30 +00002067 } else {
2068 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002069 if (DefRange.IsSubfield) {
2070 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002071 DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2072 Sym.Hdr.Register = DefRange.CVRegister;
2073 Sym.Hdr.MayHaveNoName = 0;
2074 Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2075
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002076 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2077 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2078 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002079 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2080 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002081 } else {
2082 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002083 DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2084 Sym.Hdr.Register = DefRange.CVRegister;
2085 Sym.Hdr.MayHaveNoName = 0;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002086 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2087 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2088 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002089 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2090 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002091 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002092 }
2093 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2094 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002095}
2096
David Blaikieb2fbb4b2017-02-16 18:48:33 +00002097void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002098 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00002099 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002100 assert(CurFn == &FnDebugInfo[GV]);
2101
Pete Cooperadebb932016-03-11 02:14:16 +00002102 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002103
Reid Kleckner2214ed82016-01-29 00:49:42 +00002104 // Don't emit anything if we don't have any line tables.
2105 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002106 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002107 CurFn = nullptr;
2108 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002109 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002110
2111 CurFn->End = Asm->getFunctionEnd();
2112
Craig Topper353eda42014-04-24 06:44:33 +00002113 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002114}
2115
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002116void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002117 DebugHandlerBase::beginInstruction(MI);
2118
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002119 // Ignore DBG_VALUE locations and function prologue.
David Majnemer67f684e2016-07-28 05:03:22 +00002120 if (!Asm || !CurFn || MI->isDebugValue() ||
2121 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002122 return;
2123 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00002124 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002125 return;
2126 maybeRecordLocation(DL, Asm->MF);
2127}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002128
Zachary Turner67c56012017-04-27 16:11:19 +00002129MCSymbol *CodeViewDebug::beginCVSubsection(ModuleDebugFragmentKind Kind) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002130 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2131 *EndLabel = MMI->getContext().createTempSymbol();
2132 OS.EmitIntValue(unsigned(Kind), 4);
2133 OS.AddComment("Subsection size");
2134 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2135 OS.EmitLabel(BeginLabel);
2136 return EndLabel;
2137}
2138
2139void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2140 OS.EmitLabel(EndLabel);
2141 // Every subsection must be aligned to a 4-byte boundary.
2142 OS.EmitValueToAlignment(4);
2143}
2144
David Majnemer3128b102016-06-15 18:00:01 +00002145void CodeViewDebug::emitDebugInfoForUDTs(
2146 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
2147 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
2148 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2149 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2150 OS.AddComment("Record length");
2151 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2152 OS.EmitLabel(UDTRecordBegin);
2153
2154 OS.AddComment("Record kind: S_UDT");
2155 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2156
2157 OS.AddComment("Type");
2158 OS.EmitIntValue(UDT.second.getIndex(), 4);
2159
2160 emitNullTerminatedSymbolName(OS, UDT.first);
2161 OS.EmitLabel(UDTRecordEnd);
2162 }
2163}
2164
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002165void CodeViewDebug::emitDebugInfoForGlobals() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002166 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2167 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002168 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002169 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2170 GV.getDebugInfo(GVEs);
2171 for (const auto *GVE : GVEs)
2172 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002173 }
2174
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002175 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2176 for (const MDNode *Node : CUs->operands()) {
2177 const auto *CU = cast<DICompileUnit>(Node);
2178
2179 // First, emit all globals that are not in a comdat in a single symbol
2180 // substream. MSVC doesn't like it if the substream is empty, so only open
2181 // it if we have at least one global to emit.
2182 switchToDebugSectionForSymbol(nullptr);
2183 MCSymbol *EndLabel = nullptr;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002184 for (const auto *GVE : CU->getGlobalVariables()) {
2185 if (const auto *GV = GlobalMap.lookup(GVE))
David Majnemer577be0f2016-06-15 00:19:52 +00002186 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002187 if (!EndLabel) {
2188 OS.AddComment("Symbol subsection for globals");
Zachary Turner67c56012017-04-27 16:11:19 +00002189 EndLabel = beginCVSubsection(ModuleDebugFragmentKind::Symbols);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002190 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002191 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2192 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002193 }
2194 }
2195 if (EndLabel)
2196 endCVSubsection(EndLabel);
2197
2198 // Second, emit each global that is in a comdat into its own .debug$S
2199 // section along with its own symbol substream.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002200 for (const auto *GVE : CU->getGlobalVariables()) {
2201 if (const auto *GV = GlobalMap.lookup(GVE)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002202 if (GV->hasComdat()) {
2203 MCSymbol *GVSym = Asm->getSymbol(GV);
2204 OS.AddComment("Symbol subsection for " +
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00002205 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002206 switchToDebugSectionForSymbol(GVSym);
Zachary Turner67c56012017-04-27 16:11:19 +00002207 EndLabel = beginCVSubsection(ModuleDebugFragmentKind::Symbols);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002208 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2209 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002210 endCVSubsection(EndLabel);
2211 }
2212 }
2213 }
2214 }
2215}
2216
Hans Wennborgb510b452016-06-23 16:33:53 +00002217void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2218 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2219 for (const MDNode *Node : CUs->operands()) {
2220 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2221 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2222 getTypeIndex(RT);
2223 // FIXME: Add to global/local DTU list.
2224 }
2225 }
2226 }
2227}
2228
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002229void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002230 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002231 MCSymbol *GVSym) {
2232 // DataSym record, see SymbolRecord.h for more info.
2233 // FIXME: Thread local data, etc
2234 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2235 *DataEnd = MMI->getContext().createTempSymbol();
2236 OS.AddComment("Record length");
2237 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2238 OS.EmitLabel(DataBegin);
David Majnemer7abd2692016-07-06 21:07:47 +00002239 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002240 if (GV->isThreadLocal()) {
2241 OS.AddComment("Record kind: S_LTHREAD32");
2242 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2243 } else {
2244 OS.AddComment("Record kind: S_LDATA32");
2245 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2246 }
David Majnemer7abd2692016-07-06 21:07:47 +00002247 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002248 if (GV->isThreadLocal()) {
2249 OS.AddComment("Record kind: S_GTHREAD32");
2250 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2251 } else {
2252 OS.AddComment("Record kind: S_GDATA32");
2253 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2254 }
David Majnemer7abd2692016-07-06 21:07:47 +00002255 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002256 OS.AddComment("Type");
2257 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2258 OS.AddComment("DataOffset");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00002259 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002260 OS.AddComment("Segment");
2261 OS.EmitCOFFSectionIndex(GVSym);
2262 OS.AddComment("Name");
2263 emitNullTerminatedSymbolName(OS, DIGV->getName());
2264 OS.EmitLabel(DataEnd);
2265}