blob: 021cee526d818953dc5c9e3ced7c61d8e86dda48 [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"
Adrian Prantl032d2382017-08-01 21:45:24 +000015#include "DwarfExpression.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000016#include "llvm/ADT/APSInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/DenseSet.h"
20#include "llvm/ADT/MapVector.h"
21#include "llvm/ADT/None.h"
22#include "llvm/ADT/Optional.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/StringRef.h"
Reid Kleckner156a7232016-06-22 18:31:14 +000027#include "llvm/ADT/TinyPtrVector.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000028#include "llvm/ADT/Triple.h"
29#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000030#include "llvm/BinaryFormat/COFF.h"
31#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000032#include "llvm/CodeGen/AsmPrinter.h"
33#include "llvm/CodeGen/LexicalScopes.h"
34#include "llvm/CodeGen/MachineFunction.h"
35#include "llvm/CodeGen/MachineInstr.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineOperand.h"
38#include "llvm/Config/llvm-config.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000039#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000040#include "llvm/DebugInfo/CodeView/CodeView.h"
Zachary Turner8c099fe2017-05-30 16:36:15 +000041#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000042#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000043#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000044#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000045#include "llvm/DebugInfo/CodeView/TypeIndex.h"
46#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000047#include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000048#include "llvm/IR/Constants.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000049#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DebugInfoMetadata.h"
51#include "llvm/IR/DebugLoc.h"
52#include "llvm/IR/Function.h"
53#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/GlobalVariable.h"
55#include "llvm/IR/Metadata.h"
56#include "llvm/IR/Module.h"
Reid Kleckner46cb48c2016-07-27 16:03:57 +000057#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000058#include "llvm/MC/MCContext.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000059#include "llvm/MC/MCSectionCOFF.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000060#include "llvm/MC/MCStreamer.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000061#include "llvm/MC/MCSymbol.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000062#include "llvm/Support/BinaryByteStream.h"
63#include "llvm/Support/BinaryStreamReader.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000064#include "llvm/Support/Casting.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000065#include "llvm/Support/Compiler.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000066#include "llvm/Support/Endian.h"
67#include "llvm/Support/Error.h"
68#include "llvm/Support/ErrorHandling.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000069#include "llvm/Support/ScopedPrinter.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000070#include "llvm/Support/SMLoc.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000071#include "llvm/Target/TargetFrameLowering.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000072#include "llvm/Target/TargetLoweringObjectFile.h"
73#include "llvm/Target/TargetMachine.h"
Amjad Aboud76c9eb92016-06-18 10:25:07 +000074#include "llvm/Target/TargetRegisterInfo.h"
75#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000076#include <algorithm>
77#include <cassert>
78#include <cctype>
79#include <cstddef>
80#include <cstdint>
81#include <iterator>
82#include <limits>
83#include <string>
84#include <utility>
85#include <vector>
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000086
Reid Klecknerf9c275f2016-02-10 20:55:49 +000087using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000088using namespace llvm::codeview;
89
Reid Klecknerf9c275f2016-02-10 20:55:49 +000090CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
Eugene Zelenkofb69e662017-06-06 22:22:41 +000091 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +000092 // If module doesn't have named metadata anchors or COFF debug section
93 // is not available, skip any debug info related stuff.
94 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
95 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
96 Asm = nullptr;
97 return;
98 }
99
100 // Tell MMI that we have debug info.
101 MMI->setDebugInfoAvailability(true);
102}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000103
Reid Kleckner9533af42016-01-16 00:09:09 +0000104StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
105 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000106 if (!Filepath.empty())
107 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000108
Reid Kleckner9533af42016-01-16 00:09:09 +0000109 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
110
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000111 // Clang emits directory and relative filename info into the IR, but CodeView
112 // operates on full paths. We could change Clang to emit full paths too, but
113 // that would increase the IR size and probably not needed for other users.
114 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000115 if (Filename.find(':') == 1)
116 Filepath = Filename;
117 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000118 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000119
120 // Canonicalize the path. We have to do it textually because we may no longer
121 // have access the file in the filesystem.
122 // First, replace all slashes with backslashes.
123 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
124
125 // Remove all "\.\" with "\".
126 size_t Cursor = 0;
127 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
128 Filepath.erase(Cursor, 2);
129
130 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
131 // path should be well-formatted, e.g. start with a drive letter, etc.
132 Cursor = 0;
133 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
134 // Something's wrong if the path starts with "\..\", abort.
135 if (Cursor == 0)
136 break;
137
138 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
139 if (PrevSlash == std::string::npos)
140 // Something's wrong, abort.
141 break;
142
143 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
144 // The next ".." might be following the one we've just erased.
145 Cursor = PrevSlash;
146 }
147
148 // Remove all duplicate backslashes.
149 Cursor = 0;
150 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
151 Filepath.erase(Cursor, 1);
152
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000153 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000154}
155
Reid Kleckner2214ed82016-01-29 00:49:42 +0000156unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
157 unsigned NextId = FileIdMap.size() + 1;
158 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
159 if (Insertion.second) {
160 // We have to compute the full filepath and emit a .cv_file directive.
161 StringRef FullPath = getFullFilepath(F);
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000162 std::string Checksum = fromHex(F->getChecksum());
163 void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
164 memcpy(CKMem, Checksum.data(), Checksum.size());
165 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
166 Checksum.size());
167 DIFile::ChecksumKind ChecksumKind = F->getChecksumKind();
168 bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
169 static_cast<unsigned>(ChecksumKind));
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000170 (void)Success;
171 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000172 }
173 return Insertion.first->second;
174}
175
Reid Kleckner876330d2016-02-12 21:48:30 +0000176CodeViewDebug::InlineSite &
177CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
178 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000179 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
180 InlineSite *Site = &SiteInsertion.first->second;
181 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000182 unsigned ParentFuncId = CurFn->FuncId;
183 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
184 ParentFuncId =
185 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
186 .SiteFuncId;
187
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000188 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000189 OS.EmitCVInlineSiteIdDirective(
190 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
191 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000192 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000193 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000194 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000195 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000196 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000197}
198
David Majnemer6bdc24e2016-07-01 23:12:45 +0000199static StringRef getPrettyScopeName(const DIScope *Scope) {
200 StringRef ScopeName = Scope->getName();
201 if (!ScopeName.empty())
202 return ScopeName;
203
204 switch (Scope->getTag()) {
205 case dwarf::DW_TAG_enumeration_type:
206 case dwarf::DW_TAG_class_type:
207 case dwarf::DW_TAG_structure_type:
208 case dwarf::DW_TAG_union_type:
209 return "<unnamed-tag>";
210 case dwarf::DW_TAG_namespace:
211 return "`anonymous namespace'";
212 }
213
214 return StringRef();
215}
216
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000217static const DISubprogram *getQualifiedNameComponents(
218 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
219 const DISubprogram *ClosestSubprogram = nullptr;
220 while (Scope != nullptr) {
221 if (ClosestSubprogram == nullptr)
222 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000223 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000224 if (!ScopeName.empty())
225 QualifiedNameComponents.push_back(ScopeName);
226 Scope = Scope->getScope().resolve();
227 }
228 return ClosestSubprogram;
229}
230
231static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
232 StringRef TypeName) {
233 std::string FullyQualifiedName;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000234 for (StringRef QualifiedNameComponent :
235 llvm::reverse(QualifiedNameComponents)) {
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000236 FullyQualifiedName.append(QualifiedNameComponent);
237 FullyQualifiedName.append("::");
238 }
239 FullyQualifiedName.append(TypeName);
240 return FullyQualifiedName;
241}
242
243static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
244 SmallVector<StringRef, 5> QualifiedNameComponents;
245 getQualifiedNameComponents(Scope, QualifiedNameComponents);
246 return getQualifiedName(QualifiedNameComponents, Name);
247}
248
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000249struct CodeViewDebug::TypeLoweringScope {
250 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
251 ~TypeLoweringScope() {
252 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
253 // inner TypeLoweringScopes don't attempt to emit deferred types.
254 if (CVD.TypeEmissionLevel == 1)
255 CVD.emitDeferredCompleteTypes();
256 --CVD.TypeEmissionLevel;
257 }
258 CodeViewDebug &CVD;
259};
260
David Majnemer6bdc24e2016-07-01 23:12:45 +0000261static std::string getFullyQualifiedName(const DIScope *Ty) {
262 const DIScope *Scope = Ty->getScope().resolve();
263 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
264}
265
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000266TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
267 // No scope means global scope and that uses the zero index.
268 if (!Scope || isa<DIFile>(Scope))
269 return TypeIndex();
270
271 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
272
273 // Check if we've already translated this scope.
274 auto I = TypeIndices.find({Scope, nullptr});
275 if (I != TypeIndices.end())
276 return I->second;
277
278 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000279 std::string ScopeName = getFullyQualifiedName(Scope);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000280 StringIdRecord SID(TypeIndex(), ScopeName);
281 auto TI = TypeTable.writeKnownType(SID);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000282 return recordTypeIndexForDINode(Scope, TI);
283}
284
David Majnemer75c3ebf2016-06-02 17:13:53 +0000285TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000286 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000287
David Majnemer75c3ebf2016-06-02 17:13:53 +0000288 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000289 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000290 if (I != TypeIndices.end())
291 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000292
Reid Klecknerac945e22016-06-17 16:11:20 +0000293 // The display name includes function template arguments. Drop them to match
294 // MSVC.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000295 StringRef DisplayName = SP->getName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000296
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000297 const DIScope *Scope = SP->getScope().resolve();
298 TypeIndex TI;
299 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
300 // If the scope is a DICompositeType, then this must be a method. Member
301 // function types take some special handling, and require access to the
302 // subprogram.
303 TypeIndex ClassType = getTypeIndex(Class);
304 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
305 DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000306 TI = TypeTable.writeKnownType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000307 } else {
308 // Otherwise, this must be a free function.
309 TypeIndex ParentScope = getScopeIndex(Scope);
310 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +0000311 TI = TypeTable.writeKnownType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000312 }
313
314 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000315}
316
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000317TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
318 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000319 // Always use the method declaration as the key for the function type. The
320 // method declaration contains the this adjustment.
321 if (SP->getDeclaration())
322 SP = SP->getDeclaration();
323 assert(!SP->getDeclaration() && "should use declaration as key");
324
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000325 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
326 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000327 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000328 if (I != TypeIndices.end())
329 return I->second;
330
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000331 // Make sure complete type info for the class is emitted *after* the member
332 // function type, as the complete class type is likely to reference this
333 // member function type.
334 TypeLoweringScope S(*this);
Adrian McCarthyd91bf392017-09-13 20:53:55 +0000335 const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
336 TypeIndex TI = lowerTypeMemberFunction(
337 SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000338 return recordTypeIndexForDINode(SP, TI, Class);
339}
340
Amjad Aboudacee5682016-07-12 12:06:34 +0000341TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
342 TypeIndex TI,
343 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000344 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000345 (void)InsertResult;
346 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000347 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000348}
349
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000350unsigned CodeViewDebug::getPointerSizeInBytes() {
351 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
352}
353
Reid Kleckner876330d2016-02-12 21:48:30 +0000354void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
355 const DILocation *InlinedAt) {
356 if (InlinedAt) {
357 // This variable was inlined. Associate it with the InlineSite.
358 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
359 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
360 Site.InlinedLocals.emplace_back(Var);
361 } else {
362 // This variable goes in the main ProcSym.
363 CurFn->Locals.emplace_back(Var);
364 }
365}
366
Reid Kleckner829365a2016-02-11 19:41:47 +0000367static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
368 const DILocation *Loc) {
369 auto B = Locs.begin(), E = Locs.end();
370 if (std::find(B, E, Loc) == E)
371 Locs.push_back(Loc);
372}
373
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000374void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000375 const MachineFunction *MF) {
376 // Skip this instruction if it has the same location as the previous one.
Reid Kleckner45a74622017-06-30 21:33:44 +0000377 if (!DL || DL == PrevInstLoc)
Reid Kleckner9533af42016-01-16 00:09:09 +0000378 return;
379
380 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000381 if (!Scope)
382 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000383
David Majnemerc3340db2016-01-13 01:05:23 +0000384 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000385 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
386 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
387 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000388 return;
389
Reid Kleckner2214ed82016-01-29 00:49:42 +0000390 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
391 if (CI.getStartColumn() != DL.getCol())
392 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000393
Reid Kleckner2214ed82016-01-29 00:49:42 +0000394 if (!CurFn->HaveLineInfo)
395 CurFn->HaveLineInfo = true;
396 unsigned FileId = 0;
Reid Kleckner45a74622017-06-30 21:33:44 +0000397 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
Reid Kleckner2214ed82016-01-29 00:49:42 +0000398 FileId = CurFn->LastFileId;
399 else
400 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
Reid Kleckner45a74622017-06-30 21:33:44 +0000401 PrevInstLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000402
403 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000404 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000405 const DILocation *Loc = DL.get();
406
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000407 // If this location was actually inlined from somewhere else, give it the ID
408 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000409 FuncId =
410 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000411
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000412 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000413 bool FirstLoc = true;
414 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000415 InlineSite &Site =
416 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000417 if (!FirstLoc)
418 addLocIfNotPresent(Site.ChildSites, Loc);
419 FirstLoc = false;
420 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000421 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000422 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000423 }
424
Reid Klecknerdac21b42016-02-03 21:15:48 +0000425 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000426 /*PrologueEnd=*/false, /*IsStmt=*/false,
427 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000428}
429
Reid Kleckner5d122f82016-05-25 23:16:12 +0000430void CodeViewDebug::emitCodeViewMagicVersion() {
431 OS.EmitValueToAlignment(4);
432 OS.AddComment("Debug section magic");
433 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
434}
435
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000436void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000437 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000438 return;
439
440 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000441
442 // The COFF .debug$S section consists of several subsections, each starting
443 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
444 // of the payload followed by the payload itself. The subsections are 4-byte
445 // aligned.
446
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000447 // Use the generic .debug$S section, and make a subsection for all the inlined
448 // subprograms.
449 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000450
Zachary Turner8c099fe2017-05-30 16:36:15 +0000451 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000452 emitCompilerInformation();
453 endCVSubsection(CompilerInfo);
454
Reid Kleckner5d122f82016-05-25 23:16:12 +0000455 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000456
Reid Kleckner2214ed82016-01-29 00:49:42 +0000457 // Emit per-function debug information.
458 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000459 if (!P.first->isDeclarationForLinker())
460 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000461
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000462 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000463 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000464 emitDebugInfoForGlobals();
465
Hans Wennborgb510b452016-06-23 16:33:53 +0000466 // Emit retained types.
467 emitDebugInfoForRetainedTypes();
468
Reid Kleckner5d122f82016-05-25 23:16:12 +0000469 // Switch back to the generic .debug$S section after potentially processing
470 // comdat symbol sections.
471 switchToDebugSectionForSymbol(nullptr);
472
David Majnemer3128b102016-06-15 18:00:01 +0000473 // Emit UDT records for any types used by global variables.
474 if (!GlobalUDTs.empty()) {
Zachary Turner8c099fe2017-05-30 16:36:15 +0000475 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
David Majnemer3128b102016-06-15 18:00:01 +0000476 emitDebugInfoForUDTs(GlobalUDTs);
477 endCVSubsection(SymbolsEnd);
478 }
479
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000480 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000481 OS.AddComment("File index to string table offset subsection");
482 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000483
484 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000485 OS.AddComment("String table");
486 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000487
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000488 // Emit type information last, so that any types we translate while emitting
489 // function info are included.
490 emitTypeInformation();
491
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000492 clear();
493}
494
David Majnemerb9456a52016-03-14 05:15:09 +0000495static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000496 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
497 // after a fixed length portion of the record. The fixed length portion should
498 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
499 // overall record size is less than the maximum allowed.
500 unsigned MaxFixedRecordLength = 0xF00;
501 SmallString<32> NullTerminatedString(
502 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000503 NullTerminatedString.push_back('\0');
504 OS.EmitBytes(NullTerminatedString);
505}
506
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000507void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000508 // Do nothing if we have no debug info or if no non-trivial types were emitted
509 // to TypeTable during codegen.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000510 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
Reid Klecknerfbd77872016-03-18 18:54:32 +0000511 if (!CU_Nodes)
512 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000513 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000514 return;
515
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000516 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000517 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000518 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000519
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000520 SmallString<8> CommentPrefix;
521 if (OS.isVerboseAsm()) {
522 CommentPrefix += '\t';
523 CommentPrefix += Asm->MAI->getCommentString();
524 CommentPrefix += ' ';
525 }
526
Zachary Turner526f4f22017-05-19 19:26:58 +0000527 TypeTableCollection Table(TypeTable.records());
528 Optional<TypeIndex> B = Table.getFirst();
529 while (B) {
530 // This will fail if the record data is invalid.
531 CVType Record = Table.getType(*B);
532
Zachary Turner4efa0a42016-11-08 22:24:53 +0000533 if (OS.isVerboseAsm()) {
534 // Emit a block comment describing the type record for readability.
535 SmallString<512> CommentBlock;
536 raw_svector_ostream CommentOS(CommentBlock);
537 ScopedPrinter SP(CommentOS);
538 SP.setPrefix(CommentPrefix);
Zachary Turner526f4f22017-05-19 19:26:58 +0000539 TypeDumpVisitor TDV(Table, &SP, false);
540
541 Error E = codeview::visitTypeRecord(Record, *B, TDV);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000542 if (E) {
543 logAllUnhandledErrors(std::move(E), errs(), "error: ");
544 llvm_unreachable("produced malformed type record");
545 }
546 // emitRawComment will insert its own tab and comment string before
547 // the first line, so strip off our first one. It also prints its own
548 // newline.
549 OS.emitRawComment(
550 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Zachary Turner4efa0a42016-11-08 22:24:53 +0000551 }
Zachary Turner526f4f22017-05-19 19:26:58 +0000552 OS.EmitBinaryData(Record.str_data());
553 B = Table.getNext(*B);
554 }
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000555}
556
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000557static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
558 switch (DWLang) {
559 case dwarf::DW_LANG_C:
560 case dwarf::DW_LANG_C89:
561 case dwarf::DW_LANG_C99:
562 case dwarf::DW_LANG_C11:
563 case dwarf::DW_LANG_ObjC:
564 return SourceLanguage::C;
565 case dwarf::DW_LANG_C_plus_plus:
566 case dwarf::DW_LANG_C_plus_plus_03:
567 case dwarf::DW_LANG_C_plus_plus_11:
568 case dwarf::DW_LANG_C_plus_plus_14:
569 return SourceLanguage::Cpp;
570 case dwarf::DW_LANG_Fortran77:
571 case dwarf::DW_LANG_Fortran90:
572 case dwarf::DW_LANG_Fortran03:
573 case dwarf::DW_LANG_Fortran08:
574 return SourceLanguage::Fortran;
575 case dwarf::DW_LANG_Pascal83:
576 return SourceLanguage::Pascal;
577 case dwarf::DW_LANG_Cobol74:
578 case dwarf::DW_LANG_Cobol85:
579 return SourceLanguage::Cobol;
580 case dwarf::DW_LANG_Java:
581 return SourceLanguage::Java;
Reid Kleckner898ddf62017-07-24 16:16:42 +0000582 case dwarf::DW_LANG_D:
583 return SourceLanguage::D;
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000584 default:
585 // There's no CodeView representation for this language, and CV doesn't
586 // have an "unknown" option for the language field, so we'll use MASM,
587 // as it's very low level.
588 return SourceLanguage::Masm;
589 }
590}
591
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000592namespace {
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000593struct Version {
594 int Part[4];
595};
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000596} // end anonymous namespace
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000597
598// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
599// the version number.
600static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000601 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000602 int N = 0;
603 for (const char C : Name) {
604 if (isdigit(C)) {
605 V.Part[N] *= 10;
606 V.Part[N] += C - '0';
607 } else if (C == '.') {
608 ++N;
609 if (N >= 4)
610 return V;
611 } else if (N > 0)
612 return V;
613 }
614 return V;
615}
616
617static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
618 switch (Type) {
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000619 case Triple::ArchType::x86:
620 return CPUType::Pentium3;
621 case Triple::ArchType::x86_64:
622 return CPUType::X64;
623 case Triple::ArchType::thumb:
624 return CPUType::Thumb;
625 case Triple::ArchType::aarch64:
626 return CPUType::ARM64;
627 default:
628 report_fatal_error("target architecture doesn't map to a CodeView CPUType");
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000629 }
630}
631
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000632void CodeViewDebug::emitCompilerInformation() {
633 MCContext &Context = MMI->getContext();
634 MCSymbol *CompilerBegin = Context.createTempSymbol(),
635 *CompilerEnd = Context.createTempSymbol();
636 OS.AddComment("Record length");
637 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
638 OS.EmitLabel(CompilerBegin);
639 OS.AddComment("Record kind: S_COMPILE3");
640 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
641 uint32_t Flags = 0;
642
643 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
644 const MDNode *Node = *CUs->operands().begin();
645 const auto *CU = cast<DICompileUnit>(Node);
646
647 // The low byte of the flags indicates the source language.
648 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
649 // TODO: Figure out which other flags need to be set.
650
651 OS.AddComment("Flags and language");
652 OS.EmitIntValue(Flags, 4);
653
654 OS.AddComment("CPUType");
655 CPUType CPU =
656 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
657 OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
658
659 StringRef CompilerVersion = CU->getProducer();
660 Version FrontVer = parseVersion(CompilerVersion);
661 OS.AddComment("Frontend version");
662 for (int N = 0; N < 4; ++N)
663 OS.EmitIntValue(FrontVer.Part[N], 2);
664
665 // Some Microsoft tools, like Binscope, expect a backend version number of at
666 // least 8.something, so we'll coerce the LLVM version into a form that
667 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000668 int Major = 1000 * LLVM_VERSION_MAJOR +
669 10 * LLVM_VERSION_MINOR +
670 LLVM_VERSION_PATCH;
671 // Clamp it for builds that use unusually large version numbers.
672 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
673 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000674 OS.AddComment("Backend version");
675 for (int N = 0; N < 4; ++N)
676 OS.EmitIntValue(BackVer.Part[N], 2);
677
678 OS.AddComment("Null-terminated compiler version string");
679 emitNullTerminatedSymbolName(OS, CompilerVersion);
680
681 OS.EmitLabel(CompilerEnd);
682}
683
Reid Kleckner5d122f82016-05-25 23:16:12 +0000684void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000685 if (InlinedSubprograms.empty())
686 return;
687
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000688 OS.AddComment("Inlinee lines subsection");
Zachary Turner8c099fe2017-05-30 16:36:15 +0000689 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000690
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000691 // We emit the checksum info for files. This is used by debuggers to
692 // determine if a pdb matches the source before loading it. Visual Studio,
693 // for instance, will display a warning that the breakpoints are not valid if
694 // the pdb does not match the source.
David Majnemer30579ec2016-02-02 23:18:23 +0000695 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000696 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
697
698 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000699 assert(TypeIndices.count({SP, nullptr}));
700 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000701
David Majnemer30579ec2016-02-02 23:18:23 +0000702 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000703 unsigned FileId = maybeRecordFile(SP->getFile());
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000704 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000705 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000706 OS.AddBlankLine();
David Majnemer30579ec2016-02-02 23:18:23 +0000707 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000708 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000709 OS.AddComment("Offset into filechecksum table");
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000710 OS.EmitCVFileChecksumOffsetDirective(FileId);
David Majnemer30579ec2016-02-02 23:18:23 +0000711 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000712 OS.EmitIntValue(SP->getLine(), 4);
713 }
714
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000715 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000716}
717
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000718void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
719 const DILocation *InlinedAt,
720 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000721 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
722 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000723
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000724 assert(TypeIndices.count({Site.Inlinee, nullptr}));
725 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000726
727 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000728 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000729 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000730 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000731 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000732 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000733
Reid Klecknerdac21b42016-02-03 21:15:48 +0000734 OS.AddComment("PtrParent");
735 OS.EmitIntValue(0, 4);
736 OS.AddComment("PtrEnd");
737 OS.EmitIntValue(0, 4);
738 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000739 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000740
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000741 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
742 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000743
744 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000745 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000746
747 OS.EmitLabel(InlineEnd);
748
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000749 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000750
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000751 // Recurse on child inlined call sites before closing the scope.
752 for (const DILocation *ChildSite : Site.ChildSites) {
753 auto I = FI.InlineSites.find(ChildSite);
754 assert(I != FI.InlineSites.end() &&
755 "child site not in function inline site map");
756 emitInlinedCallSite(FI, ChildSite, I->second);
757 }
758
759 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000760 OS.AddComment("Record length");
761 OS.EmitIntValue(2, 2); // RecordLength
762 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000763 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000764}
765
Reid Kleckner5d122f82016-05-25 23:16:12 +0000766void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
767 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
768 // comdat key. A section may be comdat because of -ffunction-sections or
769 // because it is comdat in the IR.
770 MCSectionCOFF *GVSec =
771 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
772 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
773
774 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
775 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
776 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
777
778 OS.SwitchSection(DebugSec);
779
780 // Emit the magic version number if this is the first time we've switched to
781 // this section.
782 if (ComdatDebugSections.insert(DebugSec).second)
783 emitCodeViewMagicVersion();
784}
785
Reid Kleckner2214ed82016-01-29 00:49:42 +0000786void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
787 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000788 // For each function there is a separate subsection
789 // which holds the PC to file:line table.
790 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000791 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000792
Reid Kleckner5d122f82016-05-25 23:16:12 +0000793 // Switch to the to a comdat section, if appropriate.
794 switchToDebugSectionForSymbol(Fn);
795
Reid Klecknerac945e22016-06-17 16:11:20 +0000796 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000797 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000798 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000799 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000800
801 // If we have a display name, build the fully qualified name by walking the
802 // chain of scopes.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000803 if (!SP->getName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000804 FuncName =
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000805 getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000806
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000807 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000808 if (FuncName.empty())
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +0000809 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000810
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000811 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000812 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Zachary Turner8c099fe2017-05-30 16:36:15 +0000813 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000814 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000815 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
816 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000817 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000818 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000819 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000820
Reid Kleckner4ad127f2016-09-14 21:49:21 +0000821 if (GV->hasLocalLinkage()) {
822 OS.AddComment("Record kind: S_LPROC32_ID");
823 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
824 } else {
825 OS.AddComment("Record kind: S_GPROC32_ID");
826 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
827 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000828
David Majnemer30579ec2016-02-02 23:18:23 +0000829 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000830 OS.AddComment("PtrParent");
831 OS.EmitIntValue(0, 4);
832 OS.AddComment("PtrEnd");
833 OS.EmitIntValue(0, 4);
834 OS.AddComment("PtrNext");
835 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000836 // This is the important bit that tells the debugger where the function
837 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000838 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000839 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000840 OS.AddComment("Offset after prologue");
841 OS.EmitIntValue(0, 4);
842 OS.AddComment("Offset before epilogue");
843 OS.EmitIntValue(0, 4);
844 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000845 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000846 OS.AddComment("Function section relative address");
Keno Fischerf7d84ee2017-01-02 03:00:19 +0000847 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000848 OS.AddComment("Function section index");
849 OS.EmitCOFFSectionIndex(Fn);
850 OS.AddComment("Flags");
851 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000852 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000853 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000854 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000855 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000856 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000857
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000858 emitLocalVariableList(FI.Locals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000859
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000860 // Emit inlined call site information. Only emit functions inlined directly
861 // into the parent function. We'll emit the other sites recursively as part
862 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000863 for (const DILocation *InlinedAt : FI.ChildSites) {
864 auto I = FI.InlineSites.find(InlinedAt);
865 assert(I != FI.InlineSites.end() &&
866 "child site not in function inline site map");
867 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000868 }
869
Reid Klecknere33c94f2017-09-05 20:14:58 +0000870 for (auto Annot : FI.Annotations) {
871 MCSymbol *Label = Annot.first;
872 MDTuple *Strs = cast<MDTuple>(Annot.second);
873 MCSymbol *AnnotBegin = MMI->getContext().createTempSymbol(),
874 *AnnotEnd = MMI->getContext().createTempSymbol();
875 OS.AddComment("Record length");
876 OS.emitAbsoluteSymbolDiff(AnnotEnd, AnnotBegin, 2);
877 OS.EmitLabel(AnnotBegin);
878 OS.AddComment("Record kind: S_ANNOTATION");
879 OS.EmitIntValue(SymbolKind::S_ANNOTATION, 2);
880 OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
881 // FIXME: Make sure we don't overflow the max record size.
882 OS.EmitCOFFSectionIndex(Label);
883 OS.EmitIntValue(Strs->getNumOperands(), 2);
884 for (Metadata *MD : Strs->operands()) {
885 // MDStrings are null terminated, so we can do EmitBytes and get the
886 // nice .asciz directive.
887 StringRef Str = cast<MDString>(MD)->getString();
888 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
889 OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
890 }
891 OS.EmitLabel(AnnotEnd);
892 }
893
David Majnemer3128b102016-06-15 18:00:01 +0000894 if (SP != nullptr)
895 emitDebugInfoForUDTs(LocalUDTs);
896
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000897 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000898 OS.AddComment("Record length");
899 OS.EmitIntValue(0x0002, 2);
900 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000901 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000902 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000903 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000904
Reid Kleckner2214ed82016-01-29 00:49:42 +0000905 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000906 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000907}
908
Reid Kleckner876330d2016-02-12 21:48:30 +0000909CodeViewDebug::LocalVarDefRange
910CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
911 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000912 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000913 DR.DataOffset = Offset;
914 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000915 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000916 DR.StructOffset = 0;
917 DR.CVRegister = CVRegister;
918 return DR;
919}
920
921CodeViewDebug::LocalVarDefRange
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000922CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
923 int Offset, bool IsSubfield,
924 uint16_t StructOffset) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000925 LocalVarDefRange DR;
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000926 DR.InMemory = InMemory;
927 DR.DataOffset = Offset;
928 DR.IsSubfield = IsSubfield;
929 DR.StructOffset = StructOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +0000930 DR.CVRegister = CVRegister;
931 return DR;
932}
933
Matthias Braunef331ef2016-11-30 23:48:50 +0000934void CodeViewDebug::collectVariableInfoFromMFTable(
Reid Kleckner876330d2016-02-12 21:48:30 +0000935 DenseSet<InlinedVariable> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +0000936 const MachineFunction &MF = *Asm->MF;
937 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +0000938 const TargetFrameLowering *TFI = TSI.getFrameLowering();
939 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
940
Matthias Braunef331ef2016-11-30 23:48:50 +0000941 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000942 if (!VI.Var)
943 continue;
944 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
945 "Expected inlined-at fields to agree");
946
Reid Kleckner876330d2016-02-12 21:48:30 +0000947 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000948 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
949
950 // If variable scope is not found then skip this variable.
951 if (!Scope)
952 continue;
953
Reid Klecknerb5fced72017-05-09 19:59:29 +0000954 // If the variable has an attached offset expression, extract it.
955 // FIXME: Try to handle DW_OP_deref as well.
956 int64_t ExprOffset = 0;
957 if (VI.Expr)
958 if (!VI.Expr->extractIfOffset(ExprOffset))
959 continue;
960
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000961 // Get the frame register used and the offset.
962 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000963 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
964 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000965
966 // Calculate the label ranges.
Reid Klecknerb5fced72017-05-09 19:59:29 +0000967 LocalVarDefRange DefRange =
968 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000969 for (const InsnRange &Range : Scope->getRanges()) {
970 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
971 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000972 End = End ? End : Asm->getFunctionEnd();
973 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000974 }
975
Reid Kleckner876330d2016-02-12 21:48:30 +0000976 LocalVariable Var;
977 Var.DIVar = VI.Var;
978 Var.DefRanges.emplace_back(std::move(DefRange));
979 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
980 }
981}
982
Reid Kleckner08f5fd52017-08-31 15:56:49 +0000983static bool canUseReferenceType(const DbgVariableLocation &Loc) {
984 return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
985}
986
987static bool needsReferenceType(const DbgVariableLocation &Loc) {
988 return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
989}
990
Bob Haarman223303c2017-08-29 20:59:25 +0000991void CodeViewDebug::calculateRanges(
992 LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
993 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
994
Reid Kleckner08f5fd52017-08-31 15:56:49 +0000995 // Calculate the definition ranges.
Bob Haarman223303c2017-08-29 20:59:25 +0000996 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
997 const InsnRange &Range = *I;
998 const MachineInstr *DVInst = Range.first;
999 assert(DVInst->isDebugValue() && "Invalid History entry");
1000 // FIXME: Find a way to represent constant variables, since they are
1001 // relatively common.
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001002 Optional<DbgVariableLocation> Location =
1003 DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1004 if (!Location)
Bob Haarmana88bce12017-08-29 21:01:55 +00001005 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001006
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001007 // CodeView can only express variables in register and variables in memory
1008 // at a constant offset from a register. However, for variables passed
1009 // indirectly by pointer, it is common for that pointer to be spilled to a
1010 // stack location. For the special case of one offseted load followed by a
1011 // zero offset load (a pointer spilled to the stack), we change the type of
1012 // the local variable from a value type to a reference type. This tricks the
1013 // debugger into doing the load for us.
1014 if (Var.UseReferenceType) {
1015 // We're using a reference type. Drop the last zero offset load.
1016 if (canUseReferenceType(*Location))
1017 Location->LoadChain.pop_back();
1018 else
1019 continue;
1020 } else if (needsReferenceType(*Location)) {
1021 // This location can't be expressed without switching to a reference type.
1022 // Start over using that.
1023 Var.UseReferenceType = true;
Bob Haarman223303c2017-08-29 20:59:25 +00001024 Var.DefRanges.clear();
1025 calculateRanges(Var, Ranges);
1026 return;
1027 }
1028
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001029 // We can only handle a register or an offseted load of a register.
1030 if (Location->Register == 0 || Location->LoadChain.size() > 1)
Bob Haarman223303c2017-08-29 20:59:25 +00001031 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001032 {
1033 LocalVarDefRange DR;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001034 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001035 DR.InMemory = !Location->LoadChain.empty();
1036 DR.DataOffset =
1037 !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001038 if (Location->FragmentInfo) {
Bob Haarman223303c2017-08-29 20:59:25 +00001039 DR.IsSubfield = true;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001040 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
Bob Haarman223303c2017-08-29 20:59:25 +00001041 } else {
1042 DR.IsSubfield = false;
1043 DR.StructOffset = 0;
1044 }
1045
1046 if (Var.DefRanges.empty() ||
1047 Var.DefRanges.back().isDifferentLocation(DR)) {
1048 Var.DefRanges.emplace_back(std::move(DR));
1049 }
1050 }
1051
1052 // Compute the label range.
1053 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1054 const MCSymbol *End = getLabelAfterInsn(Range.second);
1055 if (!End) {
1056 // This range is valid until the next overlapping bitpiece. In the
1057 // common case, ranges will not be bitpieces, so they will overlap.
1058 auto J = std::next(I);
1059 const DIExpression *DIExpr = DVInst->getDebugExpression();
1060 while (J != E &&
1061 !fragmentsOverlap(DIExpr, J->first->getDebugExpression()))
1062 ++J;
1063 if (J != E)
1064 End = getLabelBeforeInsn(J->first);
1065 else
1066 End = Asm->getFunctionEnd();
1067 }
1068
1069 // If the last range end is our begin, just extend the last range.
1070 // Otherwise make a new range.
1071 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1072 Var.DefRanges.back().Ranges;
1073 if (!R.empty() && R.back().second == Begin)
1074 R.back().second = End;
1075 else
1076 R.emplace_back(Begin, End);
1077
1078 // FIXME: Do more range combining.
1079 }
1080}
1081
Reid Kleckner876330d2016-02-12 21:48:30 +00001082void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1083 DenseSet<InlinedVariable> Processed;
1084 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +00001085 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +00001086
Reid Kleckner876330d2016-02-12 21:48:30 +00001087 for (const auto &I : DbgValues) {
1088 InlinedVariable IV = I.first;
1089 if (Processed.count(IV))
1090 continue;
1091 const DILocalVariable *DIVar = IV.first;
1092 const DILocation *InlinedAt = IV.second;
1093
1094 // Instruction ranges, specifying where IV is accessible.
1095 const auto &Ranges = I.second;
1096
1097 LexicalScope *Scope = nullptr;
1098 if (InlinedAt)
1099 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1100 else
1101 Scope = LScopes.findLexicalScope(DIVar->getScope());
1102 // If variable scope is not found then skip this variable.
1103 if (!Scope)
1104 continue;
1105
1106 LocalVariable Var;
1107 Var.DIVar = DIVar;
1108
Bob Haarman223303c2017-08-29 20:59:25 +00001109 calculateRanges(Var, Ranges);
Reid Kleckner876330d2016-02-12 21:48:30 +00001110 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001111 }
1112}
1113
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001114void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001115 const Function *GV = MF->getFunction();
1116 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001117 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +00001118 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001119 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001120
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001121 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1122
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001123 // Find the end of the function prolog. First known non-DBG_VALUE and
1124 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001125 // FIXME: is there a simpler a way to do this? Can we just search
1126 // for the first instruction of the function, not the last of the prolog?
1127 DebugLoc PrologEndLoc;
1128 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001129 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001130 for (const auto &MI : MBB) {
Adrian Prantlfb31da12017-05-22 20:47:09 +00001131 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001132 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001133 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001134 break;
Adrian Prantlfb31da12017-05-22 20:47:09 +00001135 } else if (!MI.isMetaInstruction()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001136 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001137 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001138 }
1139 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001140
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001141 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001142 if (PrologEndLoc && !EmptyPrologue) {
1143 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001144 maybeRecordLocation(FnStartDL, MF);
1145 }
1146}
1147
Zachary Turnera7b04172017-08-28 18:49:04 +00001148static bool shouldEmitUdt(const DIType *T) {
Zachary Turner37c74742017-09-05 22:06:39 +00001149 if (!T)
1150 return false;
1151
1152 // MSVC does not emit UDTs for typedefs that are scoped to classes.
1153 if (T->getTag() == dwarf::DW_TAG_typedef) {
1154 if (DIScope *Scope = T->getScope().resolve()) {
1155 switch (Scope->getTag()) {
1156 case dwarf::DW_TAG_structure_type:
1157 case dwarf::DW_TAG_class_type:
1158 case dwarf::DW_TAG_union_type:
1159 return false;
1160 }
1161 }
1162 }
1163
Zachary Turnera7b04172017-08-28 18:49:04 +00001164 while (true) {
1165 if (!T || T->isForwardDecl())
1166 return false;
1167
1168 const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1169 if (!DT)
1170 return true;
1171 T = DT->getBaseType().resolve();
1172 }
1173 return true;
1174}
1175
1176void CodeViewDebug::addToUDTs(const DIType *Ty) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001177 // Don't record empty UDTs.
1178 if (Ty->getName().empty())
1179 return;
Zachary Turnera7b04172017-08-28 18:49:04 +00001180 if (!shouldEmitUdt(Ty))
1181 return;
Reid Klecknerad56ea32016-07-01 22:24:51 +00001182
Hans Wennborg4b63a982016-06-23 22:57:25 +00001183 SmallVector<StringRef, 5> QualifiedNameComponents;
1184 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1185 Ty->getScope().resolve(), QualifiedNameComponents);
1186
1187 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001188 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001189
Zachary Turnera7b04172017-08-28 18:49:04 +00001190 if (ClosestSubprogram == nullptr) {
1191 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1192 } else if (ClosestSubprogram == CurrentSubprogram) {
1193 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1194 }
Hans Wennborg4b63a982016-06-23 22:57:25 +00001195
1196 // TODO: What if the ClosestSubprogram is neither null or the current
1197 // subprogram? Currently, the UDT just gets dropped on the floor.
1198 //
1199 // The current behavior is not desirable. To get maximal fidelity, we would
1200 // need to perform all type translation before beginning emission of .debug$S
1201 // and then make LocalUDTs a member of FunctionInfo
1202}
1203
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001204TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001205 // Generic dispatch for lowering an unknown type.
1206 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001207 case dwarf::DW_TAG_array_type:
1208 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001209 case dwarf::DW_TAG_typedef:
1210 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001211 case dwarf::DW_TAG_base_type:
1212 return lowerTypeBasic(cast<DIBasicType>(Ty));
1213 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001214 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1215 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1216 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001217 case dwarf::DW_TAG_reference_type:
1218 case dwarf::DW_TAG_rvalue_reference_type:
1219 return lowerTypePointer(cast<DIDerivedType>(Ty));
1220 case dwarf::DW_TAG_ptr_to_member_type:
1221 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1222 case dwarf::DW_TAG_const_type:
1223 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001224 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001225 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001226 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001227 if (ClassTy) {
1228 // The member function type of a member function pointer has no
1229 // ThisAdjustment.
1230 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001231 /*ThisAdjustment=*/0,
1232 /*IsStaticMethod=*/false);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001233 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001234 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001235 case dwarf::DW_TAG_enumeration_type:
1236 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001237 case dwarf::DW_TAG_class_type:
1238 case dwarf::DW_TAG_structure_type:
1239 return lowerTypeClass(cast<DICompositeType>(Ty));
1240 case dwarf::DW_TAG_union_type:
1241 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001242 default:
1243 // Use the null type index.
1244 return TypeIndex();
1245 }
1246}
1247
David Majnemerd065e232016-06-02 06:21:37 +00001248TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001249 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1250 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001251 StringRef TypeName = Ty->getName();
1252
Zachary Turnera7b04172017-08-28 18:49:04 +00001253 addToUDTs(Ty);
David Majnemer3128b102016-06-15 18:00:01 +00001254
David Majnemerd065e232016-06-02 06:21:37 +00001255 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001256 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001257 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001258 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001259 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001260 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001261
David Majnemerd065e232016-06-02 06:21:37 +00001262 return UnderlyingTypeIndex;
1263}
1264
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001265TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1266 DITypeRef ElementTypeRef = Ty->getBaseType();
1267 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1268 // IndexType is size_t, which depends on the bitness of the target.
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001269 TypeIndex IndexType = Asm->TM.getPointerSize() == 8
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001270 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1271 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001272
1273 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1274
Amjad Aboudacee5682016-07-12 12:06:34 +00001275 // Add subranges to array type.
1276 DINodeArray Elements = Ty->getElements();
1277 for (int i = Elements.size() - 1; i >= 0; --i) {
1278 const DINode *Element = Elements[i];
1279 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1280
1281 const DISubrange *Subrange = cast<DISubrange>(Element);
1282 assert(Subrange->getLowerBound() == 0 &&
1283 "codeview doesn't support subranges with lower bounds");
1284 int64_t Count = Subrange->getCount();
1285
Reid Klecknercd7bba02017-09-13 23:30:01 +00001286 // Forward declarations of arrays without a size and VLAs use a count of -1.
1287 // Emit a count of zero in these cases to match what MSVC does for arrays
1288 // without a size. MSVC doesn't support VLAs, so it's not clear what we
1289 // should do for them even if we could distinguish them.
Reid Kleckner6b78e162017-03-24 23:28:42 +00001290 if (Count == -1)
Reid Kleckner89af1122017-09-13 21:54:20 +00001291 Count = 0;
Amjad Aboudacee5682016-07-12 12:06:34 +00001292
Amjad Aboudacee5682016-07-12 12:06:34 +00001293 // Update the element size and element type index for subsequent subranges.
1294 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001295
1296 // If this is the outermost array, use the size from the array. It will be
Reid Kleckner6b78e162017-03-24 23:28:42 +00001297 // more accurate if we had a VLA or an incomplete element type size.
Reid Kleckner10762882016-09-09 17:29:36 +00001298 uint64_t ArraySize =
1299 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1300
1301 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001302 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1303 ElementTypeIndex = TypeTable.writeKnownType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001304 }
1305
Amjad Aboudacee5682016-07-12 12:06:34 +00001306 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001307}
1308
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001309TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1310 TypeIndex Index;
1311 dwarf::TypeKind Kind;
1312 uint32_t ByteSize;
1313
1314 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001315 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001316
1317 SimpleTypeKind STK = SimpleTypeKind::None;
1318 switch (Kind) {
1319 case dwarf::DW_ATE_address:
1320 // FIXME: Translate
1321 break;
1322 case dwarf::DW_ATE_boolean:
1323 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001324 case 1: STK = SimpleTypeKind::Boolean8; break;
1325 case 2: STK = SimpleTypeKind::Boolean16; break;
1326 case 4: STK = SimpleTypeKind::Boolean32; break;
1327 case 8: STK = SimpleTypeKind::Boolean64; break;
1328 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001329 }
1330 break;
1331 case dwarf::DW_ATE_complex_float:
1332 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001333 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001334 case 4: STK = SimpleTypeKind::Complex32; break;
1335 case 8: STK = SimpleTypeKind::Complex64; break;
1336 case 10: STK = SimpleTypeKind::Complex80; break;
1337 case 16: STK = SimpleTypeKind::Complex128; break;
1338 }
1339 break;
1340 case dwarf::DW_ATE_float:
1341 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001342 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001343 case 4: STK = SimpleTypeKind::Float32; break;
1344 case 6: STK = SimpleTypeKind::Float48; break;
1345 case 8: STK = SimpleTypeKind::Float64; break;
1346 case 10: STK = SimpleTypeKind::Float80; break;
1347 case 16: STK = SimpleTypeKind::Float128; break;
1348 }
1349 break;
1350 case dwarf::DW_ATE_signed:
1351 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001352 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1353 case 2: STK = SimpleTypeKind::Int16Short; break;
1354 case 4: STK = SimpleTypeKind::Int32; break;
1355 case 8: STK = SimpleTypeKind::Int64Quad; break;
1356 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001357 }
1358 break;
1359 case dwarf::DW_ATE_unsigned:
1360 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001361 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1362 case 2: STK = SimpleTypeKind::UInt16Short; break;
1363 case 4: STK = SimpleTypeKind::UInt32; break;
1364 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1365 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001366 }
1367 break;
1368 case dwarf::DW_ATE_UTF:
1369 switch (ByteSize) {
1370 case 2: STK = SimpleTypeKind::Character16; break;
1371 case 4: STK = SimpleTypeKind::Character32; break;
1372 }
1373 break;
1374 case dwarf::DW_ATE_signed_char:
1375 if (ByteSize == 1)
1376 STK = SimpleTypeKind::SignedCharacter;
1377 break;
1378 case dwarf::DW_ATE_unsigned_char:
1379 if (ByteSize == 1)
1380 STK = SimpleTypeKind::UnsignedCharacter;
1381 break;
1382 default:
1383 break;
1384 }
1385
1386 // Apply some fixups based on the source-level type name.
1387 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1388 STK = SimpleTypeKind::Int32Long;
1389 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1390 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001391 if (STK == SimpleTypeKind::UInt16Short &&
1392 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001393 STK = SimpleTypeKind::WideCharacter;
1394 if ((STK == SimpleTypeKind::SignedCharacter ||
1395 STK == SimpleTypeKind::UnsignedCharacter) &&
1396 Ty->getName() == "char")
1397 STK = SimpleTypeKind::NarrowCharacter;
1398
1399 return TypeIndex(STK);
1400}
1401
1402TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1403 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1404
1405 // Pointers to simple types can use SimpleTypeMode, rather than having a
1406 // dedicated pointer type record.
1407 if (PointeeTI.isSimple() &&
1408 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1409 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1410 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1411 ? SimpleTypeMode::NearPointer64
1412 : SimpleTypeMode::NearPointer32;
1413 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1414 }
1415
1416 PointerKind PK =
1417 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1418 PointerMode PM = PointerMode::Pointer;
1419 switch (Ty->getTag()) {
1420 default: llvm_unreachable("not a pointer tag type");
1421 case dwarf::DW_TAG_pointer_type:
1422 PM = PointerMode::Pointer;
1423 break;
1424 case dwarf::DW_TAG_reference_type:
1425 PM = PointerMode::LValueReference;
1426 break;
1427 case dwarf::DW_TAG_rvalue_reference_type:
1428 PM = PointerMode::RValueReference;
1429 break;
1430 }
1431 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1432 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1433 // do.
1434 PointerOptions PO = PointerOptions::None;
1435 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001436 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001437}
1438
Reid Kleckner6fa15462016-06-17 22:14:39 +00001439static PointerToMemberRepresentation
1440translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1441 // SizeInBytes being zero generally implies that the member pointer type was
1442 // incomplete, which can happen if it is part of a function prototype. In this
1443 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001444 if (IsPMF) {
1445 switch (Flags & DINode::FlagPtrToMemberRep) {
1446 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001447 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1448 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001449 case DINode::FlagSingleInheritance:
1450 return PointerToMemberRepresentation::SingleInheritanceFunction;
1451 case DINode::FlagMultipleInheritance:
1452 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1453 case DINode::FlagVirtualInheritance:
1454 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1455 }
1456 } else {
1457 switch (Flags & DINode::FlagPtrToMemberRep) {
1458 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001459 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1460 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001461 case DINode::FlagSingleInheritance:
1462 return PointerToMemberRepresentation::SingleInheritanceData;
1463 case DINode::FlagMultipleInheritance:
1464 return PointerToMemberRepresentation::MultipleInheritanceData;
1465 case DINode::FlagVirtualInheritance:
1466 return PointerToMemberRepresentation::VirtualInheritanceData;
1467 }
1468 }
1469 llvm_unreachable("invalid ptr to member representation");
1470}
1471
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001472TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1473 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1474 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001475 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001476 PointerKind PK = Asm->TM.getPointerSize() == 8 ? PointerKind::Near64
1477 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001478 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1479 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1480 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001481 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001482 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1483 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1484 MemberPointerInfo MPI(
1485 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001486 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001487 return TypeTable.writeKnownType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001488}
1489
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001490/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1491/// have a translation, use the NearC convention.
1492static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1493 switch (DwarfCC) {
1494 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1495 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1496 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1497 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1498 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1499 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1500 }
1501 return CallingConvention::NearC;
1502}
1503
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001504TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1505 ModifierOptions Mods = ModifierOptions::None;
1506 bool IsModifier = true;
1507 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001508 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001509 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001510 switch (BaseTy->getTag()) {
1511 case dwarf::DW_TAG_const_type:
1512 Mods |= ModifierOptions::Const;
1513 break;
1514 case dwarf::DW_TAG_volatile_type:
1515 Mods |= ModifierOptions::Volatile;
1516 break;
1517 default:
1518 IsModifier = false;
1519 break;
1520 }
1521 if (IsModifier)
1522 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1523 }
1524 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001525 ModifierRecord MR(ModifiedTI, Mods);
1526 return TypeTable.writeKnownType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001527}
1528
David Majnemer75c3ebf2016-06-02 17:13:53 +00001529TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1530 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1531 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1532 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1533
1534 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1535 ArrayRef<TypeIndex> ArgTypeIndices = None;
1536 if (!ReturnAndArgTypeIndices.empty()) {
1537 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1538 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1539 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1540 }
1541
1542 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001543 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001544
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001545 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1546
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001547 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1548 ArgTypeIndices.size(), ArgListIndex);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001549 return TypeTable.writeKnownType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001550}
1551
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001552TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001553 const DIType *ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001554 int ThisAdjustment,
1555 bool IsStaticMethod) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001556 // Lower the containing class type.
1557 TypeIndex ClassType = getTypeIndex(ClassTy);
1558
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001559 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1560 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1561 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1562
1563 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1564 ArrayRef<TypeIndex> ArgTypeIndices = None;
1565 if (!ReturnAndArgTypeIndices.empty()) {
1566 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1567 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1568 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1569 }
Reid Kleckner87288b92017-09-15 00:59:07 +00001570 TypeIndex ThisTypeIndex;
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001571 if (!IsStaticMethod && !ArgTypeIndices.empty()) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001572 ThisTypeIndex = ArgTypeIndices.front();
1573 ArgTypeIndices = ArgTypeIndices.drop_front();
1574 }
1575
1576 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00001577 TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001578
1579 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1580
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001581 // TODO: Need to use the correct values for FunctionOptions.
Zachary Turner4efa0a42016-11-08 22:24:53 +00001582 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1583 FunctionOptions::None, ArgTypeIndices.size(),
1584 ArgListIndex, ThisAdjustment);
1585 TypeIndex TI = TypeTable.writeKnownType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001586
1587 return TI;
1588}
1589
Reid Kleckner9dac4732016-08-31 15:59:30 +00001590TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001591 unsigned VSlotCount =
1592 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
Reid Kleckner9dac4732016-08-31 15:59:30 +00001593 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001594
1595 VFTableShapeRecord VFTSR(Slots);
1596 return TypeTable.writeKnownType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001597}
1598
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001599static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1600 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001601 case DINode::FlagPrivate: return MemberAccess::Private;
1602 case DINode::FlagPublic: return MemberAccess::Public;
1603 case DINode::FlagProtected: return MemberAccess::Protected;
1604 case 0:
1605 // If there was no explicit access control, provide the default for the tag.
1606 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1607 : MemberAccess::Public;
1608 }
1609 llvm_unreachable("access flags are exclusive");
1610}
1611
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001612static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1613 if (SP->isArtificial())
1614 return MethodOptions::CompilerGenerated;
1615
1616 // FIXME: Handle other MethodOptions.
1617
1618 return MethodOptions::None;
1619}
1620
1621static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1622 bool Introduced) {
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001623 if (SP->getFlags() & DINode::FlagStaticMember)
1624 return MethodKind::Static;
1625
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001626 switch (SP->getVirtuality()) {
1627 case dwarf::DW_VIRTUALITY_none:
1628 break;
1629 case dwarf::DW_VIRTUALITY_virtual:
1630 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1631 case dwarf::DW_VIRTUALITY_pure_virtual:
1632 return Introduced ? MethodKind::PureIntroducingVirtual
1633 : MethodKind::PureVirtual;
1634 default:
1635 llvm_unreachable("unhandled virtuality case");
1636 }
1637
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001638 return MethodKind::Vanilla;
1639}
1640
Reid Klecknera8d57402016-06-03 15:58:20 +00001641static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1642 switch (Ty->getTag()) {
1643 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1644 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1645 }
1646 llvm_unreachable("unexpected tag");
1647}
1648
Reid Klecknere092dad2016-07-02 00:11:07 +00001649/// Return ClassOptions that should be present on both the forward declaration
1650/// and the defintion of a tag type.
1651static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1652 ClassOptions CO = ClassOptions::None;
1653
1654 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001655 // appear to give every type a linkage name, which may be problematic for us.
1656 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001657 if (!Ty->getIdentifier().empty())
1658 CO |= ClassOptions::HasUniqueName;
1659
1660 // Put the Nested flag on a type if it appears immediately inside a tag type.
1661 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1662 // here. That flag is only set on definitions, and not forward declarations.
1663 const DIScope *ImmediateScope = Ty->getScope().resolve();
1664 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1665 CO |= ClassOptions::Nested;
1666
1667 // Put the Scoped flag on function-local types.
1668 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1669 Scope = Scope->getScope().resolve()) {
1670 if (isa<DISubprogram>(Scope)) {
1671 CO |= ClassOptions::Scoped;
1672 break;
1673 }
1674 }
1675
1676 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001677}
1678
David Majnemer979cb882016-06-16 21:32:16 +00001679TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001680 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001681 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001682 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001683
David Majnemerda9548f2016-06-17 16:13:21 +00001684 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001685 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001686 } else {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001687 FieldListRecordBuilder FLRB(TypeTable);
1688
1689 FLRB.begin();
David Majnemerda9548f2016-06-17 16:13:21 +00001690 for (const DINode *Element : Ty->getElements()) {
1691 // We assume that the frontend provides all members in source declaration
1692 // order, which is what MSVC does.
1693 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001694 EnumeratorRecord ER(MemberAccess::Public,
1695 APSInt::getUnsigned(Enumerator->getValue()),
1696 Enumerator->getName());
1697 FLRB.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00001698 EnumeratorCount++;
1699 }
1700 }
Zachary Turner7f97c362017-05-25 21:15:37 +00001701 FTI = FLRB.end(true);
David Majnemerda9548f2016-06-17 16:13:21 +00001702 }
David Majnemer979cb882016-06-16 21:32:16 +00001703
David Majnemer6bdc24e2016-07-01 23:12:45 +00001704 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001705
Zachary Turner4efa0a42016-11-08 22:24:53 +00001706 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1707 getTypeIndex(Ty->getBaseType()));
1708 return TypeTable.writeKnownType(ER);
David Majnemer979cb882016-06-16 21:32:16 +00001709}
1710
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001711//===----------------------------------------------------------------------===//
1712// ClassInfo
1713//===----------------------------------------------------------------------===//
1714
1715struct llvm::ClassInfo {
1716 struct MemberInfo {
1717 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001718 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001719 };
1720 // [MemberInfo]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001721 using MemberList = std::vector<MemberInfo>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001722
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001723 using MethodsList = TinyPtrVector<const DISubprogram *>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001724 // MethodName -> MethodsList
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001725 using MethodsMap = MapVector<MDString *, MethodsList>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001726
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001727 /// Base classes.
1728 std::vector<const DIDerivedType *> Inheritance;
1729
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001730 /// Direct members.
1731 MemberList Members;
1732 // Direct overloaded methods gathered by name.
1733 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001734
Reid Kleckner9dac4732016-08-31 15:59:30 +00001735 TypeIndex VShapeTI;
1736
Reid Klecknere2e82062017-08-08 20:30:14 +00001737 std::vector<const DIType *> NestedTypes;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001738};
1739
1740void CodeViewDebug::clear() {
1741 assert(CurFn == nullptr);
1742 FileIdMap.clear();
1743 FnDebugInfo.clear();
1744 FileToFilepathMap.clear();
1745 LocalUDTs.clear();
1746 GlobalUDTs.clear();
1747 TypeIndices.clear();
1748 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001749}
1750
1751void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1752 const DIDerivedType *DDTy) {
1753 if (!DDTy->getName().empty()) {
1754 Info.Members.push_back({DDTy, 0});
1755 return;
1756 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001757 // An unnamed member must represent a nested struct or union. Add all the
1758 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001759 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00001760 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001761 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001762 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001763 ClassInfo NestedInfo = collectClassInfo(DCTy);
1764 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001765 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001766 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001767}
1768
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001769ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1770 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001771 // Add elements to structure type.
1772 DINodeArray Elements = Ty->getElements();
1773 for (auto *Element : Elements) {
1774 // We assume that the frontend provides all members in source declaration
1775 // order, which is what MSVC does.
1776 if (!Element)
1777 continue;
1778 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001779 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001780 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001781 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001782 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001783 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1784 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001785 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1786 DDTy->getName() == "__vtbl_ptr_type") {
1787 Info.VShapeTI = getTypeIndex(DDTy);
Reid Klecknere2e82062017-08-08 20:30:14 +00001788 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
1789 Info.NestedTypes.push_back(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001790 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1791 // Ignore friend members. It appears that MSVC emitted info about
1792 // friends in the past, but modern versions do not.
1793 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001794 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
Reid Klecknere2e82062017-08-08 20:30:14 +00001795 Info.NestedTypes.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001796 }
1797 // Skip other unrecognized kinds of elements.
1798 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001799 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001800}
1801
Reid Klecknera8d57402016-06-03 15:58:20 +00001802TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1803 // First, construct the forward decl. Don't look into Ty to compute the
1804 // forward decl options, since it might not be available in all TUs.
1805 TypeRecordKind Kind = getRecordKind(Ty);
1806 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001807 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001808 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001809 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
1810 FullName, Ty->getIdentifier());
1811 TypeIndex FwdDeclTI = TypeTable.writeKnownType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001812 if (!Ty->isForwardDecl())
1813 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001814 return FwdDeclTI;
1815}
1816
1817TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1818 // Construct the field list and complete type record.
1819 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00001820 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001821 TypeIndex FieldTI;
1822 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001823 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001824 bool ContainsNestedClass;
1825 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1826 lowerRecordFieldList(Ty);
1827
1828 if (ContainsNestedClass)
1829 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00001830
David Majnemer6bdc24e2016-07-01 23:12:45 +00001831 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001832
Reid Klecknera8d57402016-06-03 15:58:20 +00001833 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001834
Zachary Turner4efa0a42016-11-08 22:24:53 +00001835 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
1836 SizeInBytes, FullName, Ty->getIdentifier());
1837 TypeIndex ClassTI = TypeTable.writeKnownType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001838
Saleem Abdulrasool87f03382017-05-03 21:39:01 +00001839 if (const auto *File = Ty->getFile()) {
1840 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
1841 TypeIndex SIDI = TypeTable.writeKnownType(SIDR);
1842 UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine());
1843 TypeTable.writeKnownType(USLR);
1844 }
Hans Wennborg9a519a02016-06-22 21:22:13 +00001845
Zachary Turnera7b04172017-08-28 18:49:04 +00001846 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001847
Hans Wennborg9a519a02016-06-22 21:22:13 +00001848 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001849}
1850
1851TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1852 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001853 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001854 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001855 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
1856 TypeIndex FwdDeclTI = TypeTable.writeKnownType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001857 if (!Ty->isForwardDecl())
1858 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001859 return FwdDeclTI;
1860}
1861
1862TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00001863 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001864 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001865 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001866 bool ContainsNestedClass;
1867 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1868 lowerRecordFieldList(Ty);
1869
1870 if (ContainsNestedClass)
1871 CO |= ClassOptions::ContainsNestedClass;
1872
Reid Klecknera8d57402016-06-03 15:58:20 +00001873 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00001874 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001875
Zachary Turner4efa0a42016-11-08 22:24:53 +00001876 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
1877 Ty->getIdentifier());
1878 TypeIndex UnionTI = TypeTable.writeKnownType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001879
Zachary Turner4efa0a42016-11-08 22:24:53 +00001880 StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1881 TypeIndex SIRI = TypeTable.writeKnownType(SIR);
1882 UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine());
1883 TypeTable.writeKnownType(USLR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001884
Zachary Turnera7b04172017-08-28 18:49:04 +00001885 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001886
Hans Wennborg9a519a02016-06-22 21:22:13 +00001887 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001888}
1889
Adrian McCarthy820ca542016-07-06 19:49:51 +00001890std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00001891CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1892 // Manually count members. MSVC appears to count everything that generates a
1893 // field list record. Each individual overload in a method overload group
1894 // contributes to this count, even though the overload group is a single field
1895 // list record.
1896 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001897 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001898 FieldListRecordBuilder FLBR(TypeTable);
1899 FLBR.begin();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001900
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001901 // Create base classes.
1902 for (const DIDerivedType *I : Info.Inheritance) {
1903 if (I->getFlags() & DINode::FlagVirtual) {
1904 // Virtual base.
1905 // FIXME: Emit VBPtrOffset when the frontend provides it.
1906 unsigned VBPtrOffset = 0;
1907 // FIXME: Despite the accessor name, the offset is really in bytes.
1908 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00001909 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
1910 ? TypeRecordKind::IndirectVirtualBaseClass
1911 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001912 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00001913 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001914 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00001915 VBTableIndex);
1916
1917 FLBR.writeMemberType(VBCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001918 } else {
1919 assert(I->getOffsetInBits() % 8 == 0 &&
1920 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00001921 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
1922 getTypeIndex(I->getBaseType()),
1923 I->getOffsetInBits() / 8);
1924 FLBR.writeMemberType(BCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001925 }
1926 }
1927
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001928 // Create members.
1929 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1930 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1931 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00001932 StringRef MemberName = Member->getName();
1933 MemberAccess Access =
1934 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001935
1936 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001937 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
1938 FLBR.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001939 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001940 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001941 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001942
Reid Kleckner9dac4732016-08-31 15:59:30 +00001943 // Virtual function pointer member.
1944 if ((Member->getFlags() & DINode::FlagArtificial) &&
1945 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001946 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
1947 FLBR.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001948 MemberCount++;
1949 continue;
1950 }
1951
David Majnemer9319cbc2016-06-30 03:00:20 +00001952 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00001953 uint64_t MemberOffsetInBits =
1954 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001955 if (Member->isBitField()) {
1956 uint64_t StartBitOffset = MemberOffsetInBits;
1957 if (const auto *CI =
1958 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00001959 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001960 }
1961 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001962 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
1963 StartBitOffset);
1964 MemberBaseType = TypeTable.writeKnownType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00001965 }
1966 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001967 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
1968 MemberName);
1969 FLBR.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001970 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001971 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001972
1973 // Create methods
1974 for (auto &MethodItr : Info.Methods) {
1975 StringRef Name = MethodItr.first->getString();
1976
1977 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00001978 for (const DISubprogram *SP : MethodItr.second) {
1979 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1980 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001981
1982 unsigned VFTableOffset = -1;
1983 if (Introduced)
1984 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1985
Zachary Turner7251ede2016-11-02 17:05:19 +00001986 Methods.push_back(OneMethodRecord(
1987 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
1988 translateMethodKindFlags(SP, Introduced),
1989 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001990 MemberCount++;
1991 }
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001992 assert(!Methods.empty() && "Empty methods map entry");
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001993 if (Methods.size() == 1)
Zachary Turner4efa0a42016-11-08 22:24:53 +00001994 FLBR.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001995 else {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001996 MethodOverloadListRecord MOLR(Methods);
1997 TypeIndex MethodList = TypeTable.writeKnownType(MOLR);
1998 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
1999 FLBR.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002000 }
2001 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002002
2003 // Create nested classes.
Reid Klecknere2e82062017-08-08 20:30:14 +00002004 for (const DIType *Nested : Info.NestedTypes) {
Adrian McCarthy820ca542016-07-06 19:49:51 +00002005 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner4efa0a42016-11-08 22:24:53 +00002006 FLBR.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00002007 MemberCount++;
2008 }
2009
Zachary Turner7f97c362017-05-25 21:15:37 +00002010 TypeIndex FieldTI = FLBR.end(true);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002011 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Reid Klecknere2e82062017-08-08 20:30:14 +00002012 !Info.NestedTypes.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00002013}
2014
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002015TypeIndex CodeViewDebug::getVBPTypeIndex() {
2016 if (!VBPType.getIndex()) {
2017 // Make a 'const int *' type.
2018 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00002019 TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002020
2021 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2022 : PointerKind::Near32;
2023 PointerMode PM = PointerMode::Pointer;
2024 PointerOptions PO = PointerOptions::None;
2025 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2026
Zachary Turner5e3e4bb2016-08-05 21:45:34 +00002027 VBPType = TypeTable.writeKnownType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002028 }
2029
2030 return VBPType;
2031}
2032
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002033TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002034 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002035 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002036
2037 // The null DIType is the void type. Don't try to hash it.
2038 if (!Ty)
2039 return TypeIndex::Void();
2040
Reid Klecknera8d57402016-06-03 15:58:20 +00002041 // Check if we've already translated this type. Don't try to do a
2042 // get-or-create style insertion that caches the hash lookup across the
2043 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002044 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002045 if (I != TypeIndices.end())
2046 return I->second;
2047
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002048 TypeLoweringScope S(*this);
2049 TypeIndex TI = lowerType(Ty, ClassTy);
2050 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002051}
2052
Bob Haarman223303c2017-08-29 20:59:25 +00002053TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
2054 DIType *Ty = TypeRef.resolve();
2055 PointerRecord PR(getTypeIndex(Ty),
2056 getPointerSizeInBytes() == 8 ? PointerKind::Near64
2057 : PointerKind::Near32,
2058 PointerMode::LValueReference, PointerOptions::None,
2059 Ty->getSizeInBits() / 8);
2060 return TypeTable.writeKnownType(PR);
2061}
2062
Reid Klecknera8d57402016-06-03 15:58:20 +00002063TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
2064 const DIType *Ty = TypeRef.resolve();
2065
2066 // The null DIType is the void type. Don't try to hash it.
2067 if (!Ty)
2068 return TypeIndex::Void();
2069
2070 // If this is a non-record type, the complete type index is the same as the
2071 // normal type index. Just call getTypeIndex.
2072 switch (Ty->getTag()) {
2073 case dwarf::DW_TAG_class_type:
2074 case dwarf::DW_TAG_structure_type:
2075 case dwarf::DW_TAG_union_type:
2076 break;
2077 default:
2078 return getTypeIndex(Ty);
2079 }
2080
2081 // Check if we've already translated the complete record type. Lowering a
2082 // complete type should never trigger lowering another complete type, so we
2083 // can reuse the hash table lookup result.
2084 const auto *CTy = cast<DICompositeType>(Ty);
2085 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2086 if (!InsertResult.second)
2087 return InsertResult.first->second;
2088
Reid Kleckner643dd832016-06-22 17:15:28 +00002089 TypeLoweringScope S(*this);
2090
Reid Klecknera8d57402016-06-03 15:58:20 +00002091 // Make sure the forward declaration is emitted first. It's unclear if this
2092 // is necessary, but MSVC does it, and we should follow suit until we can show
2093 // otherwise.
2094 TypeIndex FwdDeclTI = getTypeIndex(CTy);
2095
2096 // Just use the forward decl if we don't have complete type info. This might
2097 // happen if the frontend is using modules and expects the complete definition
2098 // to be emitted elsewhere.
2099 if (CTy->isForwardDecl())
2100 return FwdDeclTI;
2101
2102 TypeIndex TI;
2103 switch (CTy->getTag()) {
2104 case dwarf::DW_TAG_class_type:
2105 case dwarf::DW_TAG_structure_type:
2106 TI = lowerCompleteTypeClass(CTy);
2107 break;
2108 case dwarf::DW_TAG_union_type:
2109 TI = lowerCompleteTypeUnion(CTy);
2110 break;
2111 default:
2112 llvm_unreachable("not a record");
2113 }
2114
2115 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002116 return TI;
2117}
2118
Reid Kleckner643dd832016-06-22 17:15:28 +00002119/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00002120/// and do this until fixpoint, as each complete record type typically
2121/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00002122/// many other record types.
2123void CodeViewDebug::emitDeferredCompleteTypes() {
2124 SmallVector<const DICompositeType *, 4> TypesToEmit;
2125 while (!DeferredCompleteTypes.empty()) {
2126 std::swap(DeferredCompleteTypes, TypesToEmit);
2127 for (const DICompositeType *RecordTy : TypesToEmit)
2128 getCompleteTypeIndex(RecordTy);
2129 TypesToEmit.clear();
2130 }
2131}
2132
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002133void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
2134 // Get the sorted list of parameters and emit them first.
2135 SmallVector<const LocalVariable *, 6> Params;
2136 for (const LocalVariable &L : Locals)
2137 if (L.DIVar->isParameter())
2138 Params.push_back(&L);
2139 std::sort(Params.begin(), Params.end(),
2140 [](const LocalVariable *L, const LocalVariable *R) {
2141 return L->DIVar->getArg() < R->DIVar->getArg();
2142 });
2143 for (const LocalVariable *L : Params)
2144 emitLocalVariable(*L);
2145
2146 // Next emit all non-parameters in the order that we found them.
2147 for (const LocalVariable &L : Locals)
2148 if (!L.DIVar->isParameter())
2149 emitLocalVariable(L);
2150}
2151
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002152void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2153 // LocalSym record, see SymbolRecord.h for more info.
2154 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2155 *LocalEnd = MMI->getContext().createTempSymbol();
2156 OS.AddComment("Record length");
2157 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2158 OS.EmitLabel(LocalBegin);
2159
2160 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00002161 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002162
Zachary Turner63a28462016-05-17 23:50:21 +00002163 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002164 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002165 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002166 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002167 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002168
2169 OS.AddComment("TypeIndex");
Reid Kleckner08f5fd52017-08-31 15:56:49 +00002170 TypeIndex TI = Var.UseReferenceType
2171 ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2172 : getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002173 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002174 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002175 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002176 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002177 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002178 OS.EmitLabel(LocalEnd);
2179
Reid Kleckner876330d2016-02-12 21:48:30 +00002180 // Calculate the on disk prefix of the appropriate def range record. The
2181 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2182 // should be big enough to hold all forms without memory allocation.
2183 SmallString<20> BytePrefix;
2184 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2185 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002186 if (DefRange.InMemory) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002187 uint16_t RegRelFlags = 0;
2188 if (DefRange.IsSubfield) {
2189 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2190 (DefRange.StructOffset
2191 << DefRangeRegisterRelSym::OffsetInParentShift);
2192 }
Zachary Turner46225b12016-12-16 22:48:14 +00002193 DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
2194 Sym.Hdr.Register = DefRange.CVRegister;
2195 Sym.Hdr.Flags = RegRelFlags;
2196 Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +00002197 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00002198 BytePrefix +=
2199 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00002200 BytePrefix +=
Zachary Turner46225b12016-12-16 22:48:14 +00002201 StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
Reid Kleckner876330d2016-02-12 21:48:30 +00002202 } else {
2203 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002204 if (DefRange.IsSubfield) {
2205 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002206 DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2207 Sym.Hdr.Register = DefRange.CVRegister;
2208 Sym.Hdr.MayHaveNoName = 0;
2209 Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2210
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002211 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2212 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2213 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002214 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2215 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002216 } else {
2217 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002218 DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2219 Sym.Hdr.Register = DefRange.CVRegister;
2220 Sym.Hdr.MayHaveNoName = 0;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002221 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2222 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2223 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002224 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2225 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002226 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002227 }
2228 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2229 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002230}
2231
David Blaikieb2fbb4b2017-02-16 18:48:33 +00002232void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002233 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00002234 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002235 assert(CurFn == &FnDebugInfo[GV]);
2236
Pete Cooperadebb932016-03-11 02:14:16 +00002237 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002238
Reid Kleckner2214ed82016-01-29 00:49:42 +00002239 // Don't emit anything if we don't have any line tables.
2240 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002241 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002242 CurFn = nullptr;
2243 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002244 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002245
Reid Klecknere33c94f2017-09-05 20:14:58 +00002246 CurFn->Annotations = MF->getCodeViewAnnotations();
2247
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002248 CurFn->End = Asm->getFunctionEnd();
2249
Craig Topper353eda42014-04-24 06:44:33 +00002250 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002251}
2252
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002253void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002254 DebugHandlerBase::beginInstruction(MI);
2255
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002256 // Ignore DBG_VALUE locations and function prologue.
David Majnemer67f684e2016-07-28 05:03:22 +00002257 if (!Asm || !CurFn || MI->isDebugValue() ||
2258 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002259 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002260
2261 // If the first instruction of a new MBB has no location, find the first
2262 // instruction with a location and use that.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002263 DebugLoc DL = MI->getDebugLoc();
Reid Kleckner45a74622017-06-30 21:33:44 +00002264 if (!DL && MI->getParent() != PrevInstBB) {
2265 for (const auto &NextMI : *MI->getParent()) {
Reid Kleckner2de471d2017-07-31 21:03:08 +00002266 if (NextMI.isDebugValue())
2267 continue;
Reid Kleckner45a74622017-06-30 21:33:44 +00002268 DL = NextMI.getDebugLoc();
2269 if (DL)
2270 break;
2271 }
2272 }
2273 PrevInstBB = MI->getParent();
2274
2275 // If we still don't have a debug location, don't record a location.
2276 if (!DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002277 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002278
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002279 maybeRecordLocation(DL, Asm->MF);
2280}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002281
Zachary Turner8c099fe2017-05-30 16:36:15 +00002282MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002283 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2284 *EndLabel = MMI->getContext().createTempSymbol();
2285 OS.EmitIntValue(unsigned(Kind), 4);
2286 OS.AddComment("Subsection size");
2287 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2288 OS.EmitLabel(BeginLabel);
2289 return EndLabel;
2290}
2291
2292void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2293 OS.EmitLabel(EndLabel);
2294 // Every subsection must be aligned to a 4-byte boundary.
2295 OS.EmitValueToAlignment(4);
2296}
2297
David Majnemer3128b102016-06-15 18:00:01 +00002298void CodeViewDebug::emitDebugInfoForUDTs(
Zachary Turnera7b04172017-08-28 18:49:04 +00002299 ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2300 for (const auto &UDT : UDTs) {
2301 const DIType *T = UDT.second;
2302 assert(shouldEmitUdt(T));
2303
David Majnemer3128b102016-06-15 18:00:01 +00002304 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2305 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2306 OS.AddComment("Record length");
2307 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2308 OS.EmitLabel(UDTRecordBegin);
2309
2310 OS.AddComment("Record kind: S_UDT");
2311 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2312
2313 OS.AddComment("Type");
Zachary Turnera7b04172017-08-28 18:49:04 +00002314 OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
David Majnemer3128b102016-06-15 18:00:01 +00002315
2316 emitNullTerminatedSymbolName(OS, UDT.first);
2317 OS.EmitLabel(UDTRecordEnd);
2318 }
2319}
2320
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002321void CodeViewDebug::emitDebugInfoForGlobals() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002322 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2323 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002324 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002325 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2326 GV.getDebugInfo(GVEs);
2327 for (const auto *GVE : GVEs)
2328 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002329 }
2330
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002331 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2332 for (const MDNode *Node : CUs->operands()) {
2333 const auto *CU = cast<DICompileUnit>(Node);
2334
2335 // First, emit all globals that are not in a comdat in a single symbol
2336 // substream. MSVC doesn't like it if the substream is empty, so only open
2337 // it if we have at least one global to emit.
2338 switchToDebugSectionForSymbol(nullptr);
2339 MCSymbol *EndLabel = nullptr;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002340 for (const auto *GVE : CU->getGlobalVariables()) {
2341 if (const auto *GV = GlobalMap.lookup(GVE))
David Majnemer577be0f2016-06-15 00:19:52 +00002342 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002343 if (!EndLabel) {
2344 OS.AddComment("Symbol subsection for globals");
Zachary Turner8c099fe2017-05-30 16:36:15 +00002345 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002346 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002347 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2348 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002349 }
2350 }
2351 if (EndLabel)
2352 endCVSubsection(EndLabel);
2353
2354 // Second, emit each global that is in a comdat into its own .debug$S
2355 // section along with its own symbol substream.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002356 for (const auto *GVE : CU->getGlobalVariables()) {
2357 if (const auto *GV = GlobalMap.lookup(GVE)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002358 if (GV->hasComdat()) {
2359 MCSymbol *GVSym = Asm->getSymbol(GV);
2360 OS.AddComment("Symbol subsection for " +
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00002361 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002362 switchToDebugSectionForSymbol(GVSym);
Zachary Turner8c099fe2017-05-30 16:36:15 +00002363 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002364 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2365 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002366 endCVSubsection(EndLabel);
2367 }
2368 }
2369 }
2370 }
2371}
2372
Hans Wennborgb510b452016-06-23 16:33:53 +00002373void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2374 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2375 for (const MDNode *Node : CUs->operands()) {
2376 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2377 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2378 getTypeIndex(RT);
2379 // FIXME: Add to global/local DTU list.
2380 }
2381 }
2382 }
2383}
2384
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002385void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002386 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002387 MCSymbol *GVSym) {
2388 // DataSym record, see SymbolRecord.h for more info.
2389 // FIXME: Thread local data, etc
2390 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2391 *DataEnd = MMI->getContext().createTempSymbol();
2392 OS.AddComment("Record length");
2393 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2394 OS.EmitLabel(DataBegin);
David Majnemer7abd2692016-07-06 21:07:47 +00002395 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002396 if (GV->isThreadLocal()) {
2397 OS.AddComment("Record kind: S_LTHREAD32");
2398 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2399 } else {
2400 OS.AddComment("Record kind: S_LDATA32");
2401 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2402 }
David Majnemer7abd2692016-07-06 21:07:47 +00002403 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002404 if (GV->isThreadLocal()) {
2405 OS.AddComment("Record kind: S_GTHREAD32");
2406 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2407 } else {
2408 OS.AddComment("Record kind: S_GDATA32");
2409 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2410 }
David Majnemer7abd2692016-07-06 21:07:47 +00002411 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002412 OS.AddComment("Type");
2413 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2414 OS.AddComment("DataOffset");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00002415 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002416 OS.AddComment("Segment");
2417 OS.EmitCOFFSectionIndex(GVSym);
2418 OS.AddComment("Name");
2419 emitNullTerminatedSymbolName(OS, DIGV->getName());
2420 OS.EmitLabel(DataEnd);
2421}