blob: ec0f007371dcde03954b7bf4cbdc03c9e0f9708d [file] [log] [blame]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001//===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
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"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000015#include "llvm/ADT/APSInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/MapVector.h"
20#include "llvm/ADT/None.h"
21#include "llvm/ADT/Optional.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/StringRef.h"
Reid Kleckner156a7232016-06-22 18:31:14 +000026#include "llvm/ADT/TinyPtrVector.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000027#include "llvm/ADT/Triple.h"
28#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000029#include "llvm/BinaryFormat/COFF.h"
30#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000031#include "llvm/CodeGen/AsmPrinter.h"
32#include "llvm/CodeGen/LexicalScopes.h"
33#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineInstr.h"
35#include "llvm/CodeGen/MachineModuleInfo.h"
36#include "llvm/CodeGen/MachineOperand.h"
37#include "llvm/Config/llvm-config.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000038#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000039#include "llvm/DebugInfo/CodeView/CodeView.h"
Zachary Turner8c099fe2017-05-30 16:36:15 +000040#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000041#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000042#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000043#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000044#include "llvm/DebugInfo/CodeView/TypeIndex.h"
45#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000046#include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000047#include "llvm/IR/Constants.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000048#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/DebugInfoMetadata.h"
50#include "llvm/IR/DebugLoc.h"
51#include "llvm/IR/Function.h"
52#include "llvm/IR/GlobalValue.h"
53#include "llvm/IR/GlobalVariable.h"
54#include "llvm/IR/Metadata.h"
55#include "llvm/IR/Module.h"
Reid Kleckner46cb48c2016-07-27 16:03:57 +000056#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000057#include "llvm/MC/MCContext.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000058#include "llvm/MC/MCSectionCOFF.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000059#include "llvm/MC/MCStreamer.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000060#include "llvm/MC/MCSymbol.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000061#include "llvm/Support/BinaryByteStream.h"
62#include "llvm/Support/BinaryStreamReader.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000063#include "llvm/Support/Casting.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000064#include "llvm/Support/Compiler.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000065#include "llvm/Support/Endian.h"
66#include "llvm/Support/Error.h"
67#include "llvm/Support/ErrorHandling.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000068#include "llvm/Support/ScopedPrinter.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000069#include "llvm/Support/SMLoc.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000070#include "llvm/Target/TargetFrameLowering.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000071#include "llvm/Target/TargetLoweringObjectFile.h"
72#include "llvm/Target/TargetMachine.h"
Amjad Aboud76c9eb92016-06-18 10:25:07 +000073#include "llvm/Target/TargetRegisterInfo.h"
74#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000075#include <algorithm>
76#include <cassert>
77#include <cctype>
78#include <cstddef>
79#include <cstdint>
80#include <iterator>
81#include <limits>
82#include <string>
83#include <utility>
84#include <vector>
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000085
Reid Klecknerf9c275f2016-02-10 20:55:49 +000086using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000087using namespace llvm::codeview;
88
Reid Klecknerf9c275f2016-02-10 20:55:49 +000089CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
Eugene Zelenkofb69e662017-06-06 22:22:41 +000090 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +000091 // If module doesn't have named metadata anchors or COFF debug section
92 // is not available, skip any debug info related stuff.
93 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
94 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
95 Asm = nullptr;
96 return;
97 }
98
99 // Tell MMI that we have debug info.
100 MMI->setDebugInfoAvailability(true);
101}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000102
Reid Kleckner9533af42016-01-16 00:09:09 +0000103StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
104 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000105 if (!Filepath.empty())
106 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000107
Reid Kleckner9533af42016-01-16 00:09:09 +0000108 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
109
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000110 // Clang emits directory and relative filename info into the IR, but CodeView
111 // operates on full paths. We could change Clang to emit full paths too, but
112 // that would increase the IR size and probably not needed for other users.
113 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000114 if (Filename.find(':') == 1)
115 Filepath = Filename;
116 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000117 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000118
119 // Canonicalize the path. We have to do it textually because we may no longer
120 // have access the file in the filesystem.
121 // First, replace all slashes with backslashes.
122 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
123
124 // Remove all "\.\" with "\".
125 size_t Cursor = 0;
126 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
127 Filepath.erase(Cursor, 2);
128
129 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
130 // path should be well-formatted, e.g. start with a drive letter, etc.
131 Cursor = 0;
132 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
133 // Something's wrong if the path starts with "\..\", abort.
134 if (Cursor == 0)
135 break;
136
137 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
138 if (PrevSlash == std::string::npos)
139 // Something's wrong, abort.
140 break;
141
142 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
143 // The next ".." might be following the one we've just erased.
144 Cursor = PrevSlash;
145 }
146
147 // Remove all duplicate backslashes.
148 Cursor = 0;
149 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
150 Filepath.erase(Cursor, 1);
151
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000152 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000153}
154
Reid Kleckner2214ed82016-01-29 00:49:42 +0000155unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
156 unsigned NextId = FileIdMap.size() + 1;
157 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
158 if (Insertion.second) {
159 // We have to compute the full filepath and emit a .cv_file directive.
160 StringRef FullPath = getFullFilepath(F);
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000161 bool Success = OS.EmitCVFileDirective(NextId, FullPath);
162 (void)Success;
163 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000164 }
165 return Insertion.first->second;
166}
167
Reid Kleckner876330d2016-02-12 21:48:30 +0000168CodeViewDebug::InlineSite &
169CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
170 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000171 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
172 InlineSite *Site = &SiteInsertion.first->second;
173 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000174 unsigned ParentFuncId = CurFn->FuncId;
175 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
176 ParentFuncId =
177 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
178 .SiteFuncId;
179
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000180 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000181 OS.EmitCVInlineSiteIdDirective(
182 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
183 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000184 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000185 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000186 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000187 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000188 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000189}
190
David Majnemer6bdc24e2016-07-01 23:12:45 +0000191static StringRef getPrettyScopeName(const DIScope *Scope) {
192 StringRef ScopeName = Scope->getName();
193 if (!ScopeName.empty())
194 return ScopeName;
195
196 switch (Scope->getTag()) {
197 case dwarf::DW_TAG_enumeration_type:
198 case dwarf::DW_TAG_class_type:
199 case dwarf::DW_TAG_structure_type:
200 case dwarf::DW_TAG_union_type:
201 return "<unnamed-tag>";
202 case dwarf::DW_TAG_namespace:
203 return "`anonymous namespace'";
204 }
205
206 return StringRef();
207}
208
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000209static const DISubprogram *getQualifiedNameComponents(
210 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
211 const DISubprogram *ClosestSubprogram = nullptr;
212 while (Scope != nullptr) {
213 if (ClosestSubprogram == nullptr)
214 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000215 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000216 if (!ScopeName.empty())
217 QualifiedNameComponents.push_back(ScopeName);
218 Scope = Scope->getScope().resolve();
219 }
220 return ClosestSubprogram;
221}
222
223static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
224 StringRef TypeName) {
225 std::string FullyQualifiedName;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000226 for (StringRef QualifiedNameComponent :
227 llvm::reverse(QualifiedNameComponents)) {
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000228 FullyQualifiedName.append(QualifiedNameComponent);
229 FullyQualifiedName.append("::");
230 }
231 FullyQualifiedName.append(TypeName);
232 return FullyQualifiedName;
233}
234
235static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
236 SmallVector<StringRef, 5> QualifiedNameComponents;
237 getQualifiedNameComponents(Scope, QualifiedNameComponents);
238 return getQualifiedName(QualifiedNameComponents, Name);
239}
240
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000241struct CodeViewDebug::TypeLoweringScope {
242 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
243 ~TypeLoweringScope() {
244 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
245 // inner TypeLoweringScopes don't attempt to emit deferred types.
246 if (CVD.TypeEmissionLevel == 1)
247 CVD.emitDeferredCompleteTypes();
248 --CVD.TypeEmissionLevel;
249 }
250 CodeViewDebug &CVD;
251};
252
David Majnemer6bdc24e2016-07-01 23:12:45 +0000253static std::string getFullyQualifiedName(const DIScope *Ty) {
254 const DIScope *Scope = Ty->getScope().resolve();
255 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
256}
257
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000258TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
259 // No scope means global scope and that uses the zero index.
260 if (!Scope || isa<DIFile>(Scope))
261 return TypeIndex();
262
263 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
264
265 // Check if we've already translated this scope.
266 auto I = TypeIndices.find({Scope, nullptr});
267 if (I != TypeIndices.end())
268 return I->second;
269
270 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000271 std::string ScopeName = getFullyQualifiedName(Scope);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000272 StringIdRecord SID(TypeIndex(), ScopeName);
273 auto TI = TypeTable.writeKnownType(SID);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000274 return recordTypeIndexForDINode(Scope, TI);
275}
276
David Majnemer75c3ebf2016-06-02 17:13:53 +0000277TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000278 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000279
David Majnemer75c3ebf2016-06-02 17:13:53 +0000280 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000281 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000282 if (I != TypeIndices.end())
283 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000284
Reid Klecknerac945e22016-06-17 16:11:20 +0000285 // The display name includes function template arguments. Drop them to match
286 // MSVC.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000287 StringRef DisplayName = SP->getName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000288
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000289 const DIScope *Scope = SP->getScope().resolve();
290 TypeIndex TI;
291 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
292 // If the scope is a DICompositeType, then this must be a method. Member
293 // function types take some special handling, and require access to the
294 // subprogram.
295 TypeIndex ClassType = getTypeIndex(Class);
296 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
297 DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000298 TI = TypeTable.writeKnownType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000299 } else {
300 // Otherwise, this must be a free function.
301 TypeIndex ParentScope = getScopeIndex(Scope);
302 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000303 TI = TypeTable.writeKnownType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000304 }
305
306 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000307}
308
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000309TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
310 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000311 // Always use the method declaration as the key for the function type. The
312 // method declaration contains the this adjustment.
313 if (SP->getDeclaration())
314 SP = SP->getDeclaration();
315 assert(!SP->getDeclaration() && "should use declaration as key");
316
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000317 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
318 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000319 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000320 if (I != TypeIndices.end())
321 return I->second;
322
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000323 // Make sure complete type info for the class is emitted *after* the member
324 // function type, as the complete class type is likely to reference this
325 // member function type.
326 TypeLoweringScope S(*this);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000327 TypeIndex TI =
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000328 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000329 return recordTypeIndexForDINode(SP, TI, Class);
330}
331
Amjad Aboudacee5682016-07-12 12:06:34 +0000332TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
333 TypeIndex TI,
334 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000335 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000336 (void)InsertResult;
337 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000338 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000339}
340
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000341unsigned CodeViewDebug::getPointerSizeInBytes() {
342 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
343}
344
Reid Kleckner876330d2016-02-12 21:48:30 +0000345void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
346 const DILocation *InlinedAt) {
347 if (InlinedAt) {
348 // This variable was inlined. Associate it with the InlineSite.
349 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
350 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
351 Site.InlinedLocals.emplace_back(Var);
352 } else {
353 // This variable goes in the main ProcSym.
354 CurFn->Locals.emplace_back(Var);
355 }
356}
357
Reid Kleckner829365a2016-02-11 19:41:47 +0000358static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
359 const DILocation *Loc) {
360 auto B = Locs.begin(), E = Locs.end();
361 if (std::find(B, E, Loc) == E)
362 Locs.push_back(Loc);
363}
364
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000365void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000366 const MachineFunction *MF) {
367 // Skip this instruction if it has the same location as the previous one.
Reid Kleckner45a74622017-06-30 21:33:44 +0000368 if (!DL || DL == PrevInstLoc)
Reid Kleckner9533af42016-01-16 00:09:09 +0000369 return;
370
371 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000372 if (!Scope)
373 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000374
David Majnemerc3340db2016-01-13 01:05:23 +0000375 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000376 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
377 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
378 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000379 return;
380
Reid Kleckner2214ed82016-01-29 00:49:42 +0000381 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
382 if (CI.getStartColumn() != DL.getCol())
383 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000384
Reid Kleckner2214ed82016-01-29 00:49:42 +0000385 if (!CurFn->HaveLineInfo)
386 CurFn->HaveLineInfo = true;
387 unsigned FileId = 0;
Reid Kleckner45a74622017-06-30 21:33:44 +0000388 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
Reid Kleckner2214ed82016-01-29 00:49:42 +0000389 FileId = CurFn->LastFileId;
390 else
391 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
Reid Kleckner45a74622017-06-30 21:33:44 +0000392 PrevInstLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000393
394 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000395 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000396 const DILocation *Loc = DL.get();
397
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000398 // If this location was actually inlined from somewhere else, give it the ID
399 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000400 FuncId =
401 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000402
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000403 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000404 bool FirstLoc = true;
405 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000406 InlineSite &Site =
407 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000408 if (!FirstLoc)
409 addLocIfNotPresent(Site.ChildSites, Loc);
410 FirstLoc = false;
411 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000412 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000413 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000414 }
415
Reid Klecknerdac21b42016-02-03 21:15:48 +0000416 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000417 /*PrologueEnd=*/false, /*IsStmt=*/false,
418 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000419}
420
Reid Kleckner5d122f82016-05-25 23:16:12 +0000421void CodeViewDebug::emitCodeViewMagicVersion() {
422 OS.EmitValueToAlignment(4);
423 OS.AddComment("Debug section magic");
424 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
425}
426
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000427void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000428 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000429 return;
430
431 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000432
433 // The COFF .debug$S section consists of several subsections, each starting
434 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
435 // of the payload followed by the payload itself. The subsections are 4-byte
436 // aligned.
437
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000438 // Use the generic .debug$S section, and make a subsection for all the inlined
439 // subprograms.
440 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000441
Zachary Turner8c099fe2017-05-30 16:36:15 +0000442 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000443 emitCompilerInformation();
444 endCVSubsection(CompilerInfo);
445
Reid Kleckner5d122f82016-05-25 23:16:12 +0000446 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000447
Reid Kleckner2214ed82016-01-29 00:49:42 +0000448 // Emit per-function debug information.
449 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000450 if (!P.first->isDeclarationForLinker())
451 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000452
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000453 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000454 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000455 emitDebugInfoForGlobals();
456
Hans Wennborgb510b452016-06-23 16:33:53 +0000457 // Emit retained types.
458 emitDebugInfoForRetainedTypes();
459
Reid Kleckner5d122f82016-05-25 23:16:12 +0000460 // Switch back to the generic .debug$S section after potentially processing
461 // comdat symbol sections.
462 switchToDebugSectionForSymbol(nullptr);
463
David Majnemer3128b102016-06-15 18:00:01 +0000464 // Emit UDT records for any types used by global variables.
465 if (!GlobalUDTs.empty()) {
Zachary Turner8c099fe2017-05-30 16:36:15 +0000466 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
David Majnemer3128b102016-06-15 18:00:01 +0000467 emitDebugInfoForUDTs(GlobalUDTs);
468 endCVSubsection(SymbolsEnd);
469 }
470
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000471 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000472 OS.AddComment("File index to string table offset subsection");
473 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000474
475 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000476 OS.AddComment("String table");
477 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000478
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000479 // Emit type information last, so that any types we translate while emitting
480 // function info are included.
481 emitTypeInformation();
482
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000483 clear();
484}
485
David Majnemerb9456a52016-03-14 05:15:09 +0000486static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000487 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
488 // after a fixed length portion of the record. The fixed length portion should
489 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
490 // overall record size is less than the maximum allowed.
491 unsigned MaxFixedRecordLength = 0xF00;
492 SmallString<32> NullTerminatedString(
493 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000494 NullTerminatedString.push_back('\0');
495 OS.EmitBytes(NullTerminatedString);
496}
497
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000498void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000499 // Do nothing if we have no debug info or if no non-trivial types were emitted
500 // to TypeTable during codegen.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000501 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
Reid Klecknerfbd77872016-03-18 18:54:32 +0000502 if (!CU_Nodes)
503 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000504 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000505 return;
506
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000507 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000508 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000509 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000510
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000511 SmallString<8> CommentPrefix;
512 if (OS.isVerboseAsm()) {
513 CommentPrefix += '\t';
514 CommentPrefix += Asm->MAI->getCommentString();
515 CommentPrefix += ' ';
516 }
517
Zachary Turner526f4f22017-05-19 19:26:58 +0000518 TypeTableCollection Table(TypeTable.records());
519 Optional<TypeIndex> B = Table.getFirst();
520 while (B) {
521 // This will fail if the record data is invalid.
522 CVType Record = Table.getType(*B);
523
Zachary Turner4efa0a42016-11-08 22:24:53 +0000524 if (OS.isVerboseAsm()) {
525 // Emit a block comment describing the type record for readability.
526 SmallString<512> CommentBlock;
527 raw_svector_ostream CommentOS(CommentBlock);
528 ScopedPrinter SP(CommentOS);
529 SP.setPrefix(CommentPrefix);
Zachary Turner526f4f22017-05-19 19:26:58 +0000530 TypeDumpVisitor TDV(Table, &SP, false);
531
532 Error E = codeview::visitTypeRecord(Record, *B, TDV);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000533 if (E) {
534 logAllUnhandledErrors(std::move(E), errs(), "error: ");
535 llvm_unreachable("produced malformed type record");
536 }
537 // emitRawComment will insert its own tab and comment string before
538 // the first line, so strip off our first one. It also prints its own
539 // newline.
540 OS.emitRawComment(
541 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Zachary Turner4efa0a42016-11-08 22:24:53 +0000542 }
Zachary Turner526f4f22017-05-19 19:26:58 +0000543 OS.EmitBinaryData(Record.str_data());
544 B = Table.getNext(*B);
545 }
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000546}
547
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000548static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
549 switch (DWLang) {
550 case dwarf::DW_LANG_C:
551 case dwarf::DW_LANG_C89:
552 case dwarf::DW_LANG_C99:
553 case dwarf::DW_LANG_C11:
554 case dwarf::DW_LANG_ObjC:
555 return SourceLanguage::C;
556 case dwarf::DW_LANG_C_plus_plus:
557 case dwarf::DW_LANG_C_plus_plus_03:
558 case dwarf::DW_LANG_C_plus_plus_11:
559 case dwarf::DW_LANG_C_plus_plus_14:
560 return SourceLanguage::Cpp;
561 case dwarf::DW_LANG_Fortran77:
562 case dwarf::DW_LANG_Fortran90:
563 case dwarf::DW_LANG_Fortran03:
564 case dwarf::DW_LANG_Fortran08:
565 return SourceLanguage::Fortran;
566 case dwarf::DW_LANG_Pascal83:
567 return SourceLanguage::Pascal;
568 case dwarf::DW_LANG_Cobol74:
569 case dwarf::DW_LANG_Cobol85:
570 return SourceLanguage::Cobol;
571 case dwarf::DW_LANG_Java:
572 return SourceLanguage::Java;
573 default:
574 // There's no CodeView representation for this language, and CV doesn't
575 // have an "unknown" option for the language field, so we'll use MASM,
576 // as it's very low level.
577 return SourceLanguage::Masm;
578 }
579}
580
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000581namespace {
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000582struct Version {
583 int Part[4];
584};
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000585} // end anonymous namespace
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000586
587// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
588// the version number.
589static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000590 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000591 int N = 0;
592 for (const char C : Name) {
593 if (isdigit(C)) {
594 V.Part[N] *= 10;
595 V.Part[N] += C - '0';
596 } else if (C == '.') {
597 ++N;
598 if (N >= 4)
599 return V;
600 } else if (N > 0)
601 return V;
602 }
603 return V;
604}
605
606static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
607 switch (Type) {
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000608 case Triple::ArchType::x86:
609 return CPUType::Pentium3;
610 case Triple::ArchType::x86_64:
611 return CPUType::X64;
612 case Triple::ArchType::thumb:
613 return CPUType::Thumb;
614 case Triple::ArchType::aarch64:
615 return CPUType::ARM64;
616 default:
617 report_fatal_error("target architecture doesn't map to a CodeView CPUType");
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000618 }
619}
620
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000621void CodeViewDebug::emitCompilerInformation() {
622 MCContext &Context = MMI->getContext();
623 MCSymbol *CompilerBegin = Context.createTempSymbol(),
624 *CompilerEnd = Context.createTempSymbol();
625 OS.AddComment("Record length");
626 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
627 OS.EmitLabel(CompilerBegin);
628 OS.AddComment("Record kind: S_COMPILE3");
629 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
630 uint32_t Flags = 0;
631
632 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
633 const MDNode *Node = *CUs->operands().begin();
634 const auto *CU = cast<DICompileUnit>(Node);
635
636 // The low byte of the flags indicates the source language.
637 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
638 // TODO: Figure out which other flags need to be set.
639
640 OS.AddComment("Flags and language");
641 OS.EmitIntValue(Flags, 4);
642
643 OS.AddComment("CPUType");
644 CPUType CPU =
645 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
646 OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
647
648 StringRef CompilerVersion = CU->getProducer();
649 Version FrontVer = parseVersion(CompilerVersion);
650 OS.AddComment("Frontend version");
651 for (int N = 0; N < 4; ++N)
652 OS.EmitIntValue(FrontVer.Part[N], 2);
653
654 // Some Microsoft tools, like Binscope, expect a backend version number of at
655 // least 8.something, so we'll coerce the LLVM version into a form that
656 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000657 int Major = 1000 * LLVM_VERSION_MAJOR +
658 10 * LLVM_VERSION_MINOR +
659 LLVM_VERSION_PATCH;
660 // Clamp it for builds that use unusually large version numbers.
661 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
662 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000663 OS.AddComment("Backend version");
664 for (int N = 0; N < 4; ++N)
665 OS.EmitIntValue(BackVer.Part[N], 2);
666
667 OS.AddComment("Null-terminated compiler version string");
668 emitNullTerminatedSymbolName(OS, CompilerVersion);
669
670 OS.EmitLabel(CompilerEnd);
671}
672
Reid Kleckner5d122f82016-05-25 23:16:12 +0000673void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000674 if (InlinedSubprograms.empty())
675 return;
676
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000677 OS.AddComment("Inlinee lines subsection");
Zachary Turner8c099fe2017-05-30 16:36:15 +0000678 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000679
680 // We don't provide any extra file info.
681 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000682 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000683 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
684
685 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000686 assert(TypeIndices.count({SP, nullptr}));
687 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000688
David Majnemer30579ec2016-02-02 23:18:23 +0000689 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000690 unsigned FileId = maybeRecordFile(SP->getFile());
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000691 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000692 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000693 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000694 // The filechecksum table uses 8 byte entries for now, and file ids start at
695 // 1.
696 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000697 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000698 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000699 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000700 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000701 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000702 OS.EmitIntValue(SP->getLine(), 4);
703 }
704
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000705 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000706}
707
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000708void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
709 const DILocation *InlinedAt,
710 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000711 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
712 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000713
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000714 assert(TypeIndices.count({Site.Inlinee, nullptr}));
715 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000716
717 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000718 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000719 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000720 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000721 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000722 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000723
Reid Klecknerdac21b42016-02-03 21:15:48 +0000724 OS.AddComment("PtrParent");
725 OS.EmitIntValue(0, 4);
726 OS.AddComment("PtrEnd");
727 OS.EmitIntValue(0, 4);
728 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000729 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000730
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000731 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
732 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000733
734 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000735 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000736
737 OS.EmitLabel(InlineEnd);
738
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000739 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000740
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000741 // Recurse on child inlined call sites before closing the scope.
742 for (const DILocation *ChildSite : Site.ChildSites) {
743 auto I = FI.InlineSites.find(ChildSite);
744 assert(I != FI.InlineSites.end() &&
745 "child site not in function inline site map");
746 emitInlinedCallSite(FI, ChildSite, I->second);
747 }
748
749 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000750 OS.AddComment("Record length");
751 OS.EmitIntValue(2, 2); // RecordLength
752 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000753 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000754}
755
Reid Kleckner5d122f82016-05-25 23:16:12 +0000756void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
757 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
758 // comdat key. A section may be comdat because of -ffunction-sections or
759 // because it is comdat in the IR.
760 MCSectionCOFF *GVSec =
761 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
762 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
763
764 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
765 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
766 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
767
768 OS.SwitchSection(DebugSec);
769
770 // Emit the magic version number if this is the first time we've switched to
771 // this section.
772 if (ComdatDebugSections.insert(DebugSec).second)
773 emitCodeViewMagicVersion();
774}
775
Reid Kleckner2214ed82016-01-29 00:49:42 +0000776void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
777 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000778 // For each function there is a separate subsection
779 // which holds the PC to file:line table.
780 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000781 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000782
Reid Kleckner5d122f82016-05-25 23:16:12 +0000783 // Switch to the to a comdat section, if appropriate.
784 switchToDebugSectionForSymbol(Fn);
785
Reid Klecknerac945e22016-06-17 16:11:20 +0000786 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000787 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000788 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000789 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000790
791 // If we have a display name, build the fully qualified name by walking the
792 // chain of scopes.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000793 if (!SP->getName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000794 FuncName =
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000795 getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000796
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000797 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000798 if (FuncName.empty())
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +0000799 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000800
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000801 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000802 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Zachary Turner8c099fe2017-05-30 16:36:15 +0000803 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000804 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000805 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
806 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000807 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000808 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000809 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000810
Reid Kleckner4ad127f2016-09-14 21:49:21 +0000811 if (GV->hasLocalLinkage()) {
812 OS.AddComment("Record kind: S_LPROC32_ID");
813 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
814 } else {
815 OS.AddComment("Record kind: S_GPROC32_ID");
816 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
817 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000818
David Majnemer30579ec2016-02-02 23:18:23 +0000819 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000820 OS.AddComment("PtrParent");
821 OS.EmitIntValue(0, 4);
822 OS.AddComment("PtrEnd");
823 OS.EmitIntValue(0, 4);
824 OS.AddComment("PtrNext");
825 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000826 // This is the important bit that tells the debugger where the function
827 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000828 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000829 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000830 OS.AddComment("Offset after prologue");
831 OS.EmitIntValue(0, 4);
832 OS.AddComment("Offset before epilogue");
833 OS.EmitIntValue(0, 4);
834 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000835 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000836 OS.AddComment("Function section relative address");
Keno Fischerf7d84ee2017-01-02 03:00:19 +0000837 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000838 OS.AddComment("Function section index");
839 OS.EmitCOFFSectionIndex(Fn);
840 OS.AddComment("Flags");
841 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000842 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000843 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000844 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000845 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000846 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000847
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000848 emitLocalVariableList(FI.Locals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000849
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000850 // Emit inlined call site information. Only emit functions inlined directly
851 // into the parent function. We'll emit the other sites recursively as part
852 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000853 for (const DILocation *InlinedAt : FI.ChildSites) {
854 auto I = FI.InlineSites.find(InlinedAt);
855 assert(I != FI.InlineSites.end() &&
856 "child site not in function inline site map");
857 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000858 }
859
David Majnemer3128b102016-06-15 18:00:01 +0000860 if (SP != nullptr)
861 emitDebugInfoForUDTs(LocalUDTs);
862
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000863 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000864 OS.AddComment("Record length");
865 OS.EmitIntValue(0x0002, 2);
866 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000867 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000868 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000869 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000870
Reid Kleckner2214ed82016-01-29 00:49:42 +0000871 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000872 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000873}
874
Reid Kleckner876330d2016-02-12 21:48:30 +0000875CodeViewDebug::LocalVarDefRange
876CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
877 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000878 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000879 DR.DataOffset = Offset;
880 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000881 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000882 DR.StructOffset = 0;
883 DR.CVRegister = CVRegister;
884 return DR;
885}
886
887CodeViewDebug::LocalVarDefRange
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000888CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
889 int Offset, bool IsSubfield,
890 uint16_t StructOffset) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000891 LocalVarDefRange DR;
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000892 DR.InMemory = InMemory;
893 DR.DataOffset = Offset;
894 DR.IsSubfield = IsSubfield;
895 DR.StructOffset = StructOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +0000896 DR.CVRegister = CVRegister;
897 return DR;
898}
899
Matthias Braunef331ef2016-11-30 23:48:50 +0000900void CodeViewDebug::collectVariableInfoFromMFTable(
Reid Kleckner876330d2016-02-12 21:48:30 +0000901 DenseSet<InlinedVariable> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +0000902 const MachineFunction &MF = *Asm->MF;
903 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +0000904 const TargetFrameLowering *TFI = TSI.getFrameLowering();
905 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
906
Matthias Braunef331ef2016-11-30 23:48:50 +0000907 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000908 if (!VI.Var)
909 continue;
910 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
911 "Expected inlined-at fields to agree");
912
Reid Kleckner876330d2016-02-12 21:48:30 +0000913 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000914 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
915
916 // If variable scope is not found then skip this variable.
917 if (!Scope)
918 continue;
919
Reid Klecknerb5fced72017-05-09 19:59:29 +0000920 // If the variable has an attached offset expression, extract it.
921 // FIXME: Try to handle DW_OP_deref as well.
922 int64_t ExprOffset = 0;
923 if (VI.Expr)
924 if (!VI.Expr->extractIfOffset(ExprOffset))
925 continue;
926
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000927 // Get the frame register used and the offset.
928 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000929 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
930 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000931
932 // Calculate the label ranges.
Reid Klecknerb5fced72017-05-09 19:59:29 +0000933 LocalVarDefRange DefRange =
934 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000935 for (const InsnRange &Range : Scope->getRanges()) {
936 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
937 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000938 End = End ? End : Asm->getFunctionEnd();
939 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000940 }
941
Reid Kleckner876330d2016-02-12 21:48:30 +0000942 LocalVariable Var;
943 Var.DIVar = VI.Var;
944 Var.DefRanges.emplace_back(std::move(DefRange));
945 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
946 }
947}
948
949void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
950 DenseSet<InlinedVariable> Processed;
951 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +0000952 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +0000953
954 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
955
956 for (const auto &I : DbgValues) {
957 InlinedVariable IV = I.first;
958 if (Processed.count(IV))
959 continue;
960 const DILocalVariable *DIVar = IV.first;
961 const DILocation *InlinedAt = IV.second;
962
963 // Instruction ranges, specifying where IV is accessible.
964 const auto &Ranges = I.second;
965
966 LexicalScope *Scope = nullptr;
967 if (InlinedAt)
968 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
969 else
970 Scope = LScopes.findLexicalScope(DIVar->getScope());
971 // If variable scope is not found then skip this variable.
972 if (!Scope)
973 continue;
974
975 LocalVariable Var;
976 Var.DIVar = DIVar;
977
978 // Calculate the definition ranges.
979 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
980 const InsnRange &Range = *I;
981 const MachineInstr *DVInst = Range.first;
982 assert(DVInst->isDebugValue() && "Invalid History entry");
983 const DIExpression *DIExpr = DVInst->getDebugExpression();
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000984 bool IsSubfield = false;
985 unsigned StructOffset = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000986
Adrian Prantl941fa752016-12-05 18:04:47 +0000987 // Handle fragments.
Adrian Prantl49797ca2016-12-22 05:27:12 +0000988 auto Fragment = DIExpr->getFragmentInfo();
Adrian Prantle8450fd2017-03-27 17:36:31 +0000989 if (Fragment) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000990 IsSubfield = true;
Adrian Prantl49797ca2016-12-22 05:27:12 +0000991 StructOffset = Fragment->OffsetInBits / 8;
Adrian Prantle8450fd2017-03-27 17:36:31 +0000992 } else if (DIExpr->getNumElements() > 0) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000993 continue; // Ignore unrecognized exprs.
994 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000995
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000996 // Bail if operand 0 is not a valid register. This means the variable is a
997 // simple constant, or is described by a complex expression.
998 // FIXME: Find a way to represent constant variables, since they are
999 // relatively common.
1000 unsigned Reg =
1001 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
1002 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +00001003 continue;
1004
Reid Kleckner876330d2016-02-12 21:48:30 +00001005 // Handle the two cases we can handle: indirect in memory and in register.
Reid Kleckner2b3e6422016-10-05 21:21:33 +00001006 unsigned CVReg = TRI->getCodeViewRegNum(Reg);
1007 bool InMemory = DVInst->getOperand(1).isImm();
1008 int Offset = InMemory ? DVInst->getOperand(1).getImm() : 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001009 {
Reid Kleckner2b3e6422016-10-05 21:21:33 +00001010 LocalVarDefRange DR;
1011 DR.CVRegister = CVReg;
1012 DR.InMemory = InMemory;
1013 DR.DataOffset = Offset;
1014 DR.IsSubfield = IsSubfield;
1015 DR.StructOffset = StructOffset;
1016
Reid Kleckner876330d2016-02-12 21:48:30 +00001017 if (Var.DefRanges.empty() ||
Reid Kleckner2b3e6422016-10-05 21:21:33 +00001018 Var.DefRanges.back().isDifferentLocation(DR)) {
1019 Var.DefRanges.emplace_back(std::move(DR));
Reid Kleckner876330d2016-02-12 21:48:30 +00001020 }
1021 }
1022
1023 // Compute the label range.
1024 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1025 const MCSymbol *End = getLabelAfterInsn(Range.second);
1026 if (!End) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +00001027 // This range is valid until the next overlapping bitpiece. In the
1028 // common case, ranges will not be bitpieces, so they will overlap.
1029 auto J = std::next(I);
Adrian Prantl941fa752016-12-05 18:04:47 +00001030 while (J != E &&
1031 !fragmentsOverlap(DIExpr, J->first->getDebugExpression()))
Reid Kleckner2b3e6422016-10-05 21:21:33 +00001032 ++J;
1033 if (J != E)
1034 End = getLabelBeforeInsn(J->first);
Reid Kleckner876330d2016-02-12 21:48:30 +00001035 else
1036 End = Asm->getFunctionEnd();
1037 }
1038
1039 // If the last range end is our begin, just extend the last range.
1040 // Otherwise make a new range.
1041 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
1042 Var.DefRanges.back().Ranges;
1043 if (!Ranges.empty() && Ranges.back().second == Begin)
1044 Ranges.back().second = End;
1045 else
1046 Ranges.emplace_back(Begin, End);
1047
1048 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001049 }
Reid Kleckner876330d2016-02-12 21:48:30 +00001050
1051 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001052 }
1053}
1054
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001055void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001056 const Function *GV = MF->getFunction();
1057 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001058 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +00001059 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001060 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001061
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001062 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1063
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001064 // Find the end of the function prolog. First known non-DBG_VALUE and
1065 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001066 // FIXME: is there a simpler a way to do this? Can we just search
1067 // for the first instruction of the function, not the last of the prolog?
1068 DebugLoc PrologEndLoc;
1069 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001070 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001071 for (const auto &MI : MBB) {
Adrian Prantlfb31da12017-05-22 20:47:09 +00001072 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001073 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001074 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001075 break;
Adrian Prantlfb31da12017-05-22 20:47:09 +00001076 } else if (!MI.isMetaInstruction()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001077 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001078 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001079 }
1080 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001081
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001082 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001083 if (PrologEndLoc && !EmptyPrologue) {
1084 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001085 maybeRecordLocation(FnStartDL, MF);
1086 }
1087}
1088
Hans Wennborg4b63a982016-06-23 22:57:25 +00001089void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001090 // Don't record empty UDTs.
1091 if (Ty->getName().empty())
1092 return;
1093
Hans Wennborg4b63a982016-06-23 22:57:25 +00001094 SmallVector<StringRef, 5> QualifiedNameComponents;
1095 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1096 Ty->getScope().resolve(), QualifiedNameComponents);
1097
1098 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001099 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001100
1101 if (ClosestSubprogram == nullptr)
1102 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1103 else if (ClosestSubprogram == CurrentSubprogram)
1104 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
1105
1106 // TODO: What if the ClosestSubprogram is neither null or the current
1107 // subprogram? Currently, the UDT just gets dropped on the floor.
1108 //
1109 // The current behavior is not desirable. To get maximal fidelity, we would
1110 // need to perform all type translation before beginning emission of .debug$S
1111 // and then make LocalUDTs a member of FunctionInfo
1112}
1113
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001114TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001115 // Generic dispatch for lowering an unknown type.
1116 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001117 case dwarf::DW_TAG_array_type:
1118 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001119 case dwarf::DW_TAG_typedef:
1120 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001121 case dwarf::DW_TAG_base_type:
1122 return lowerTypeBasic(cast<DIBasicType>(Ty));
1123 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001124 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1125 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1126 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001127 case dwarf::DW_TAG_reference_type:
1128 case dwarf::DW_TAG_rvalue_reference_type:
1129 return lowerTypePointer(cast<DIDerivedType>(Ty));
1130 case dwarf::DW_TAG_ptr_to_member_type:
1131 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1132 case dwarf::DW_TAG_const_type:
1133 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001134 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001135 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001136 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001137 if (ClassTy) {
1138 // The member function type of a member function pointer has no
1139 // ThisAdjustment.
1140 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1141 /*ThisAdjustment=*/0);
1142 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001143 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001144 case dwarf::DW_TAG_enumeration_type:
1145 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001146 case dwarf::DW_TAG_class_type:
1147 case dwarf::DW_TAG_structure_type:
1148 return lowerTypeClass(cast<DICompositeType>(Ty));
1149 case dwarf::DW_TAG_union_type:
1150 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001151 default:
1152 // Use the null type index.
1153 return TypeIndex();
1154 }
1155}
1156
David Majnemerd065e232016-06-02 06:21:37 +00001157TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001158 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1159 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001160 StringRef TypeName = Ty->getName();
1161
Hans Wennborg4b63a982016-06-23 22:57:25 +00001162 addToUDTs(Ty, UnderlyingTypeIndex);
David Majnemer3128b102016-06-15 18:00:01 +00001163
David Majnemerd065e232016-06-02 06:21:37 +00001164 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001165 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001166 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001167 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001168 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001169 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001170
David Majnemerd065e232016-06-02 06:21:37 +00001171 return UnderlyingTypeIndex;
1172}
1173
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001174TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1175 DITypeRef ElementTypeRef = Ty->getBaseType();
1176 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1177 // IndexType is size_t, which depends on the bitness of the target.
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001178 TypeIndex IndexType = Asm->TM.getPointerSize() == 8
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001179 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1180 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001181
1182 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1183
Amjad Aboudacee5682016-07-12 12:06:34 +00001184 // Add subranges to array type.
1185 DINodeArray Elements = Ty->getElements();
1186 for (int i = Elements.size() - 1; i >= 0; --i) {
1187 const DINode *Element = Elements[i];
1188 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1189
1190 const DISubrange *Subrange = cast<DISubrange>(Element);
1191 assert(Subrange->getLowerBound() == 0 &&
1192 "codeview doesn't support subranges with lower bounds");
1193 int64_t Count = Subrange->getCount();
1194
1195 // Variable Length Array (VLA) has Count equal to '-1'.
1196 // Replace with Count '1', assume it is the minimum VLA length.
1197 // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
Reid Kleckner6b78e162017-03-24 23:28:42 +00001198 if (Count == -1)
Amjad Aboudacee5682016-07-12 12:06:34 +00001199 Count = 1;
Amjad Aboudacee5682016-07-12 12:06:34 +00001200
Amjad Aboudacee5682016-07-12 12:06:34 +00001201 // Update the element size and element type index for subsequent subranges.
1202 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001203
1204 // If this is the outermost array, use the size from the array. It will be
Reid Kleckner6b78e162017-03-24 23:28:42 +00001205 // more accurate if we had a VLA or an incomplete element type size.
Reid Kleckner10762882016-09-09 17:29:36 +00001206 uint64_t ArraySize =
1207 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1208
1209 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001210 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1211 ElementTypeIndex = TypeTable.writeKnownType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001212 }
1213
Amjad Aboudacee5682016-07-12 12:06:34 +00001214 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001215}
1216
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001217TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1218 TypeIndex Index;
1219 dwarf::TypeKind Kind;
1220 uint32_t ByteSize;
1221
1222 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001223 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001224
1225 SimpleTypeKind STK = SimpleTypeKind::None;
1226 switch (Kind) {
1227 case dwarf::DW_ATE_address:
1228 // FIXME: Translate
1229 break;
1230 case dwarf::DW_ATE_boolean:
1231 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001232 case 1: STK = SimpleTypeKind::Boolean8; break;
1233 case 2: STK = SimpleTypeKind::Boolean16; break;
1234 case 4: STK = SimpleTypeKind::Boolean32; break;
1235 case 8: STK = SimpleTypeKind::Boolean64; break;
1236 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001237 }
1238 break;
1239 case dwarf::DW_ATE_complex_float:
1240 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001241 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001242 case 4: STK = SimpleTypeKind::Complex32; break;
1243 case 8: STK = SimpleTypeKind::Complex64; break;
1244 case 10: STK = SimpleTypeKind::Complex80; break;
1245 case 16: STK = SimpleTypeKind::Complex128; break;
1246 }
1247 break;
1248 case dwarf::DW_ATE_float:
1249 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001250 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001251 case 4: STK = SimpleTypeKind::Float32; break;
1252 case 6: STK = SimpleTypeKind::Float48; break;
1253 case 8: STK = SimpleTypeKind::Float64; break;
1254 case 10: STK = SimpleTypeKind::Float80; break;
1255 case 16: STK = SimpleTypeKind::Float128; break;
1256 }
1257 break;
1258 case dwarf::DW_ATE_signed:
1259 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001260 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1261 case 2: STK = SimpleTypeKind::Int16Short; break;
1262 case 4: STK = SimpleTypeKind::Int32; break;
1263 case 8: STK = SimpleTypeKind::Int64Quad; break;
1264 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001265 }
1266 break;
1267 case dwarf::DW_ATE_unsigned:
1268 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001269 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1270 case 2: STK = SimpleTypeKind::UInt16Short; break;
1271 case 4: STK = SimpleTypeKind::UInt32; break;
1272 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1273 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001274 }
1275 break;
1276 case dwarf::DW_ATE_UTF:
1277 switch (ByteSize) {
1278 case 2: STK = SimpleTypeKind::Character16; break;
1279 case 4: STK = SimpleTypeKind::Character32; break;
1280 }
1281 break;
1282 case dwarf::DW_ATE_signed_char:
1283 if (ByteSize == 1)
1284 STK = SimpleTypeKind::SignedCharacter;
1285 break;
1286 case dwarf::DW_ATE_unsigned_char:
1287 if (ByteSize == 1)
1288 STK = SimpleTypeKind::UnsignedCharacter;
1289 break;
1290 default:
1291 break;
1292 }
1293
1294 // Apply some fixups based on the source-level type name.
1295 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1296 STK = SimpleTypeKind::Int32Long;
1297 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1298 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001299 if (STK == SimpleTypeKind::UInt16Short &&
1300 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001301 STK = SimpleTypeKind::WideCharacter;
1302 if ((STK == SimpleTypeKind::SignedCharacter ||
1303 STK == SimpleTypeKind::UnsignedCharacter) &&
1304 Ty->getName() == "char")
1305 STK = SimpleTypeKind::NarrowCharacter;
1306
1307 return TypeIndex(STK);
1308}
1309
1310TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1311 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1312
1313 // Pointers to simple types can use SimpleTypeMode, rather than having a
1314 // dedicated pointer type record.
1315 if (PointeeTI.isSimple() &&
1316 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1317 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1318 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1319 ? SimpleTypeMode::NearPointer64
1320 : SimpleTypeMode::NearPointer32;
1321 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1322 }
1323
1324 PointerKind PK =
1325 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1326 PointerMode PM = PointerMode::Pointer;
1327 switch (Ty->getTag()) {
1328 default: llvm_unreachable("not a pointer tag type");
1329 case dwarf::DW_TAG_pointer_type:
1330 PM = PointerMode::Pointer;
1331 break;
1332 case dwarf::DW_TAG_reference_type:
1333 PM = PointerMode::LValueReference;
1334 break;
1335 case dwarf::DW_TAG_rvalue_reference_type:
1336 PM = PointerMode::RValueReference;
1337 break;
1338 }
1339 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1340 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1341 // do.
1342 PointerOptions PO = PointerOptions::None;
1343 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001344 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001345}
1346
Reid Kleckner6fa15462016-06-17 22:14:39 +00001347static PointerToMemberRepresentation
1348translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1349 // SizeInBytes being zero generally implies that the member pointer type was
1350 // incomplete, which can happen if it is part of a function prototype. In this
1351 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001352 if (IsPMF) {
1353 switch (Flags & DINode::FlagPtrToMemberRep) {
1354 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001355 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1356 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001357 case DINode::FlagSingleInheritance:
1358 return PointerToMemberRepresentation::SingleInheritanceFunction;
1359 case DINode::FlagMultipleInheritance:
1360 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1361 case DINode::FlagVirtualInheritance:
1362 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1363 }
1364 } else {
1365 switch (Flags & DINode::FlagPtrToMemberRep) {
1366 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001367 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1368 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001369 case DINode::FlagSingleInheritance:
1370 return PointerToMemberRepresentation::SingleInheritanceData;
1371 case DINode::FlagMultipleInheritance:
1372 return PointerToMemberRepresentation::MultipleInheritanceData;
1373 case DINode::FlagVirtualInheritance:
1374 return PointerToMemberRepresentation::VirtualInheritanceData;
1375 }
1376 }
1377 llvm_unreachable("invalid ptr to member representation");
1378}
1379
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001380TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1381 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1382 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001383 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001384 PointerKind PK = Asm->TM.getPointerSize() == 8 ? PointerKind::Near64
1385 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001386 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1387 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1388 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001389 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001390 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1391 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1392 MemberPointerInfo MPI(
1393 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001394 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001395 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001396}
1397
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001398/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1399/// have a translation, use the NearC convention.
1400static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1401 switch (DwarfCC) {
1402 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1403 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1404 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1405 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1406 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1407 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1408 }
1409 return CallingConvention::NearC;
1410}
1411
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001412TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1413 ModifierOptions Mods = ModifierOptions::None;
1414 bool IsModifier = true;
1415 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001416 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001417 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001418 switch (BaseTy->getTag()) {
1419 case dwarf::DW_TAG_const_type:
1420 Mods |= ModifierOptions::Const;
1421 break;
1422 case dwarf::DW_TAG_volatile_type:
1423 Mods |= ModifierOptions::Volatile;
1424 break;
1425 default:
1426 IsModifier = false;
1427 break;
1428 }
1429 if (IsModifier)
1430 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1431 }
1432 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001433 ModifierRecord MR(ModifiedTI, Mods);
1434 return TypeTable.writeKnownType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001435}
1436
David Majnemer75c3ebf2016-06-02 17:13:53 +00001437TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1438 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1439 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1440 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1441
1442 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1443 ArrayRef<TypeIndex> ArgTypeIndices = None;
1444 if (!ReturnAndArgTypeIndices.empty()) {
1445 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1446 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1447 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1448 }
1449
1450 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001451 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001452
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001453 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1454
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001455 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1456 ArgTypeIndices.size(), ArgListIndex);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001457 return TypeTable.writeKnownType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001458}
1459
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001460TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001461 const DIType *ClassTy,
1462 int ThisAdjustment) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001463 // Lower the containing class type.
1464 TypeIndex ClassType = getTypeIndex(ClassTy);
1465
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001466 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1467 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1468 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1469
1470 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1471 ArrayRef<TypeIndex> ArgTypeIndices = None;
1472 if (!ReturnAndArgTypeIndices.empty()) {
1473 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1474 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1475 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1476 }
1477 TypeIndex ThisTypeIndex = TypeIndex::Void();
1478 if (!ArgTypeIndices.empty()) {
1479 ThisTypeIndex = ArgTypeIndices.front();
1480 ArgTypeIndices = ArgTypeIndices.drop_front();
1481 }
1482
1483 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001484 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001485
1486 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1487
1488 // TODO: Need to use the correct values for:
1489 // FunctionOptions
1490 // ThisPointerAdjustment.
Zachary Turner4efa0a42016-11-08 22:24:53 +00001491 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1492 FunctionOptions::None, ArgTypeIndices.size(),
1493 ArgListIndex, ThisAdjustment);
1494 TypeIndex TI = TypeTable.writeKnownType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001495
1496 return TI;
1497}
1498
Reid Kleckner9dac4732016-08-31 15:59:30 +00001499TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001500 unsigned VSlotCount =
1501 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
Reid Kleckner9dac4732016-08-31 15:59:30 +00001502 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001503
1504 VFTableShapeRecord VFTSR(Slots);
1505 return TypeTable.writeKnownType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001506}
1507
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001508static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1509 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001510 case DINode::FlagPrivate: return MemberAccess::Private;
1511 case DINode::FlagPublic: return MemberAccess::Public;
1512 case DINode::FlagProtected: return MemberAccess::Protected;
1513 case 0:
1514 // If there was no explicit access control, provide the default for the tag.
1515 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1516 : MemberAccess::Public;
1517 }
1518 llvm_unreachable("access flags are exclusive");
1519}
1520
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001521static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1522 if (SP->isArtificial())
1523 return MethodOptions::CompilerGenerated;
1524
1525 // FIXME: Handle other MethodOptions.
1526
1527 return MethodOptions::None;
1528}
1529
1530static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1531 bool Introduced) {
1532 switch (SP->getVirtuality()) {
1533 case dwarf::DW_VIRTUALITY_none:
1534 break;
1535 case dwarf::DW_VIRTUALITY_virtual:
1536 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1537 case dwarf::DW_VIRTUALITY_pure_virtual:
1538 return Introduced ? MethodKind::PureIntroducingVirtual
1539 : MethodKind::PureVirtual;
1540 default:
1541 llvm_unreachable("unhandled virtuality case");
1542 }
1543
1544 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1545
1546 return MethodKind::Vanilla;
1547}
1548
Reid Klecknera8d57402016-06-03 15:58:20 +00001549static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1550 switch (Ty->getTag()) {
1551 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1552 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1553 }
1554 llvm_unreachable("unexpected tag");
1555}
1556
Reid Klecknere092dad2016-07-02 00:11:07 +00001557/// Return ClassOptions that should be present on both the forward declaration
1558/// and the defintion of a tag type.
1559static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1560 ClassOptions CO = ClassOptions::None;
1561
1562 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001563 // appear to give every type a linkage name, which may be problematic for us.
1564 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001565 if (!Ty->getIdentifier().empty())
1566 CO |= ClassOptions::HasUniqueName;
1567
1568 // Put the Nested flag on a type if it appears immediately inside a tag type.
1569 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1570 // here. That flag is only set on definitions, and not forward declarations.
1571 const DIScope *ImmediateScope = Ty->getScope().resolve();
1572 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1573 CO |= ClassOptions::Nested;
1574
1575 // Put the Scoped flag on function-local types.
1576 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1577 Scope = Scope->getScope().resolve()) {
1578 if (isa<DISubprogram>(Scope)) {
1579 CO |= ClassOptions::Scoped;
1580 break;
1581 }
1582 }
1583
1584 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001585}
1586
David Majnemer979cb882016-06-16 21:32:16 +00001587TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001588 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001589 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001590 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001591
David Majnemerda9548f2016-06-17 16:13:21 +00001592 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001593 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001594 } else {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001595 FieldListRecordBuilder FLRB(TypeTable);
1596
1597 FLRB.begin();
David Majnemerda9548f2016-06-17 16:13:21 +00001598 for (const DINode *Element : Ty->getElements()) {
1599 // We assume that the frontend provides all members in source declaration
1600 // order, which is what MSVC does.
1601 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001602 EnumeratorRecord ER(MemberAccess::Public,
1603 APSInt::getUnsigned(Enumerator->getValue()),
1604 Enumerator->getName());
1605 FLRB.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00001606 EnumeratorCount++;
1607 }
1608 }
Zachary Turner7f97c362017-05-25 21:15:37 +00001609 FTI = FLRB.end(true);
David Majnemerda9548f2016-06-17 16:13:21 +00001610 }
David Majnemer979cb882016-06-16 21:32:16 +00001611
David Majnemer6bdc24e2016-07-01 23:12:45 +00001612 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001613
Zachary Turner4efa0a42016-11-08 22:24:53 +00001614 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1615 getTypeIndex(Ty->getBaseType()));
1616 return TypeTable.writeKnownType(ER);
David Majnemer979cb882016-06-16 21:32:16 +00001617}
1618
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001619//===----------------------------------------------------------------------===//
1620// ClassInfo
1621//===----------------------------------------------------------------------===//
1622
1623struct llvm::ClassInfo {
1624 struct MemberInfo {
1625 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001626 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001627 };
1628 // [MemberInfo]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001629 using MemberList = std::vector<MemberInfo>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001630
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001631 using MethodsList = TinyPtrVector<const DISubprogram *>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001632 // MethodName -> MethodsList
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001633 using MethodsMap = MapVector<MDString *, MethodsList>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001634
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001635 /// Base classes.
1636 std::vector<const DIDerivedType *> Inheritance;
1637
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001638 /// Direct members.
1639 MemberList Members;
1640 // Direct overloaded methods gathered by name.
1641 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001642
Reid Kleckner9dac4732016-08-31 15:59:30 +00001643 TypeIndex VShapeTI;
1644
Adrian McCarthy820ca542016-07-06 19:49:51 +00001645 std::vector<const DICompositeType *> NestedClasses;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001646};
1647
1648void CodeViewDebug::clear() {
1649 assert(CurFn == nullptr);
1650 FileIdMap.clear();
1651 FnDebugInfo.clear();
1652 FileToFilepathMap.clear();
1653 LocalUDTs.clear();
1654 GlobalUDTs.clear();
1655 TypeIndices.clear();
1656 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001657}
1658
1659void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1660 const DIDerivedType *DDTy) {
1661 if (!DDTy->getName().empty()) {
1662 Info.Members.push_back({DDTy, 0});
1663 return;
1664 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001665 // An unnamed member must represent a nested struct or union. Add all the
1666 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001667 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00001668 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001669 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001670 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001671 ClassInfo NestedInfo = collectClassInfo(DCTy);
1672 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001673 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001674 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001675}
1676
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001677ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1678 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001679 // Add elements to structure type.
1680 DINodeArray Elements = Ty->getElements();
1681 for (auto *Element : Elements) {
1682 // We assume that the frontend provides all members in source declaration
1683 // order, which is what MSVC does.
1684 if (!Element)
1685 continue;
1686 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001687 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001688 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001689 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001690 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001691 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1692 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001693 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1694 DDTy->getName() == "__vtbl_ptr_type") {
1695 Info.VShapeTI = getTypeIndex(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001696 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1697 // Ignore friend members. It appears that MSVC emitted info about
1698 // friends in the past, but modern versions do not.
1699 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001700 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1701 Info.NestedClasses.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001702 }
1703 // Skip other unrecognized kinds of elements.
1704 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001705 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001706}
1707
Reid Klecknera8d57402016-06-03 15:58:20 +00001708TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1709 // First, construct the forward decl. Don't look into Ty to compute the
1710 // forward decl options, since it might not be available in all TUs.
1711 TypeRecordKind Kind = getRecordKind(Ty);
1712 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001713 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001714 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001715 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
1716 FullName, Ty->getIdentifier());
1717 TypeIndex FwdDeclTI = TypeTable.writeKnownType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001718 if (!Ty->isForwardDecl())
1719 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001720 return FwdDeclTI;
1721}
1722
1723TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1724 // Construct the field list and complete type record.
1725 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00001726 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001727 TypeIndex FieldTI;
1728 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001729 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001730 bool ContainsNestedClass;
1731 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1732 lowerRecordFieldList(Ty);
1733
1734 if (ContainsNestedClass)
1735 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00001736
David Majnemer6bdc24e2016-07-01 23:12:45 +00001737 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001738
Reid Klecknera8d57402016-06-03 15:58:20 +00001739 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001740
Zachary Turner4efa0a42016-11-08 22:24:53 +00001741 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
1742 SizeInBytes, FullName, Ty->getIdentifier());
1743 TypeIndex ClassTI = TypeTable.writeKnownType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001744
Saleem Abdulrasool87f03382017-05-03 21:39:01 +00001745 if (const auto *File = Ty->getFile()) {
1746 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
1747 TypeIndex SIDI = TypeTable.writeKnownType(SIDR);
1748 UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine());
1749 TypeTable.writeKnownType(USLR);
1750 }
Hans Wennborg9a519a02016-06-22 21:22:13 +00001751
Hans Wennborg4b63a982016-06-23 22:57:25 +00001752 addToUDTs(Ty, ClassTI);
1753
Hans Wennborg9a519a02016-06-22 21:22:13 +00001754 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001755}
1756
1757TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1758 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001759 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001760 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001761 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
1762 TypeIndex FwdDeclTI = TypeTable.writeKnownType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001763 if (!Ty->isForwardDecl())
1764 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001765 return FwdDeclTI;
1766}
1767
1768TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00001769 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001770 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001771 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001772 bool ContainsNestedClass;
1773 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1774 lowerRecordFieldList(Ty);
1775
1776 if (ContainsNestedClass)
1777 CO |= ClassOptions::ContainsNestedClass;
1778
Reid Klecknera8d57402016-06-03 15:58:20 +00001779 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00001780 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001781
Zachary Turner4efa0a42016-11-08 22:24:53 +00001782 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
1783 Ty->getIdentifier());
1784 TypeIndex UnionTI = TypeTable.writeKnownType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001785
Zachary Turner4efa0a42016-11-08 22:24:53 +00001786 StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1787 TypeIndex SIRI = TypeTable.writeKnownType(SIR);
1788 UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine());
1789 TypeTable.writeKnownType(USLR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001790
Hans Wennborg4b63a982016-06-23 22:57:25 +00001791 addToUDTs(Ty, UnionTI);
1792
Hans Wennborg9a519a02016-06-22 21:22:13 +00001793 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001794}
1795
Adrian McCarthy820ca542016-07-06 19:49:51 +00001796std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00001797CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1798 // Manually count members. MSVC appears to count everything that generates a
1799 // field list record. Each individual overload in a method overload group
1800 // contributes to this count, even though the overload group is a single field
1801 // list record.
1802 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001803 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001804 FieldListRecordBuilder FLBR(TypeTable);
1805 FLBR.begin();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001806
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001807 // Create base classes.
1808 for (const DIDerivedType *I : Info.Inheritance) {
1809 if (I->getFlags() & DINode::FlagVirtual) {
1810 // Virtual base.
1811 // FIXME: Emit VBPtrOffset when the frontend provides it.
1812 unsigned VBPtrOffset = 0;
1813 // FIXME: Despite the accessor name, the offset is really in bytes.
1814 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00001815 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
1816 ? TypeRecordKind::IndirectVirtualBaseClass
1817 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001818 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00001819 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001820 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00001821 VBTableIndex);
1822
1823 FLBR.writeMemberType(VBCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001824 } else {
1825 assert(I->getOffsetInBits() % 8 == 0 &&
1826 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00001827 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
1828 getTypeIndex(I->getBaseType()),
1829 I->getOffsetInBits() / 8);
1830 FLBR.writeMemberType(BCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001831 }
1832 }
1833
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001834 // Create members.
1835 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1836 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1837 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00001838 StringRef MemberName = Member->getName();
1839 MemberAccess Access =
1840 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001841
1842 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001843 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
1844 FLBR.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001845 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001846 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001847 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001848
Reid Kleckner9dac4732016-08-31 15:59:30 +00001849 // Virtual function pointer member.
1850 if ((Member->getFlags() & DINode::FlagArtificial) &&
1851 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001852 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
1853 FLBR.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001854 MemberCount++;
1855 continue;
1856 }
1857
David Majnemer9319cbc2016-06-30 03:00:20 +00001858 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00001859 uint64_t MemberOffsetInBits =
1860 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001861 if (Member->isBitField()) {
1862 uint64_t StartBitOffset = MemberOffsetInBits;
1863 if (const auto *CI =
1864 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00001865 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001866 }
1867 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001868 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
1869 StartBitOffset);
1870 MemberBaseType = TypeTable.writeKnownType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00001871 }
1872 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001873 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
1874 MemberName);
1875 FLBR.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001876 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001877 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001878
1879 // Create methods
1880 for (auto &MethodItr : Info.Methods) {
1881 StringRef Name = MethodItr.first->getString();
1882
1883 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00001884 for (const DISubprogram *SP : MethodItr.second) {
1885 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1886 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001887
1888 unsigned VFTableOffset = -1;
1889 if (Introduced)
1890 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1891
Zachary Turner7251ede2016-11-02 17:05:19 +00001892 Methods.push_back(OneMethodRecord(
1893 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
1894 translateMethodKindFlags(SP, Introduced),
1895 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001896 MemberCount++;
1897 }
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001898 assert(!Methods.empty() && "Empty methods map entry");
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001899 if (Methods.size() == 1)
Zachary Turner4efa0a42016-11-08 22:24:53 +00001900 FLBR.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001901 else {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001902 MethodOverloadListRecord MOLR(Methods);
1903 TypeIndex MethodList = TypeTable.writeKnownType(MOLR);
1904 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
1905 FLBR.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001906 }
1907 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001908
1909 // Create nested classes.
1910 for (const DICompositeType *Nested : Info.NestedClasses) {
1911 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner4efa0a42016-11-08 22:24:53 +00001912 FLBR.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00001913 MemberCount++;
1914 }
1915
Zachary Turner7f97c362017-05-25 21:15:37 +00001916 TypeIndex FieldTI = FLBR.end(true);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001917 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Adrian McCarthy820ca542016-07-06 19:49:51 +00001918 !Info.NestedClasses.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00001919}
1920
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001921TypeIndex CodeViewDebug::getVBPTypeIndex() {
1922 if (!VBPType.getIndex()) {
1923 // Make a 'const int *' type.
1924 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001925 TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001926
1927 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1928 : PointerKind::Near32;
1929 PointerMode PM = PointerMode::Pointer;
1930 PointerOptions PO = PointerOptions::None;
1931 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1932
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001933 VBPType = TypeTable.writeKnownType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001934 }
1935
1936 return VBPType;
1937}
1938
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001939TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001940 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001941 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001942
1943 // The null DIType is the void type. Don't try to hash it.
1944 if (!Ty)
1945 return TypeIndex::Void();
1946
Reid Klecknera8d57402016-06-03 15:58:20 +00001947 // Check if we've already translated this type. Don't try to do a
1948 // get-or-create style insertion that caches the hash lookup across the
1949 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001950 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001951 if (I != TypeIndices.end())
1952 return I->second;
1953
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001954 TypeLoweringScope S(*this);
1955 TypeIndex TI = lowerType(Ty, ClassTy);
1956 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00001957}
1958
1959TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1960 const DIType *Ty = TypeRef.resolve();
1961
1962 // The null DIType is the void type. Don't try to hash it.
1963 if (!Ty)
1964 return TypeIndex::Void();
1965
1966 // If this is a non-record type, the complete type index is the same as the
1967 // normal type index. Just call getTypeIndex.
1968 switch (Ty->getTag()) {
1969 case dwarf::DW_TAG_class_type:
1970 case dwarf::DW_TAG_structure_type:
1971 case dwarf::DW_TAG_union_type:
1972 break;
1973 default:
1974 return getTypeIndex(Ty);
1975 }
1976
1977 // Check if we've already translated the complete record type. Lowering a
1978 // complete type should never trigger lowering another complete type, so we
1979 // can reuse the hash table lookup result.
1980 const auto *CTy = cast<DICompositeType>(Ty);
1981 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1982 if (!InsertResult.second)
1983 return InsertResult.first->second;
1984
Reid Kleckner643dd832016-06-22 17:15:28 +00001985 TypeLoweringScope S(*this);
1986
Reid Klecknera8d57402016-06-03 15:58:20 +00001987 // Make sure the forward declaration is emitted first. It's unclear if this
1988 // is necessary, but MSVC does it, and we should follow suit until we can show
1989 // otherwise.
1990 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1991
1992 // Just use the forward decl if we don't have complete type info. This might
1993 // happen if the frontend is using modules and expects the complete definition
1994 // to be emitted elsewhere.
1995 if (CTy->isForwardDecl())
1996 return FwdDeclTI;
1997
1998 TypeIndex TI;
1999 switch (CTy->getTag()) {
2000 case dwarf::DW_TAG_class_type:
2001 case dwarf::DW_TAG_structure_type:
2002 TI = lowerCompleteTypeClass(CTy);
2003 break;
2004 case dwarf::DW_TAG_union_type:
2005 TI = lowerCompleteTypeUnion(CTy);
2006 break;
2007 default:
2008 llvm_unreachable("not a record");
2009 }
2010
2011 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002012 return TI;
2013}
2014
Reid Kleckner643dd832016-06-22 17:15:28 +00002015/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00002016/// and do this until fixpoint, as each complete record type typically
2017/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00002018/// many other record types.
2019void CodeViewDebug::emitDeferredCompleteTypes() {
2020 SmallVector<const DICompositeType *, 4> TypesToEmit;
2021 while (!DeferredCompleteTypes.empty()) {
2022 std::swap(DeferredCompleteTypes, TypesToEmit);
2023 for (const DICompositeType *RecordTy : TypesToEmit)
2024 getCompleteTypeIndex(RecordTy);
2025 TypesToEmit.clear();
2026 }
2027}
2028
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002029void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
2030 // Get the sorted list of parameters and emit them first.
2031 SmallVector<const LocalVariable *, 6> Params;
2032 for (const LocalVariable &L : Locals)
2033 if (L.DIVar->isParameter())
2034 Params.push_back(&L);
2035 std::sort(Params.begin(), Params.end(),
2036 [](const LocalVariable *L, const LocalVariable *R) {
2037 return L->DIVar->getArg() < R->DIVar->getArg();
2038 });
2039 for (const LocalVariable *L : Params)
2040 emitLocalVariable(*L);
2041
2042 // Next emit all non-parameters in the order that we found them.
2043 for (const LocalVariable &L : Locals)
2044 if (!L.DIVar->isParameter())
2045 emitLocalVariable(L);
2046}
2047
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002048void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2049 // LocalSym record, see SymbolRecord.h for more info.
2050 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2051 *LocalEnd = MMI->getContext().createTempSymbol();
2052 OS.AddComment("Record length");
2053 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2054 OS.EmitLabel(LocalBegin);
2055
2056 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00002057 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002058
Zachary Turner63a28462016-05-17 23:50:21 +00002059 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002060 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002061 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002062 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002063 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002064
2065 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00002066 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002067 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002068 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002069 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002070 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002071 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002072 OS.EmitLabel(LocalEnd);
2073
Reid Kleckner876330d2016-02-12 21:48:30 +00002074 // Calculate the on disk prefix of the appropriate def range record. The
2075 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2076 // should be big enough to hold all forms without memory allocation.
2077 SmallString<20> BytePrefix;
2078 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2079 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002080 if (DefRange.InMemory) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002081 uint16_t RegRelFlags = 0;
2082 if (DefRange.IsSubfield) {
2083 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2084 (DefRange.StructOffset
2085 << DefRangeRegisterRelSym::OffsetInParentShift);
2086 }
Zachary Turner46225b12016-12-16 22:48:14 +00002087 DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
2088 Sym.Hdr.Register = DefRange.CVRegister;
2089 Sym.Hdr.Flags = RegRelFlags;
2090 Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +00002091 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00002092 BytePrefix +=
2093 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00002094 BytePrefix +=
Zachary Turner46225b12016-12-16 22:48:14 +00002095 StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
Reid Kleckner876330d2016-02-12 21:48:30 +00002096 } else {
2097 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002098 if (DefRange.IsSubfield) {
2099 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002100 DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2101 Sym.Hdr.Register = DefRange.CVRegister;
2102 Sym.Hdr.MayHaveNoName = 0;
2103 Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2104
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002105 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2106 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2107 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002108 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2109 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002110 } else {
2111 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002112 DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2113 Sym.Hdr.Register = DefRange.CVRegister;
2114 Sym.Hdr.MayHaveNoName = 0;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002115 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2116 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2117 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002118 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2119 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002120 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002121 }
2122 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2123 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002124}
2125
David Blaikieb2fbb4b2017-02-16 18:48:33 +00002126void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002127 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00002128 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002129 assert(CurFn == &FnDebugInfo[GV]);
2130
Pete Cooperadebb932016-03-11 02:14:16 +00002131 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002132
Reid Kleckner2214ed82016-01-29 00:49:42 +00002133 // Don't emit anything if we don't have any line tables.
2134 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002135 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002136 CurFn = nullptr;
2137 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002138 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002139
2140 CurFn->End = Asm->getFunctionEnd();
2141
Craig Topper353eda42014-04-24 06:44:33 +00002142 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002143}
2144
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002145void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002146 DebugHandlerBase::beginInstruction(MI);
2147
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002148 // Ignore DBG_VALUE locations and function prologue.
David Majnemer67f684e2016-07-28 05:03:22 +00002149 if (!Asm || !CurFn || MI->isDebugValue() ||
2150 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002151 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002152
2153 // If the first instruction of a new MBB has no location, find the first
2154 // instruction with a location and use that.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002155 DebugLoc DL = MI->getDebugLoc();
Reid Kleckner45a74622017-06-30 21:33:44 +00002156 if (!DL && MI->getParent() != PrevInstBB) {
2157 for (const auto &NextMI : *MI->getParent()) {
2158 DL = NextMI.getDebugLoc();
2159 if (DL)
2160 break;
2161 }
2162 }
2163 PrevInstBB = MI->getParent();
2164
2165 // If we still don't have a debug location, don't record a location.
2166 if (!DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002167 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002168
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002169 maybeRecordLocation(DL, Asm->MF);
2170}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002171
Zachary Turner8c099fe2017-05-30 16:36:15 +00002172MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002173 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2174 *EndLabel = MMI->getContext().createTempSymbol();
2175 OS.EmitIntValue(unsigned(Kind), 4);
2176 OS.AddComment("Subsection size");
2177 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2178 OS.EmitLabel(BeginLabel);
2179 return EndLabel;
2180}
2181
2182void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2183 OS.EmitLabel(EndLabel);
2184 // Every subsection must be aligned to a 4-byte boundary.
2185 OS.EmitValueToAlignment(4);
2186}
2187
David Majnemer3128b102016-06-15 18:00:01 +00002188void CodeViewDebug::emitDebugInfoForUDTs(
2189 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
2190 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
2191 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2192 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2193 OS.AddComment("Record length");
2194 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2195 OS.EmitLabel(UDTRecordBegin);
2196
2197 OS.AddComment("Record kind: S_UDT");
2198 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2199
2200 OS.AddComment("Type");
2201 OS.EmitIntValue(UDT.second.getIndex(), 4);
2202
2203 emitNullTerminatedSymbolName(OS, UDT.first);
2204 OS.EmitLabel(UDTRecordEnd);
2205 }
2206}
2207
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002208void CodeViewDebug::emitDebugInfoForGlobals() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002209 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2210 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002211 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002212 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2213 GV.getDebugInfo(GVEs);
2214 for (const auto *GVE : GVEs)
2215 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002216 }
2217
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002218 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2219 for (const MDNode *Node : CUs->operands()) {
2220 const auto *CU = cast<DICompileUnit>(Node);
2221
2222 // First, emit all globals that are not in a comdat in a single symbol
2223 // substream. MSVC doesn't like it if the substream is empty, so only open
2224 // it if we have at least one global to emit.
2225 switchToDebugSectionForSymbol(nullptr);
2226 MCSymbol *EndLabel = nullptr;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002227 for (const auto *GVE : CU->getGlobalVariables()) {
2228 if (const auto *GV = GlobalMap.lookup(GVE))
David Majnemer577be0f2016-06-15 00:19:52 +00002229 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002230 if (!EndLabel) {
2231 OS.AddComment("Symbol subsection for globals");
Zachary Turner8c099fe2017-05-30 16:36:15 +00002232 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002233 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002234 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2235 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002236 }
2237 }
2238 if (EndLabel)
2239 endCVSubsection(EndLabel);
2240
2241 // Second, emit each global that is in a comdat into its own .debug$S
2242 // section along with its own symbol substream.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002243 for (const auto *GVE : CU->getGlobalVariables()) {
2244 if (const auto *GV = GlobalMap.lookup(GVE)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002245 if (GV->hasComdat()) {
2246 MCSymbol *GVSym = Asm->getSymbol(GV);
2247 OS.AddComment("Symbol subsection for " +
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00002248 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002249 switchToDebugSectionForSymbol(GVSym);
Zachary Turner8c099fe2017-05-30 16:36:15 +00002250 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002251 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2252 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002253 endCVSubsection(EndLabel);
2254 }
2255 }
2256 }
2257 }
2258}
2259
Hans Wennborgb510b452016-06-23 16:33:53 +00002260void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2261 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2262 for (const MDNode *Node : CUs->operands()) {
2263 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2264 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2265 getTypeIndex(RT);
2266 // FIXME: Add to global/local DTU list.
2267 }
2268 }
2269 }
2270}
2271
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002272void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002273 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002274 MCSymbol *GVSym) {
2275 // DataSym record, see SymbolRecord.h for more info.
2276 // FIXME: Thread local data, etc
2277 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2278 *DataEnd = MMI->getContext().createTempSymbol();
2279 OS.AddComment("Record length");
2280 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2281 OS.EmitLabel(DataBegin);
David Majnemer7abd2692016-07-06 21:07:47 +00002282 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002283 if (GV->isThreadLocal()) {
2284 OS.AddComment("Record kind: S_LTHREAD32");
2285 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2286 } else {
2287 OS.AddComment("Record kind: S_LDATA32");
2288 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2289 }
David Majnemer7abd2692016-07-06 21:07:47 +00002290 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002291 if (GV->isThreadLocal()) {
2292 OS.AddComment("Record kind: S_GTHREAD32");
2293 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2294 } else {
2295 OS.AddComment("Record kind: S_GDATA32");
2296 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2297 }
David Majnemer7abd2692016-07-06 21:07:47 +00002298 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002299 OS.AddComment("Type");
2300 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2301 OS.AddComment("DataOffset");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00002302 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002303 OS.AddComment("Segment");
2304 OS.EmitCOFFSectionIndex(GVSym);
2305 OS.AddComment("Name");
2306 emitNullTerminatedSymbolName(OS, DIGV->getName());
2307 OS.EmitLabel(DataEnd);
2308}