blob: 59056b0ff5df33bf7397ad8c3bb9d9d348e90388 [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"
David Blaikieb3bde2e2017-11-17 01:07:10 +000023#include "llvm/ADT/STLExtras.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000024#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/SmallVector.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000026#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"
Reid Kleckner9ea2c012018-10-01 21:59:45 +000034#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000035#include "llvm/CodeGen/MachineFunction.h"
36#include "llvm/CodeGen/MachineInstr.h"
37#include "llvm/CodeGen/MachineModuleInfo.h"
38#include "llvm/CodeGen/MachineOperand.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000039#include "llvm/CodeGen/TargetFrameLowering.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000040#include "llvm/CodeGen/TargetRegisterInfo.h"
41#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000042#include "llvm/Config/llvm-config.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000043#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000044#include "llvm/DebugInfo/CodeView/CodeView.h"
Zachary Turner6900de12017-11-28 18:33:17 +000045#include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
Zachary Turner8c099fe2017-05-30 16:36:15 +000046#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000047#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000048#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000049#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000050#include "llvm/DebugInfo/CodeView/TypeIndex.h"
51#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000052#include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000053#include "llvm/IR/Constants.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000054#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/DebugInfoMetadata.h"
56#include "llvm/IR/DebugLoc.h"
57#include "llvm/IR/Function.h"
58#include "llvm/IR/GlobalValue.h"
59#include "llvm/IR/GlobalVariable.h"
60#include "llvm/IR/Metadata.h"
61#include "llvm/IR/Module.h"
Reid Kleckner46cb48c2016-07-27 16:03:57 +000062#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000063#include "llvm/MC/MCContext.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000064#include "llvm/MC/MCSectionCOFF.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000065#include "llvm/MC/MCStreamer.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000066#include "llvm/MC/MCSymbol.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000067#include "llvm/Support/BinaryByteStream.h"
68#include "llvm/Support/BinaryStreamReader.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000069#include "llvm/Support/Casting.h"
Zachary Turner048f8f92017-12-13 22:33:58 +000070#include "llvm/Support/CommandLine.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000071#include "llvm/Support/Compiler.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000072#include "llvm/Support/Endian.h"
73#include "llvm/Support/Error.h"
74#include "llvm/Support/ErrorHandling.h"
Zachary Turner048f8f92017-12-13 22:33:58 +000075#include "llvm/Support/FormatVariadic.h"
Zachary Turner5bba1ca2018-10-12 17:26:19 +000076#include "llvm/Support/Path.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000077#include "llvm/Support/SMLoc.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000078#include "llvm/Support/ScopedPrinter.h"
David Blaikie6054e652018-03-23 23:58:19 +000079#include "llvm/Target/TargetLoweringObjectFile.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000080#include "llvm/Target/TargetMachine.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000081#include <algorithm>
82#include <cassert>
83#include <cctype>
84#include <cstddef>
85#include <cstdint>
86#include <iterator>
87#include <limits>
88#include <string>
89#include <utility>
90#include <vector>
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000091
Reid Klecknerf9c275f2016-02-10 20:55:49 +000092using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000093using namespace llvm::codeview;
94
Reid Kleckner9ea2c012018-10-01 21:59:45 +000095static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
96 switch (Type) {
97 case Triple::ArchType::x86:
98 return CPUType::Pentium3;
99 case Triple::ArchType::x86_64:
100 return CPUType::X64;
101 case Triple::ArchType::thumb:
102 return CPUType::Thumb;
103 case Triple::ArchType::aarch64:
104 return CPUType::ARM64;
105 default:
106 report_fatal_error("target architecture doesn't map to a CodeView CPUType");
107 }
108}
109
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000110CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000111 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000112 // If module doesn't have named metadata anchors or COFF debug section
113 // is not available, skip any debug info related stuff.
114 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
115 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
116 Asm = nullptr;
Matthias Braun8763c0c2018-10-31 17:18:41 +0000117 MMI->setDebugInfoAvailability(false);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000118 return;
119 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000120 // Tell MMI that we have debug info.
121 MMI->setDebugInfoAvailability(true);
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000122
123 TheCPU =
124 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
Reid Kleckner75557712018-11-16 18:47:41 +0000125
126 // Check if we should emit type record hashes.
127 ConstantInt *GH = mdconst::extract_or_null<ConstantInt>(
128 MMI->getModule()->getModuleFlag("CodeViewGHash"));
129 EmitDebugGlobalHashes = GH && !GH->isZero();
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000130}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000131
Reid Kleckner9533af42016-01-16 00:09:09 +0000132StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
133 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000134 if (!Filepath.empty())
135 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000136
Reid Kleckner9533af42016-01-16 00:09:09 +0000137 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
138
Peter Collingbournecb8a6662018-04-11 18:24:03 +0000139 // If this is a Unix-style path, just use it as is. Don't try to canonicalize
140 // it textually because one of the path components could be a symlink.
Zachary Turner5bba1ca2018-10-12 17:26:19 +0000141 if (Dir.startswith("/") || Filename.startswith("/")) {
142 if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
143 return Filename;
Peter Collingbournecb8a6662018-04-11 18:24:03 +0000144 Filepath = Dir;
145 if (Dir.back() != '/')
146 Filepath += '/';
147 Filepath += Filename;
148 return Filepath;
149 }
150
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000151 // Clang emits directory and relative filename info into the IR, but CodeView
152 // operates on full paths. We could change Clang to emit full paths too, but
153 // that would increase the IR size and probably not needed for other users.
154 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000155 if (Filename.find(':') == 1)
156 Filepath = Filename;
157 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000158 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000159
160 // Canonicalize the path. We have to do it textually because we may no longer
161 // have access the file in the filesystem.
162 // First, replace all slashes with backslashes.
163 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
164
165 // Remove all "\.\" with "\".
166 size_t Cursor = 0;
167 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
168 Filepath.erase(Cursor, 2);
169
170 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
171 // path should be well-formatted, e.g. start with a drive letter, etc.
172 Cursor = 0;
173 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
174 // Something's wrong if the path starts with "\..\", abort.
175 if (Cursor == 0)
176 break;
177
178 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
179 if (PrevSlash == std::string::npos)
180 // Something's wrong, abort.
181 break;
182
183 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
184 // The next ".." might be following the one we've just erased.
185 Cursor = PrevSlash;
186 }
187
188 // Remove all duplicate backslashes.
189 Cursor = 0;
190 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
191 Filepath.erase(Cursor, 1);
192
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000193 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000194}
195
Reid Kleckner2214ed82016-01-29 00:49:42 +0000196unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000197 StringRef FullPath = getFullFilepath(F);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000198 unsigned NextId = FileIdMap.size() + 1;
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000199 auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
Reid Kleckner2214ed82016-01-29 00:49:42 +0000200 if (Insertion.second) {
201 // We have to compute the full filepath and emit a .cv_file directive.
Scott Linder71603842018-02-12 19:45:54 +0000202 ArrayRef<uint8_t> ChecksumAsBytes;
203 FileChecksumKind CSKind = FileChecksumKind::None;
204 if (F->getChecksum()) {
205 std::string Checksum = fromHex(F->getChecksum()->Value);
206 void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
207 memcpy(CKMem, Checksum.data(), Checksum.size());
208 ChecksumAsBytes = ArrayRef<uint8_t>(
209 reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
210 switch (F->getChecksum()->Kind) {
211 case DIFile::CSK_MD5: CSKind = FileChecksumKind::MD5; break;
212 case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
213 }
214 }
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000215 bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
Scott Linder71603842018-02-12 19:45:54 +0000216 static_cast<unsigned>(CSKind));
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000217 (void)Success;
218 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000219 }
220 return Insertion.first->second;
221}
222
Reid Kleckner876330d2016-02-12 21:48:30 +0000223CodeViewDebug::InlineSite &
224CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
225 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000226 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
227 InlineSite *Site = &SiteInsertion.first->second;
228 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000229 unsigned ParentFuncId = CurFn->FuncId;
230 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
231 ParentFuncId =
232 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
233 .SiteFuncId;
234
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000235 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000236 OS.EmitCVInlineSiteIdDirective(
237 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
238 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000239 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000240 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000241 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000242 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000243 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000244}
245
David Majnemer6bdc24e2016-07-01 23:12:45 +0000246static StringRef getPrettyScopeName(const DIScope *Scope) {
247 StringRef ScopeName = Scope->getName();
248 if (!ScopeName.empty())
249 return ScopeName;
250
251 switch (Scope->getTag()) {
252 case dwarf::DW_TAG_enumeration_type:
253 case dwarf::DW_TAG_class_type:
254 case dwarf::DW_TAG_structure_type:
255 case dwarf::DW_TAG_union_type:
256 return "<unnamed-tag>";
257 case dwarf::DW_TAG_namespace:
258 return "`anonymous namespace'";
259 }
260
261 return StringRef();
262}
263
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000264static const DISubprogram *getQualifiedNameComponents(
265 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
266 const DISubprogram *ClosestSubprogram = nullptr;
267 while (Scope != nullptr) {
268 if (ClosestSubprogram == nullptr)
269 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000270 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000271 if (!ScopeName.empty())
272 QualifiedNameComponents.push_back(ScopeName);
273 Scope = Scope->getScope().resolve();
274 }
275 return ClosestSubprogram;
276}
277
278static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
279 StringRef TypeName) {
280 std::string FullyQualifiedName;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000281 for (StringRef QualifiedNameComponent :
282 llvm::reverse(QualifiedNameComponents)) {
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000283 FullyQualifiedName.append(QualifiedNameComponent);
284 FullyQualifiedName.append("::");
285 }
286 FullyQualifiedName.append(TypeName);
287 return FullyQualifiedName;
288}
289
290static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
291 SmallVector<StringRef, 5> QualifiedNameComponents;
292 getQualifiedNameComponents(Scope, QualifiedNameComponents);
293 return getQualifiedName(QualifiedNameComponents, Name);
294}
295
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000296struct CodeViewDebug::TypeLoweringScope {
297 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
298 ~TypeLoweringScope() {
299 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
300 // inner TypeLoweringScopes don't attempt to emit deferred types.
301 if (CVD.TypeEmissionLevel == 1)
302 CVD.emitDeferredCompleteTypes();
303 --CVD.TypeEmissionLevel;
304 }
305 CodeViewDebug &CVD;
306};
307
David Majnemer6bdc24e2016-07-01 23:12:45 +0000308static std::string getFullyQualifiedName(const DIScope *Ty) {
309 const DIScope *Scope = Ty->getScope().resolve();
310 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
311}
312
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000313TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
314 // No scope means global scope and that uses the zero index.
315 if (!Scope || isa<DIFile>(Scope))
316 return TypeIndex();
317
318 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
319
320 // Check if we've already translated this scope.
321 auto I = TypeIndices.find({Scope, nullptr});
322 if (I != TypeIndices.end())
323 return I->second;
324
325 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000326 std::string ScopeName = getFullyQualifiedName(Scope);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000327 StringIdRecord SID(TypeIndex(), ScopeName);
Zachary Turner6900de12017-11-28 18:33:17 +0000328 auto TI = TypeTable.writeLeafType(SID);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000329 return recordTypeIndexForDINode(Scope, TI);
330}
331
David Majnemer75c3ebf2016-06-02 17:13:53 +0000332TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000333 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000334
David Majnemer75c3ebf2016-06-02 17:13:53 +0000335 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000336 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000337 if (I != TypeIndices.end())
338 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000339
Reid Klecknerac945e22016-06-17 16:11:20 +0000340 // The display name includes function template arguments. Drop them to match
341 // MSVC.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000342 StringRef DisplayName = SP->getName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000343
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000344 const DIScope *Scope = SP->getScope().resolve();
345 TypeIndex TI;
346 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
347 // If the scope is a DICompositeType, then this must be a method. Member
348 // function types take some special handling, and require access to the
349 // subprogram.
350 TypeIndex ClassType = getTypeIndex(Class);
351 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
352 DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000353 TI = TypeTable.writeLeafType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000354 } else {
355 // Otherwise, this must be a free function.
356 TypeIndex ParentScope = getScopeIndex(Scope);
357 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000358 TI = TypeTable.writeLeafType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000359 }
360
361 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000362}
363
Aaron Smith802b0332018-10-02 20:21:05 +0000364static bool isTrivial(const DICompositeType *DCTy) {
365 return ((DCTy->getFlags() & DINode::FlagTrivial) == DINode::FlagTrivial);
366}
367
368static FunctionOptions
369getFunctionOptions(const DISubroutineType *Ty,
370 const DICompositeType *ClassTy = nullptr,
371 StringRef SPName = StringRef("")) {
372 FunctionOptions FO = FunctionOptions::None;
373 const DIType *ReturnTy = nullptr;
374 if (auto TypeArray = Ty->getTypeArray()) {
375 if (TypeArray.size())
376 ReturnTy = TypeArray[0].resolve();
377 }
378
379 if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy)) {
380 if (!isTrivial(ReturnDCTy))
381 FO |= FunctionOptions::CxxReturnUdt;
382 }
383
384 // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
385 if (ClassTy && !isTrivial(ClassTy) && SPName == ClassTy->getName()) {
386 FO |= FunctionOptions::Constructor;
387
388 // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
389
390 }
391 return FO;
392}
393
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000394TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
395 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000396 // Always use the method declaration as the key for the function type. The
397 // method declaration contains the this adjustment.
398 if (SP->getDeclaration())
399 SP = SP->getDeclaration();
400 assert(!SP->getDeclaration() && "should use declaration as key");
401
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000402 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
403 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000404 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000405 if (I != TypeIndices.end())
406 return I->second;
407
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000408 // Make sure complete type info for the class is emitted *after* the member
409 // function type, as the complete class type is likely to reference this
410 // member function type.
411 TypeLoweringScope S(*this);
Adrian McCarthyd91bf392017-09-13 20:53:55 +0000412 const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
Aaron Smith802b0332018-10-02 20:21:05 +0000413
414 FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
Adrian McCarthyd91bf392017-09-13 20:53:55 +0000415 TypeIndex TI = lowerTypeMemberFunction(
Aaron Smith802b0332018-10-02 20:21:05 +0000416 SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000417 return recordTypeIndexForDINode(SP, TI, Class);
418}
419
Amjad Aboudacee5682016-07-12 12:06:34 +0000420TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
421 TypeIndex TI,
422 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000423 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000424 (void)InsertResult;
425 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000426 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000427}
428
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000429unsigned CodeViewDebug::getPointerSizeInBytes() {
430 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
431}
432
Reid Kleckner876330d2016-02-12 21:48:30 +0000433void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000434 const LexicalScope *LS) {
435 if (const DILocation *InlinedAt = LS->getInlinedAt()) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000436 // This variable was inlined. Associate it with the InlineSite.
437 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
438 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
439 Site.InlinedLocals.emplace_back(Var);
440 } else {
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000441 // This variable goes into the corresponding lexical scope.
442 ScopeVariables[LS].emplace_back(Var);
Reid Kleckner876330d2016-02-12 21:48:30 +0000443 }
444}
445
Reid Kleckner829365a2016-02-11 19:41:47 +0000446static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
447 const DILocation *Loc) {
448 auto B = Locs.begin(), E = Locs.end();
449 if (std::find(B, E, Loc) == E)
450 Locs.push_back(Loc);
451}
452
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000453void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000454 const MachineFunction *MF) {
455 // Skip this instruction if it has the same location as the previous one.
Reid Kleckner45a74622017-06-30 21:33:44 +0000456 if (!DL || DL == PrevInstLoc)
Reid Kleckner9533af42016-01-16 00:09:09 +0000457 return;
458
459 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000460 if (!Scope)
461 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000462
David Majnemerc3340db2016-01-13 01:05:23 +0000463 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000464 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
465 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
466 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000467 return;
468
Reid Kleckner2214ed82016-01-29 00:49:42 +0000469 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
470 if (CI.getStartColumn() != DL.getCol())
471 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000472
Reid Kleckner2214ed82016-01-29 00:49:42 +0000473 if (!CurFn->HaveLineInfo)
474 CurFn->HaveLineInfo = true;
475 unsigned FileId = 0;
Reid Kleckner45a74622017-06-30 21:33:44 +0000476 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
Reid Kleckner2214ed82016-01-29 00:49:42 +0000477 FileId = CurFn->LastFileId;
478 else
479 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
Reid Kleckner45a74622017-06-30 21:33:44 +0000480 PrevInstLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000481
482 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000483 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000484 const DILocation *Loc = DL.get();
485
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000486 // If this location was actually inlined from somewhere else, give it the ID
487 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000488 FuncId =
489 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000490
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000491 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000492 bool FirstLoc = true;
493 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000494 InlineSite &Site =
495 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000496 if (!FirstLoc)
497 addLocIfNotPresent(Site.ChildSites, Loc);
498 FirstLoc = false;
499 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000500 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000501 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000502 }
503
Reid Klecknerdac21b42016-02-03 21:15:48 +0000504 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000505 /*PrologueEnd=*/false, /*IsStmt=*/false,
506 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000507}
508
Reid Kleckner5d122f82016-05-25 23:16:12 +0000509void CodeViewDebug::emitCodeViewMagicVersion() {
510 OS.EmitValueToAlignment(4);
511 OS.AddComment("Debug section magic");
512 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
513}
514
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000515void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000516 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000517 return;
518
519 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000520
521 // The COFF .debug$S section consists of several subsections, each starting
522 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
523 // of the payload followed by the payload itself. The subsections are 4-byte
524 // aligned.
525
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000526 // Use the generic .debug$S section, and make a subsection for all the inlined
527 // subprograms.
528 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000529
Zachary Turner8c099fe2017-05-30 16:36:15 +0000530 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000531 emitCompilerInformation();
532 endCVSubsection(CompilerInfo);
533
Reid Kleckner5d122f82016-05-25 23:16:12 +0000534 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000535
Reid Kleckner2214ed82016-01-29 00:49:42 +0000536 // Emit per-function debug information.
537 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000538 if (!P.first->isDeclarationForLinker())
Reid Kleckner55baeef2018-03-15 21:12:21 +0000539 emitDebugInfoForFunction(P.first, *P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000540
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000541 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000542 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000543 emitDebugInfoForGlobals();
544
Hans Wennborgb510b452016-06-23 16:33:53 +0000545 // Emit retained types.
546 emitDebugInfoForRetainedTypes();
547
Reid Kleckner5d122f82016-05-25 23:16:12 +0000548 // Switch back to the generic .debug$S section after potentially processing
549 // comdat symbol sections.
550 switchToDebugSectionForSymbol(nullptr);
551
David Majnemer3128b102016-06-15 18:00:01 +0000552 // Emit UDT records for any types used by global variables.
553 if (!GlobalUDTs.empty()) {
Zachary Turner8c099fe2017-05-30 16:36:15 +0000554 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
David Majnemer3128b102016-06-15 18:00:01 +0000555 emitDebugInfoForUDTs(GlobalUDTs);
556 endCVSubsection(SymbolsEnd);
557 }
558
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000559 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000560 OS.AddComment("File index to string table offset subsection");
561 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000562
563 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000564 OS.AddComment("String table");
565 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000566
Reid Kleckner810687c2018-10-12 18:19:06 +0000567 // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
568 // subsection in the generic .debug$S section at the end. There is no
569 // particular reason for this ordering other than to match MSVC.
570 emitBuildInfo();
571
Zachary Turner048f8f92017-12-13 22:33:58 +0000572 // Emit type information and hashes last, so that any types we translate while
573 // emitting function info are included.
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000574 emitTypeInformation();
575
Zachary Turner048f8f92017-12-13 22:33:58 +0000576 if (EmitDebugGlobalHashes)
577 emitTypeGlobalHashes();
578
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000579 clear();
580}
581
Brock Wyma19e17b32018-02-11 21:26:46 +0000582static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
583 unsigned MaxFixedRecordLength = 0xF00) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000584 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
585 // after a fixed length portion of the record. The fixed length portion should
586 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
587 // overall record size is less than the maximum allowed.
Reid Klecknerbb96df62016-10-05 22:36:07 +0000588 SmallString<32> NullTerminatedString(
589 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000590 NullTerminatedString.push_back('\0');
591 OS.EmitBytes(NullTerminatedString);
592}
593
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000594void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000595 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000596 return;
597
Alexandre Ganead9e96742018-04-09 20:17:56 +0000598 // Start the .debug$T or .debug$P section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000599 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000600 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000601
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000602 SmallString<8> CommentPrefix;
603 if (OS.isVerboseAsm()) {
604 CommentPrefix += '\t';
605 CommentPrefix += Asm->MAI->getCommentString();
606 CommentPrefix += ' ';
607 }
608
Zachary Turner526f4f22017-05-19 19:26:58 +0000609 TypeTableCollection Table(TypeTable.records());
610 Optional<TypeIndex> B = Table.getFirst();
611 while (B) {
612 // This will fail if the record data is invalid.
613 CVType Record = Table.getType(*B);
614
Zachary Turner4efa0a42016-11-08 22:24:53 +0000615 if (OS.isVerboseAsm()) {
616 // Emit a block comment describing the type record for readability.
617 SmallString<512> CommentBlock;
618 raw_svector_ostream CommentOS(CommentBlock);
619 ScopedPrinter SP(CommentOS);
620 SP.setPrefix(CommentPrefix);
Zachary Turner526f4f22017-05-19 19:26:58 +0000621 TypeDumpVisitor TDV(Table, &SP, false);
622
623 Error E = codeview::visitTypeRecord(Record, *B, TDV);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000624 if (E) {
625 logAllUnhandledErrors(std::move(E), errs(), "error: ");
626 llvm_unreachable("produced malformed type record");
627 }
628 // emitRawComment will insert its own tab and comment string before
629 // the first line, so strip off our first one. It also prints its own
630 // newline.
631 OS.emitRawComment(
632 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Zachary Turner4efa0a42016-11-08 22:24:53 +0000633 }
Zachary Turner526f4f22017-05-19 19:26:58 +0000634 OS.EmitBinaryData(Record.str_data());
635 B = Table.getNext(*B);
636 }
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000637}
638
Zachary Turner048f8f92017-12-13 22:33:58 +0000639void CodeViewDebug::emitTypeGlobalHashes() {
640 if (TypeTable.empty())
641 return;
642
643 // Start the .debug$H section with the version and hash algorithm, currently
644 // hardcoded to version 0, SHA1.
645 OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
646
647 OS.EmitValueToAlignment(4);
648 OS.AddComment("Magic");
649 OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
650 OS.AddComment("Section Version");
651 OS.EmitIntValue(0, 2);
652 OS.AddComment("Hash Algorithm");
Zachary Turnerc7626662018-05-17 22:55:15 +0000653 OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1_8), 2);
Zachary Turner048f8f92017-12-13 22:33:58 +0000654
655 TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
656 for (const auto &GHR : TypeTable.hashes()) {
657 if (OS.isVerboseAsm()) {
658 // Emit an EOL-comment describing which TypeIndex this hash corresponds
659 // to, as well as the stringified SHA1 hash.
660 SmallString<32> Comment;
661 raw_svector_ostream CommentOS(Comment);
662 CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
663 OS.AddComment(Comment);
664 ++TI;
665 }
Zachary Turnerc7626662018-05-17 22:55:15 +0000666 assert(GHR.Hash.size() == 8);
Zachary Turner048f8f92017-12-13 22:33:58 +0000667 StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
668 GHR.Hash.size());
669 OS.EmitBinaryData(S);
670 }
671}
672
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000673static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
674 switch (DWLang) {
675 case dwarf::DW_LANG_C:
676 case dwarf::DW_LANG_C89:
677 case dwarf::DW_LANG_C99:
678 case dwarf::DW_LANG_C11:
679 case dwarf::DW_LANG_ObjC:
680 return SourceLanguage::C;
681 case dwarf::DW_LANG_C_plus_plus:
682 case dwarf::DW_LANG_C_plus_plus_03:
683 case dwarf::DW_LANG_C_plus_plus_11:
684 case dwarf::DW_LANG_C_plus_plus_14:
685 return SourceLanguage::Cpp;
686 case dwarf::DW_LANG_Fortran77:
687 case dwarf::DW_LANG_Fortran90:
688 case dwarf::DW_LANG_Fortran03:
689 case dwarf::DW_LANG_Fortran08:
690 return SourceLanguage::Fortran;
691 case dwarf::DW_LANG_Pascal83:
692 return SourceLanguage::Pascal;
693 case dwarf::DW_LANG_Cobol74:
694 case dwarf::DW_LANG_Cobol85:
695 return SourceLanguage::Cobol;
696 case dwarf::DW_LANG_Java:
697 return SourceLanguage::Java;
Reid Kleckner898ddf62017-07-24 16:16:42 +0000698 case dwarf::DW_LANG_D:
699 return SourceLanguage::D;
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000700 default:
701 // There's no CodeView representation for this language, and CV doesn't
702 // have an "unknown" option for the language field, so we'll use MASM,
703 // as it's very low level.
704 return SourceLanguage::Masm;
705 }
706}
707
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000708namespace {
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000709struct Version {
710 int Part[4];
711};
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000712} // end anonymous namespace
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000713
714// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
715// the version number.
716static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000717 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000718 int N = 0;
719 for (const char C : Name) {
720 if (isdigit(C)) {
721 V.Part[N] *= 10;
722 V.Part[N] += C - '0';
723 } else if (C == '.') {
724 ++N;
725 if (N >= 4)
726 return V;
727 } else if (N > 0)
728 return V;
729 }
730 return V;
731}
732
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000733void CodeViewDebug::emitCompilerInformation() {
734 MCContext &Context = MMI->getContext();
735 MCSymbol *CompilerBegin = Context.createTempSymbol(),
736 *CompilerEnd = Context.createTempSymbol();
737 OS.AddComment("Record length");
738 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
739 OS.EmitLabel(CompilerBegin);
740 OS.AddComment("Record kind: S_COMPILE3");
741 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
742 uint32_t Flags = 0;
743
744 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
745 const MDNode *Node = *CUs->operands().begin();
746 const auto *CU = cast<DICompileUnit>(Node);
747
748 // The low byte of the flags indicates the source language.
749 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
750 // TODO: Figure out which other flags need to be set.
751
752 OS.AddComment("Flags and language");
753 OS.EmitIntValue(Flags, 4);
754
755 OS.AddComment("CPUType");
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000756 OS.EmitIntValue(static_cast<uint64_t>(TheCPU), 2);
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000757
758 StringRef CompilerVersion = CU->getProducer();
759 Version FrontVer = parseVersion(CompilerVersion);
760 OS.AddComment("Frontend version");
761 for (int N = 0; N < 4; ++N)
762 OS.EmitIntValue(FrontVer.Part[N], 2);
763
764 // Some Microsoft tools, like Binscope, expect a backend version number of at
765 // least 8.something, so we'll coerce the LLVM version into a form that
766 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000767 int Major = 1000 * LLVM_VERSION_MAJOR +
768 10 * LLVM_VERSION_MINOR +
769 LLVM_VERSION_PATCH;
770 // Clamp it for builds that use unusually large version numbers.
771 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
772 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000773 OS.AddComment("Backend version");
774 for (int N = 0; N < 4; ++N)
775 OS.EmitIntValue(BackVer.Part[N], 2);
776
777 OS.AddComment("Null-terminated compiler version string");
778 emitNullTerminatedSymbolName(OS, CompilerVersion);
779
780 OS.EmitLabel(CompilerEnd);
781}
782
Reid Kleckner810687c2018-10-12 18:19:06 +0000783static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
784 StringRef S) {
785 StringIdRecord SIR(TypeIndex(0x0), S);
786 return TypeTable.writeLeafType(SIR);
787}
788
789void CodeViewDebug::emitBuildInfo() {
790 // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
791 // build info. The known prefix is:
792 // - Absolute path of current directory
793 // - Compiler path
794 // - Main source file path, relative to CWD or absolute
795 // - Type server PDB file
796 // - Canonical compiler command line
797 // If frontend and backend compilation are separated (think llc or LTO), it's
798 // not clear if the compiler path should refer to the executable for the
799 // frontend or the backend. Leave it blank for now.
800 TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
801 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
802 const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
803 const auto *CU = cast<DICompileUnit>(Node);
804 const DIFile *MainSourceFile = CU->getFile();
805 BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
806 getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
807 BuildInfoArgs[BuildInfoRecord::SourceFile] =
808 getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
809 // FIXME: Path to compiler and command line. PDB is intentionally blank unless
810 // we implement /Zi type servers.
811 BuildInfoRecord BIR(BuildInfoArgs);
812 TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
813
814 // Make a new .debug$S subsection for the S_BUILDINFO record, which points
815 // from the module symbols into the type stream.
816 MCSymbol *BuildInfoEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
817 OS.AddComment("Record length");
818 OS.EmitIntValue(6, 2);
819 OS.AddComment("Record kind: S_BUILDINFO");
820 OS.EmitIntValue(unsigned(SymbolKind::S_BUILDINFO), 2);
821 OS.AddComment("LF_BUILDINFO index");
822 OS.EmitIntValue(BuildInfoIndex.getIndex(), 4);
823 endCVSubsection(BuildInfoEnd);
824}
825
Reid Kleckner5d122f82016-05-25 23:16:12 +0000826void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000827 if (InlinedSubprograms.empty())
828 return;
829
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000830 OS.AddComment("Inlinee lines subsection");
Zachary Turner8c099fe2017-05-30 16:36:15 +0000831 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000832
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000833 // We emit the checksum info for files. This is used by debuggers to
834 // determine if a pdb matches the source before loading it. Visual Studio,
835 // for instance, will display a warning that the breakpoints are not valid if
836 // the pdb does not match the source.
David Majnemer30579ec2016-02-02 23:18:23 +0000837 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000838 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
839
840 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000841 assert(TypeIndices.count({SP, nullptr}));
842 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000843
David Majnemer30579ec2016-02-02 23:18:23 +0000844 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000845 unsigned FileId = maybeRecordFile(SP->getFile());
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000846 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000847 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000848 OS.AddBlankLine();
David Majnemer30579ec2016-02-02 23:18:23 +0000849 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000850 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000851 OS.AddComment("Offset into filechecksum table");
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000852 OS.EmitCVFileChecksumOffsetDirective(FileId);
David Majnemer30579ec2016-02-02 23:18:23 +0000853 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000854 OS.EmitIntValue(SP->getLine(), 4);
855 }
856
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000857 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000858}
859
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000860void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
861 const DILocation *InlinedAt,
862 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000863 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
864 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000865
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000866 assert(TypeIndices.count({Site.Inlinee, nullptr}));
867 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000868
869 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000870 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000871 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000872 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000873 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000874 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000875
Reid Klecknerdac21b42016-02-03 21:15:48 +0000876 OS.AddComment("PtrParent");
877 OS.EmitIntValue(0, 4);
878 OS.AddComment("PtrEnd");
879 OS.EmitIntValue(0, 4);
880 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000881 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000882
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000883 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
884 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000885
886 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000887 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000888
889 OS.EmitLabel(InlineEnd);
890
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000891 emitLocalVariableList(FI, Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000892
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000893 // Recurse on child inlined call sites before closing the scope.
894 for (const DILocation *ChildSite : Site.ChildSites) {
895 auto I = FI.InlineSites.find(ChildSite);
896 assert(I != FI.InlineSites.end() &&
897 "child site not in function inline site map");
898 emitInlinedCallSite(FI, ChildSite, I->second);
899 }
900
901 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000902 OS.AddComment("Record length");
903 OS.EmitIntValue(2, 2); // RecordLength
904 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000905 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000906}
907
Reid Kleckner5d122f82016-05-25 23:16:12 +0000908void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
909 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
910 // comdat key. A section may be comdat because of -ffunction-sections or
911 // because it is comdat in the IR.
912 MCSectionCOFF *GVSec =
913 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
914 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
915
916 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
917 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
918 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
919
920 OS.SwitchSection(DebugSec);
921
922 // Emit the magic version number if this is the first time we've switched to
923 // this section.
924 if (ComdatDebugSections.insert(DebugSec).second)
925 emitCodeViewMagicVersion();
926}
927
Brock Wyma94ece8f2018-04-16 16:53:57 +0000928// Emit an S_THUNK32/S_END symbol pair for a thunk routine.
929// The only supported thunk ordinal is currently the standard type.
930void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
931 FunctionInfo &FI,
932 const MCSymbol *Fn) {
933 std::string FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
934 const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
935
936 OS.AddComment("Symbol subsection for " + Twine(FuncName));
937 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
938
939 // Emit S_THUNK32
940 MCSymbol *ThunkRecordBegin = MMI->getContext().createTempSymbol(),
941 *ThunkRecordEnd = MMI->getContext().createTempSymbol();
942 OS.AddComment("Record length");
943 OS.emitAbsoluteSymbolDiff(ThunkRecordEnd, ThunkRecordBegin, 2);
944 OS.EmitLabel(ThunkRecordBegin);
945 OS.AddComment("Record kind: S_THUNK32");
946 OS.EmitIntValue(unsigned(SymbolKind::S_THUNK32), 2);
947 OS.AddComment("PtrParent");
948 OS.EmitIntValue(0, 4);
949 OS.AddComment("PtrEnd");
950 OS.EmitIntValue(0, 4);
951 OS.AddComment("PtrNext");
952 OS.EmitIntValue(0, 4);
953 OS.AddComment("Thunk section relative address");
954 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
955 OS.AddComment("Thunk section index");
956 OS.EmitCOFFSectionIndex(Fn);
957 OS.AddComment("Code size");
958 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
959 OS.AddComment("Ordinal");
960 OS.EmitIntValue(unsigned(ordinal), 1);
961 OS.AddComment("Function name");
962 emitNullTerminatedSymbolName(OS, FuncName);
963 // Additional fields specific to the thunk ordinal would go here.
964 OS.EmitLabel(ThunkRecordEnd);
965
966 // Local variables/inlined routines are purposely omitted here. The point of
967 // marking this as a thunk is so Visual Studio will NOT stop in this routine.
968
969 // Emit S_PROC_ID_END
970 const unsigned RecordLengthForSymbolEnd = 2;
971 OS.AddComment("Record length");
972 OS.EmitIntValue(RecordLengthForSymbolEnd, 2);
973 OS.AddComment("Record kind: S_PROC_ID_END");
974 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
975
976 endCVSubsection(SymbolsEnd);
977}
978
Reid Kleckner2214ed82016-01-29 00:49:42 +0000979void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
980 FunctionInfo &FI) {
Brock Wyma31cc1eb2018-01-30 13:16:50 +0000981 // For each function there is a separate subsection which holds the PC to
982 // file:line table.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000983 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000984 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000985
Reid Kleckner5d122f82016-05-25 23:16:12 +0000986 // Switch to the to a comdat section, if appropriate.
987 switchToDebugSectionForSymbol(Fn);
988
Reid Klecknerac945e22016-06-17 16:11:20 +0000989 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000990 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000991 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000992 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000993
Brock Wyma94ece8f2018-04-16 16:53:57 +0000994 if (SP->isThunk()) {
995 emitDebugInfoForThunk(GV, FI, Fn);
996 return;
997 }
998
Reid Klecknerac945e22016-06-17 16:11:20 +0000999 // If we have a display name, build the fully qualified name by walking the
1000 // chain of scopes.
Adrian Prantl9d2f0192017-04-26 23:59:52 +00001001 if (!SP->getName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001002 FuncName =
Adrian Prantl9d2f0192017-04-26 23:59:52 +00001003 getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +00001004
Reid Kleckner3c0ff982016-01-14 00:12:54 +00001005 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +00001006 if (FuncName.empty())
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00001007 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +00001008
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00001009 // Emit FPO data, but only on 32-bit x86. No other platforms use it.
1010 if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
1011 OS.EmitCVFPOData(Fn);
1012
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001013 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001014 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Zachary Turner8c099fe2017-05-30 16:36:15 +00001015 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001016 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001017 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
1018 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +00001019 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +00001020 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001021 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001022
Reid Kleckner4ad127f2016-09-14 21:49:21 +00001023 if (GV->hasLocalLinkage()) {
1024 OS.AddComment("Record kind: S_LPROC32_ID");
1025 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
1026 } else {
1027 OS.AddComment("Record kind: S_GPROC32_ID");
1028 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
1029 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +00001030
David Majnemer30579ec2016-02-02 23:18:23 +00001031 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001032 OS.AddComment("PtrParent");
1033 OS.EmitIntValue(0, 4);
1034 OS.AddComment("PtrEnd");
1035 OS.EmitIntValue(0, 4);
1036 OS.AddComment("PtrNext");
1037 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001038 // This is the important bit that tells the debugger where the function
1039 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +00001040 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +00001041 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001042 OS.AddComment("Offset after prologue");
1043 OS.EmitIntValue(0, 4);
1044 OS.AddComment("Offset before epilogue");
1045 OS.EmitIntValue(0, 4);
1046 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +00001047 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001048 OS.AddComment("Function section relative address");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00001049 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001050 OS.AddComment("Function section index");
1051 OS.EmitCOFFSectionIndex(Fn);
1052 OS.AddComment("Flags");
1053 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +00001054 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001055 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +00001056 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00001057 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001058 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001059
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001060 MCSymbol *FrameProcBegin = MMI->getContext().createTempSymbol(),
1061 *FrameProcEnd = MMI->getContext().createTempSymbol();
1062 OS.AddComment("Record length");
1063 OS.emitAbsoluteSymbolDiff(FrameProcEnd, FrameProcBegin, 2);
1064 OS.EmitLabel(FrameProcBegin);
1065 OS.AddComment("Record kind: S_FRAMEPROC");
1066 OS.EmitIntValue(unsigned(SymbolKind::S_FRAMEPROC), 2);
1067 // Subtract out the CSR size since MSVC excludes that and we include it.
1068 OS.AddComment("FrameSize");
1069 OS.EmitIntValue(FI.FrameSize - FI.CSRSize, 4);
1070 OS.AddComment("Padding");
1071 OS.EmitIntValue(0, 4);
1072 OS.AddComment("Offset of padding");
1073 OS.EmitIntValue(0, 4);
1074 OS.AddComment("Bytes of callee saved registers");
1075 OS.EmitIntValue(FI.CSRSize, 4);
1076 OS.AddComment("Exception handler offset");
1077 OS.EmitIntValue(0, 4);
1078 OS.AddComment("Exception handler section");
1079 OS.EmitIntValue(0, 2);
1080 OS.AddComment("Flags (defines frame register)");
1081 OS.EmitIntValue(uint32_t(FI.FrameProcOpts), 4);
1082 OS.EmitLabel(FrameProcEnd);
1083
1084 emitLocalVariableList(FI, FI.Locals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001085 emitLexicalBlockList(FI.ChildBlocks, FI);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001086
Reid Klecknerf3b9ba42016-01-29 18:16:43 +00001087 // Emit inlined call site information. Only emit functions inlined directly
1088 // into the parent function. We'll emit the other sites recursively as part
1089 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001090 for (const DILocation *InlinedAt : FI.ChildSites) {
1091 auto I = FI.InlineSites.find(InlinedAt);
1092 assert(I != FI.InlineSites.end() &&
1093 "child site not in function inline site map");
1094 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +00001095 }
1096
Reid Klecknere33c94f2017-09-05 20:14:58 +00001097 for (auto Annot : FI.Annotations) {
1098 MCSymbol *Label = Annot.first;
1099 MDTuple *Strs = cast<MDTuple>(Annot.second);
1100 MCSymbol *AnnotBegin = MMI->getContext().createTempSymbol(),
1101 *AnnotEnd = MMI->getContext().createTempSymbol();
1102 OS.AddComment("Record length");
1103 OS.emitAbsoluteSymbolDiff(AnnotEnd, AnnotBegin, 2);
1104 OS.EmitLabel(AnnotBegin);
1105 OS.AddComment("Record kind: S_ANNOTATION");
1106 OS.EmitIntValue(SymbolKind::S_ANNOTATION, 2);
1107 OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
1108 // FIXME: Make sure we don't overflow the max record size.
1109 OS.EmitCOFFSectionIndex(Label);
1110 OS.EmitIntValue(Strs->getNumOperands(), 2);
1111 for (Metadata *MD : Strs->operands()) {
1112 // MDStrings are null terminated, so we can do EmitBytes and get the
1113 // nice .asciz directive.
1114 StringRef Str = cast<MDString>(MD)->getString();
1115 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1116 OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
1117 }
1118 OS.EmitLabel(AnnotEnd);
1119 }
1120
David Majnemer3128b102016-06-15 18:00:01 +00001121 if (SP != nullptr)
1122 emitDebugInfoForUDTs(LocalUDTs);
1123
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001124 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001125 OS.AddComment("Record length");
1126 OS.EmitIntValue(0x0002, 2);
1127 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +00001128 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001129 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001130 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001131
Reid Kleckner2214ed82016-01-29 00:49:42 +00001132 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001133 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001134}
1135
Reid Kleckner876330d2016-02-12 21:48:30 +00001136CodeViewDebug::LocalVarDefRange
1137CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
1138 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +00001139 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +00001140 DR.DataOffset = Offset;
1141 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00001142 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001143 DR.StructOffset = 0;
1144 DR.CVRegister = CVRegister;
1145 return DR;
1146}
1147
Matthias Braunef331ef2016-11-30 23:48:50 +00001148void CodeViewDebug::collectVariableInfoFromMFTable(
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001149 DenseSet<InlinedEntity> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +00001150 const MachineFunction &MF = *Asm->MF;
1151 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +00001152 const TargetFrameLowering *TFI = TSI.getFrameLowering();
1153 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1154
Matthias Braunef331ef2016-11-30 23:48:50 +00001155 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001156 if (!VI.Var)
1157 continue;
1158 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1159 "Expected inlined-at fields to agree");
1160
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001161 Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001162 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1163
1164 // If variable scope is not found then skip this variable.
1165 if (!Scope)
1166 continue;
1167
Reid Klecknerb5fced72017-05-09 19:59:29 +00001168 // If the variable has an attached offset expression, extract it.
1169 // FIXME: Try to handle DW_OP_deref as well.
1170 int64_t ExprOffset = 0;
1171 if (VI.Expr)
1172 if (!VI.Expr->extractIfOffset(ExprOffset))
1173 continue;
1174
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001175 // Get the frame register used and the offset.
1176 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001177 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1178 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001179
1180 // Calculate the label ranges.
Reid Klecknerb5fced72017-05-09 19:59:29 +00001181 LocalVarDefRange DefRange =
1182 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001183 for (const InsnRange &Range : Scope->getRanges()) {
1184 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1185 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +00001186 End = End ? End : Asm->getFunctionEnd();
1187 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001188 }
1189
Reid Kleckner876330d2016-02-12 21:48:30 +00001190 LocalVariable Var;
1191 Var.DIVar = VI.Var;
1192 Var.DefRanges.emplace_back(std::move(DefRange));
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001193 recordLocalVariable(std::move(Var), Scope);
Reid Kleckner876330d2016-02-12 21:48:30 +00001194 }
1195}
1196
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001197static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1198 return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1199}
1200
1201static bool needsReferenceType(const DbgVariableLocation &Loc) {
1202 return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1203}
1204
Bob Haarman223303c2017-08-29 20:59:25 +00001205void CodeViewDebug::calculateRanges(
1206 LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
1207 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1208
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001209 // Calculate the definition ranges.
Bob Haarman223303c2017-08-29 20:59:25 +00001210 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1211 const InsnRange &Range = *I;
1212 const MachineInstr *DVInst = Range.first;
1213 assert(DVInst->isDebugValue() && "Invalid History entry");
1214 // FIXME: Find a way to represent constant variables, since they are
1215 // relatively common.
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001216 Optional<DbgVariableLocation> Location =
1217 DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1218 if (!Location)
Bob Haarmana88bce12017-08-29 21:01:55 +00001219 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001220
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001221 // CodeView can only express variables in register and variables in memory
1222 // at a constant offset from a register. However, for variables passed
1223 // indirectly by pointer, it is common for that pointer to be spilled to a
1224 // stack location. For the special case of one offseted load followed by a
1225 // zero offset load (a pointer spilled to the stack), we change the type of
1226 // the local variable from a value type to a reference type. This tricks the
1227 // debugger into doing the load for us.
1228 if (Var.UseReferenceType) {
1229 // We're using a reference type. Drop the last zero offset load.
1230 if (canUseReferenceType(*Location))
1231 Location->LoadChain.pop_back();
1232 else
1233 continue;
1234 } else if (needsReferenceType(*Location)) {
1235 // This location can't be expressed without switching to a reference type.
1236 // Start over using that.
1237 Var.UseReferenceType = true;
Bob Haarman223303c2017-08-29 20:59:25 +00001238 Var.DefRanges.clear();
1239 calculateRanges(Var, Ranges);
1240 return;
1241 }
1242
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001243 // We can only handle a register or an offseted load of a register.
1244 if (Location->Register == 0 || Location->LoadChain.size() > 1)
Bob Haarman223303c2017-08-29 20:59:25 +00001245 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001246 {
1247 LocalVarDefRange DR;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001248 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001249 DR.InMemory = !Location->LoadChain.empty();
1250 DR.DataOffset =
1251 !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001252 if (Location->FragmentInfo) {
Bob Haarman223303c2017-08-29 20:59:25 +00001253 DR.IsSubfield = true;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001254 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
Bob Haarman223303c2017-08-29 20:59:25 +00001255 } else {
1256 DR.IsSubfield = false;
1257 DR.StructOffset = 0;
1258 }
1259
1260 if (Var.DefRanges.empty() ||
1261 Var.DefRanges.back().isDifferentLocation(DR)) {
1262 Var.DefRanges.emplace_back(std::move(DR));
1263 }
1264 }
1265
1266 // Compute the label range.
1267 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1268 const MCSymbol *End = getLabelAfterInsn(Range.second);
1269 if (!End) {
1270 // This range is valid until the next overlapping bitpiece. In the
1271 // common case, ranges will not be bitpieces, so they will overlap.
1272 auto J = std::next(I);
1273 const DIExpression *DIExpr = DVInst->getDebugExpression();
1274 while (J != E &&
Bjorn Petterssona223f8152018-03-12 18:02:39 +00001275 !DIExpr->fragmentsOverlap(J->first->getDebugExpression()))
Bob Haarman223303c2017-08-29 20:59:25 +00001276 ++J;
1277 if (J != E)
1278 End = getLabelBeforeInsn(J->first);
1279 else
1280 End = Asm->getFunctionEnd();
1281 }
1282
1283 // If the last range end is our begin, just extend the last range.
1284 // Otherwise make a new range.
1285 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1286 Var.DefRanges.back().Ranges;
1287 if (!R.empty() && R.back().second == Begin)
1288 R.back().second = End;
1289 else
1290 R.emplace_back(Begin, End);
1291
1292 // FIXME: Do more range combining.
1293 }
1294}
1295
Reid Kleckner876330d2016-02-12 21:48:30 +00001296void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001297 DenseSet<InlinedEntity> Processed;
Reid Kleckner876330d2016-02-12 21:48:30 +00001298 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +00001299 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +00001300
Reid Kleckner876330d2016-02-12 21:48:30 +00001301 for (const auto &I : DbgValues) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001302 InlinedEntity IV = I.first;
Reid Kleckner876330d2016-02-12 21:48:30 +00001303 if (Processed.count(IV))
1304 continue;
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001305 const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
Reid Kleckner876330d2016-02-12 21:48:30 +00001306 const DILocation *InlinedAt = IV.second;
1307
1308 // Instruction ranges, specifying where IV is accessible.
1309 const auto &Ranges = I.second;
1310
1311 LexicalScope *Scope = nullptr;
1312 if (InlinedAt)
1313 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1314 else
1315 Scope = LScopes.findLexicalScope(DIVar->getScope());
1316 // If variable scope is not found then skip this variable.
1317 if (!Scope)
1318 continue;
1319
1320 LocalVariable Var;
1321 Var.DIVar = DIVar;
1322
Bob Haarman223303c2017-08-29 20:59:25 +00001323 calculateRanges(Var, Ranges);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001324 recordLocalVariable(std::move(Var), Scope);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001325 }
1326}
1327
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001328void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001329 const TargetSubtargetInfo &TSI = MF->getSubtarget();
1330 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1331 const MachineFrameInfo &MFI = MF->getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00001332 const Function &GV = MF->getFunction();
Reid Kleckner55baeef2018-03-15 21:12:21 +00001333 auto Insertion = FnDebugInfo.insert({&GV, llvm::make_unique<FunctionInfo>()});
Reid Klecknere9dc30d2018-03-15 21:18:42 +00001334 assert(Insertion.second && "function already has info");
Reid Kleckner55baeef2018-03-15 21:12:21 +00001335 CurFn = Insertion.first->second.get();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001336 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001337 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001338
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001339 // The S_FRAMEPROC record reports the stack size, and how many bytes of
1340 // callee-saved registers were used. For targets that don't use a PUSH
1341 // instruction (AArch64), this will be zero.
1342 CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1343 CurFn->FrameSize = MFI.getStackSize();
Reid Kleckner2bcb2882018-11-03 00:41:52 +00001344 CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00001345 CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001346
1347 // For this function S_FRAMEPROC record, figure out which codeview register
1348 // will be the frame pointer.
1349 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1350 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1351 if (CurFn->FrameSize > 0) {
1352 if (!TSI.getFrameLowering()->hasFP(*MF)) {
1353 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1354 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1355 } else {
1356 // If there is an FP, parameters are always relative to it.
1357 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00001358 if (CurFn->HasStackRealignment) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001359 // If the stack needs realignment, locals are relative to SP or VFRAME.
1360 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1361 } else {
1362 // Otherwise, locals are relative to EBP, and we probably have VLAs or
1363 // other stack adjustments.
1364 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1365 }
1366 }
1367 }
1368
1369 // Compute other frame procedure options.
1370 FrameProcedureOptions FPO = FrameProcedureOptions::None;
1371 if (MFI.hasVarSizedObjects())
1372 FPO |= FrameProcedureOptions::HasAlloca;
1373 if (MF->exposesReturnsTwice())
1374 FPO |= FrameProcedureOptions::HasSetJmp;
1375 // FIXME: Set HasLongJmp if we ever track that info.
1376 if (MF->hasInlineAsm())
1377 FPO |= FrameProcedureOptions::HasInlineAssembly;
1378 if (GV.hasPersonalityFn()) {
1379 if (isAsynchronousEHPersonality(
1380 classifyEHPersonality(GV.getPersonalityFn())))
1381 FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
1382 else
1383 FPO |= FrameProcedureOptions::HasExceptionHandling;
1384 }
1385 if (GV.hasFnAttribute(Attribute::InlineHint))
1386 FPO |= FrameProcedureOptions::MarkedInline;
1387 if (GV.hasFnAttribute(Attribute::Naked))
1388 FPO |= FrameProcedureOptions::Naked;
1389 if (MFI.hasStackProtectorIndex())
1390 FPO |= FrameProcedureOptions::SecurityChecks;
1391 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1392 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1393 if (Asm->TM.getOptLevel() != CodeGenOpt::None && !GV.optForSize() &&
1394 !GV.hasFnAttribute(Attribute::OptimizeNone))
1395 FPO |= FrameProcedureOptions::OptimizedForSpeed;
1396 // FIXME: Set GuardCfg when it is implemented.
1397 CurFn->FrameProcOpts = FPO;
1398
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001399 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1400
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001401 // Find the end of the function prolog. First known non-DBG_VALUE and
1402 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001403 // FIXME: is there a simpler a way to do this? Can we just search
1404 // for the first instruction of the function, not the last of the prolog?
1405 DebugLoc PrologEndLoc;
1406 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001407 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001408 for (const auto &MI : MBB) {
Adrian Prantlfb31da12017-05-22 20:47:09 +00001409 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001410 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001411 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001412 break;
Adrian Prantlfb31da12017-05-22 20:47:09 +00001413 } else if (!MI.isMetaInstruction()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001414 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001415 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001416 }
1417 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001418
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001419 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001420 if (PrologEndLoc && !EmptyPrologue) {
1421 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001422 maybeRecordLocation(FnStartDL, MF);
1423 }
1424}
1425
Zachary Turnera7b04172017-08-28 18:49:04 +00001426static bool shouldEmitUdt(const DIType *T) {
Zachary Turner37c74742017-09-05 22:06:39 +00001427 if (!T)
1428 return false;
1429
1430 // MSVC does not emit UDTs for typedefs that are scoped to classes.
1431 if (T->getTag() == dwarf::DW_TAG_typedef) {
1432 if (DIScope *Scope = T->getScope().resolve()) {
1433 switch (Scope->getTag()) {
1434 case dwarf::DW_TAG_structure_type:
1435 case dwarf::DW_TAG_class_type:
1436 case dwarf::DW_TAG_union_type:
1437 return false;
1438 }
1439 }
1440 }
1441
Zachary Turnera7b04172017-08-28 18:49:04 +00001442 while (true) {
1443 if (!T || T->isForwardDecl())
1444 return false;
1445
1446 const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1447 if (!DT)
1448 return true;
1449 T = DT->getBaseType().resolve();
1450 }
1451 return true;
1452}
1453
1454void CodeViewDebug::addToUDTs(const DIType *Ty) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001455 // Don't record empty UDTs.
1456 if (Ty->getName().empty())
1457 return;
Zachary Turnera7b04172017-08-28 18:49:04 +00001458 if (!shouldEmitUdt(Ty))
1459 return;
Reid Klecknerad56ea32016-07-01 22:24:51 +00001460
Hans Wennborg4b63a982016-06-23 22:57:25 +00001461 SmallVector<StringRef, 5> QualifiedNameComponents;
1462 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1463 Ty->getScope().resolve(), QualifiedNameComponents);
1464
1465 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001466 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001467
Zachary Turnera7b04172017-08-28 18:49:04 +00001468 if (ClosestSubprogram == nullptr) {
1469 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1470 } else if (ClosestSubprogram == CurrentSubprogram) {
1471 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1472 }
Hans Wennborg4b63a982016-06-23 22:57:25 +00001473
1474 // TODO: What if the ClosestSubprogram is neither null or the current
1475 // subprogram? Currently, the UDT just gets dropped on the floor.
1476 //
1477 // The current behavior is not desirable. To get maximal fidelity, we would
1478 // need to perform all type translation before beginning emission of .debug$S
1479 // and then make LocalUDTs a member of FunctionInfo
1480}
1481
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001482TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001483 // Generic dispatch for lowering an unknown type.
1484 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001485 case dwarf::DW_TAG_array_type:
1486 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001487 case dwarf::DW_TAG_typedef:
1488 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001489 case dwarf::DW_TAG_base_type:
1490 return lowerTypeBasic(cast<DIBasicType>(Ty));
1491 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001492 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1493 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1494 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001495 case dwarf::DW_TAG_reference_type:
1496 case dwarf::DW_TAG_rvalue_reference_type:
1497 return lowerTypePointer(cast<DIDerivedType>(Ty));
1498 case dwarf::DW_TAG_ptr_to_member_type:
1499 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
Reid Kleckner3acdc672018-02-27 22:08:15 +00001500 case dwarf::DW_TAG_restrict_type:
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001501 case dwarf::DW_TAG_const_type:
1502 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001503 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001504 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001505 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001506 if (ClassTy) {
1507 // The member function type of a member function pointer has no
1508 // ThisAdjustment.
1509 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001510 /*ThisAdjustment=*/0,
1511 /*IsStaticMethod=*/false);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001512 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001513 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001514 case dwarf::DW_TAG_enumeration_type:
1515 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001516 case dwarf::DW_TAG_class_type:
1517 case dwarf::DW_TAG_structure_type:
1518 return lowerTypeClass(cast<DICompositeType>(Ty));
1519 case dwarf::DW_TAG_union_type:
1520 return lowerTypeUnion(cast<DICompositeType>(Ty));
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001521 case dwarf::DW_TAG_unspecified_type:
Zachary Turner56a5a0c2018-11-01 04:02:41 +00001522 if (Ty->getName() == "decltype(nullptr)")
1523 return TypeIndex::NullptrT();
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001524 return TypeIndex::None();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001525 default:
1526 // Use the null type index.
1527 return TypeIndex();
1528 }
1529}
1530
David Majnemerd065e232016-06-02 06:21:37 +00001531TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001532 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1533 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001534 StringRef TypeName = Ty->getName();
1535
Zachary Turnera7b04172017-08-28 18:49:04 +00001536 addToUDTs(Ty);
David Majnemer3128b102016-06-15 18:00:01 +00001537
David Majnemerd065e232016-06-02 06:21:37 +00001538 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001539 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001540 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001541 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001542 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001543 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001544
David Majnemerd065e232016-06-02 06:21:37 +00001545 return UnderlyingTypeIndex;
1546}
1547
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001548TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1549 DITypeRef ElementTypeRef = Ty->getBaseType();
1550 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1551 // IndexType is size_t, which depends on the bitness of the target.
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001552 TypeIndex IndexType = getPointerSizeInBytes() == 8
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001553 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1554 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001555
1556 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1557
Amjad Aboudacee5682016-07-12 12:06:34 +00001558 // Add subranges to array type.
1559 DINodeArray Elements = Ty->getElements();
1560 for (int i = Elements.size() - 1; i >= 0; --i) {
1561 const DINode *Element = Elements[i];
1562 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1563
1564 const DISubrange *Subrange = cast<DISubrange>(Element);
1565 assert(Subrange->getLowerBound() == 0 &&
1566 "codeview doesn't support subranges with lower bounds");
Sander de Smalenfdf40912018-01-24 09:56:07 +00001567 int64_t Count = -1;
1568 if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
1569 Count = CI->getSExtValue();
Amjad Aboudacee5682016-07-12 12:06:34 +00001570
Reid Klecknercd7bba02017-09-13 23:30:01 +00001571 // Forward declarations of arrays without a size and VLAs use a count of -1.
1572 // Emit a count of zero in these cases to match what MSVC does for arrays
1573 // without a size. MSVC doesn't support VLAs, so it's not clear what we
1574 // should do for them even if we could distinguish them.
Reid Kleckner6b78e162017-03-24 23:28:42 +00001575 if (Count == -1)
Reid Kleckner89af1122017-09-13 21:54:20 +00001576 Count = 0;
Amjad Aboudacee5682016-07-12 12:06:34 +00001577
Amjad Aboudacee5682016-07-12 12:06:34 +00001578 // Update the element size and element type index for subsequent subranges.
1579 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001580
1581 // If this is the outermost array, use the size from the array. It will be
Reid Kleckner6b78e162017-03-24 23:28:42 +00001582 // more accurate if we had a VLA or an incomplete element type size.
Reid Kleckner10762882016-09-09 17:29:36 +00001583 uint64_t ArraySize =
1584 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1585
1586 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001587 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00001588 ElementTypeIndex = TypeTable.writeLeafType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001589 }
1590
Amjad Aboudacee5682016-07-12 12:06:34 +00001591 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001592}
1593
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001594TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1595 TypeIndex Index;
1596 dwarf::TypeKind Kind;
1597 uint32_t ByteSize;
1598
1599 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001600 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001601
1602 SimpleTypeKind STK = SimpleTypeKind::None;
1603 switch (Kind) {
1604 case dwarf::DW_ATE_address:
1605 // FIXME: Translate
1606 break;
1607 case dwarf::DW_ATE_boolean:
1608 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001609 case 1: STK = SimpleTypeKind::Boolean8; break;
1610 case 2: STK = SimpleTypeKind::Boolean16; break;
1611 case 4: STK = SimpleTypeKind::Boolean32; break;
1612 case 8: STK = SimpleTypeKind::Boolean64; break;
1613 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001614 }
1615 break;
1616 case dwarf::DW_ATE_complex_float:
1617 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001618 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001619 case 4: STK = SimpleTypeKind::Complex32; break;
1620 case 8: STK = SimpleTypeKind::Complex64; break;
1621 case 10: STK = SimpleTypeKind::Complex80; break;
1622 case 16: STK = SimpleTypeKind::Complex128; break;
1623 }
1624 break;
1625 case dwarf::DW_ATE_float:
1626 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001627 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001628 case 4: STK = SimpleTypeKind::Float32; break;
1629 case 6: STK = SimpleTypeKind::Float48; break;
1630 case 8: STK = SimpleTypeKind::Float64; break;
1631 case 10: STK = SimpleTypeKind::Float80; break;
1632 case 16: STK = SimpleTypeKind::Float128; break;
1633 }
1634 break;
1635 case dwarf::DW_ATE_signed:
1636 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001637 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1638 case 2: STK = SimpleTypeKind::Int16Short; break;
1639 case 4: STK = SimpleTypeKind::Int32; break;
1640 case 8: STK = SimpleTypeKind::Int64Quad; break;
1641 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001642 }
1643 break;
1644 case dwarf::DW_ATE_unsigned:
1645 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001646 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1647 case 2: STK = SimpleTypeKind::UInt16Short; break;
1648 case 4: STK = SimpleTypeKind::UInt32; break;
1649 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1650 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001651 }
1652 break;
1653 case dwarf::DW_ATE_UTF:
1654 switch (ByteSize) {
1655 case 2: STK = SimpleTypeKind::Character16; break;
1656 case 4: STK = SimpleTypeKind::Character32; break;
1657 }
1658 break;
1659 case dwarf::DW_ATE_signed_char:
1660 if (ByteSize == 1)
1661 STK = SimpleTypeKind::SignedCharacter;
1662 break;
1663 case dwarf::DW_ATE_unsigned_char:
1664 if (ByteSize == 1)
1665 STK = SimpleTypeKind::UnsignedCharacter;
1666 break;
1667 default:
1668 break;
1669 }
1670
1671 // Apply some fixups based on the source-level type name.
1672 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1673 STK = SimpleTypeKind::Int32Long;
1674 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1675 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001676 if (STK == SimpleTypeKind::UInt16Short &&
1677 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001678 STK = SimpleTypeKind::WideCharacter;
1679 if ((STK == SimpleTypeKind::SignedCharacter ||
1680 STK == SimpleTypeKind::UnsignedCharacter) &&
1681 Ty->getName() == "char")
1682 STK = SimpleTypeKind::NarrowCharacter;
1683
1684 return TypeIndex(STK);
1685}
1686
Reid Kleckner3acdc672018-02-27 22:08:15 +00001687TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1688 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001689 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1690
Reid Kleckner3acdc672018-02-27 22:08:15 +00001691 // Pointers to simple types without any options can use SimpleTypeMode, rather
1692 // than having a dedicated pointer type record.
1693 if (PointeeTI.isSimple() && PO == PointerOptions::None &&
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001694 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1695 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1696 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1697 ? SimpleTypeMode::NearPointer64
1698 : SimpleTypeMode::NearPointer32;
1699 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1700 }
1701
1702 PointerKind PK =
1703 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1704 PointerMode PM = PointerMode::Pointer;
1705 switch (Ty->getTag()) {
1706 default: llvm_unreachable("not a pointer tag type");
1707 case dwarf::DW_TAG_pointer_type:
1708 PM = PointerMode::Pointer;
1709 break;
1710 case dwarf::DW_TAG_reference_type:
1711 PM = PointerMode::LValueReference;
1712 break;
1713 case dwarf::DW_TAG_rvalue_reference_type:
1714 PM = PointerMode::RValueReference;
1715 break;
1716 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001717
Zachary Turner38265662018-11-20 22:13:23 +00001718 if (Ty->isObjectPointer())
1719 PO |= PointerOptions::Const;
1720
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001721 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00001722 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001723}
1724
Reid Kleckner6fa15462016-06-17 22:14:39 +00001725static PointerToMemberRepresentation
1726translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1727 // SizeInBytes being zero generally implies that the member pointer type was
1728 // incomplete, which can happen if it is part of a function prototype. In this
1729 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001730 if (IsPMF) {
1731 switch (Flags & DINode::FlagPtrToMemberRep) {
1732 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001733 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1734 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001735 case DINode::FlagSingleInheritance:
1736 return PointerToMemberRepresentation::SingleInheritanceFunction;
1737 case DINode::FlagMultipleInheritance:
1738 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1739 case DINode::FlagVirtualInheritance:
1740 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1741 }
1742 } else {
1743 switch (Flags & DINode::FlagPtrToMemberRep) {
1744 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001745 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1746 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001747 case DINode::FlagSingleInheritance:
1748 return PointerToMemberRepresentation::SingleInheritanceData;
1749 case DINode::FlagMultipleInheritance:
1750 return PointerToMemberRepresentation::MultipleInheritanceData;
1751 case DINode::FlagVirtualInheritance:
1752 return PointerToMemberRepresentation::VirtualInheritanceData;
1753 }
1754 }
1755 llvm_unreachable("invalid ptr to member representation");
1756}
1757
Reid Kleckner3acdc672018-02-27 22:08:15 +00001758TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1759 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001760 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1761 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001762 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001763 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1764 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001765 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1766 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1767 : PointerMode::PointerToDataMember;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001768
Reid Kleckner6fa15462016-06-17 22:14:39 +00001769 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1770 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1771 MemberPointerInfo MPI(
1772 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001773 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner6900de12017-11-28 18:33:17 +00001774 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001775}
1776
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001777/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1778/// have a translation, use the NearC convention.
1779static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1780 switch (DwarfCC) {
1781 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1782 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1783 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1784 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1785 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1786 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1787 }
1788 return CallingConvention::NearC;
1789}
1790
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001791TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1792 ModifierOptions Mods = ModifierOptions::None;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001793 PointerOptions PO = PointerOptions::None;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001794 bool IsModifier = true;
1795 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001796 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001797 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001798 switch (BaseTy->getTag()) {
1799 case dwarf::DW_TAG_const_type:
1800 Mods |= ModifierOptions::Const;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001801 PO |= PointerOptions::Const;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001802 break;
1803 case dwarf::DW_TAG_volatile_type:
1804 Mods |= ModifierOptions::Volatile;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001805 PO |= PointerOptions::Volatile;
1806 break;
1807 case dwarf::DW_TAG_restrict_type:
1808 // Only pointer types be marked with __restrict. There is no known flag
1809 // for __restrict in LF_MODIFIER records.
1810 PO |= PointerOptions::Restrict;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001811 break;
1812 default:
1813 IsModifier = false;
1814 break;
1815 }
1816 if (IsModifier)
1817 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1818 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001819
1820 // Check if the inner type will use an LF_POINTER record. If so, the
1821 // qualifiers will go in the LF_POINTER record. This comes up for types like
1822 // 'int *const' and 'int *__restrict', not the more common cases like 'const
1823 // char *'.
1824 if (BaseTy) {
1825 switch (BaseTy->getTag()) {
1826 case dwarf::DW_TAG_pointer_type:
1827 case dwarf::DW_TAG_reference_type:
1828 case dwarf::DW_TAG_rvalue_reference_type:
1829 return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
1830 case dwarf::DW_TAG_ptr_to_member_type:
1831 return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
1832 default:
1833 break;
1834 }
1835 }
1836
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001837 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Reid Kleckner3acdc672018-02-27 22:08:15 +00001838
1839 // Return the base type index if there aren't any modifiers. For example, the
1840 // metadata could contain restrict wrappers around non-pointer types.
1841 if (Mods == ModifierOptions::None)
1842 return ModifiedTI;
1843
Zachary Turner4efa0a42016-11-08 22:24:53 +00001844 ModifierRecord MR(ModifiedTI, Mods);
Zachary Turner6900de12017-11-28 18:33:17 +00001845 return TypeTable.writeLeafType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001846}
1847
David Majnemer75c3ebf2016-06-02 17:13:53 +00001848TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1849 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1850 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1851 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1852
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001853 // MSVC uses type none for variadic argument.
1854 if (ReturnAndArgTypeIndices.size() > 1 &&
1855 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1856 ReturnAndArgTypeIndices.back() = TypeIndex::None();
1857 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001858 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1859 ArrayRef<TypeIndex> ArgTypeIndices = None;
1860 if (!ReturnAndArgTypeIndices.empty()) {
1861 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1862 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1863 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1864 }
1865
1866 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001867 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001868
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001869 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1870
Aaron Smith802b0332018-10-02 20:21:05 +00001871 FunctionOptions FO = getFunctionOptions(Ty);
1872 ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
1873 ArgListIndex);
Zachary Turner6900de12017-11-28 18:33:17 +00001874 return TypeTable.writeLeafType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001875}
1876
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001877TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001878 const DIType *ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001879 int ThisAdjustment,
Aaron Smith802b0332018-10-02 20:21:05 +00001880 bool IsStaticMethod,
1881 FunctionOptions FO) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001882 // Lower the containing class type.
1883 TypeIndex ClassType = getTypeIndex(ClassTy);
1884
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001885 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1886 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1887 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1888
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001889 // MSVC uses type none for variadic argument.
1890 if (ReturnAndArgTypeIndices.size() > 1 &&
1891 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1892 ReturnAndArgTypeIndices.back() = TypeIndex::None();
1893 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001894 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1895 ArrayRef<TypeIndex> ArgTypeIndices = None;
1896 if (!ReturnAndArgTypeIndices.empty()) {
1897 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1898 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1899 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1900 }
Reid Kleckner87288b92017-09-15 00:59:07 +00001901 TypeIndex ThisTypeIndex;
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001902 if (!IsStaticMethod && !ArgTypeIndices.empty()) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001903 ThisTypeIndex = ArgTypeIndices.front();
1904 ArgTypeIndices = ArgTypeIndices.drop_front();
1905 }
1906
1907 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001908 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001909
1910 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1911
Aaron Smith802b0332018-10-02 20:21:05 +00001912 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
1913 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
Zachary Turner6900de12017-11-28 18:33:17 +00001914 return TypeTable.writeLeafType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001915}
1916
Reid Kleckner9dac4732016-08-31 15:59:30 +00001917TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001918 unsigned VSlotCount =
1919 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
Reid Kleckner9dac4732016-08-31 15:59:30 +00001920 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001921
1922 VFTableShapeRecord VFTSR(Slots);
Zachary Turner6900de12017-11-28 18:33:17 +00001923 return TypeTable.writeLeafType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001924}
1925
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001926static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1927 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001928 case DINode::FlagPrivate: return MemberAccess::Private;
1929 case DINode::FlagPublic: return MemberAccess::Public;
1930 case DINode::FlagProtected: return MemberAccess::Protected;
1931 case 0:
1932 // If there was no explicit access control, provide the default for the tag.
1933 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1934 : MemberAccess::Public;
1935 }
1936 llvm_unreachable("access flags are exclusive");
1937}
1938
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001939static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1940 if (SP->isArtificial())
1941 return MethodOptions::CompilerGenerated;
1942
1943 // FIXME: Handle other MethodOptions.
1944
1945 return MethodOptions::None;
1946}
1947
1948static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1949 bool Introduced) {
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001950 if (SP->getFlags() & DINode::FlagStaticMember)
1951 return MethodKind::Static;
1952
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001953 switch (SP->getVirtuality()) {
1954 case dwarf::DW_VIRTUALITY_none:
1955 break;
1956 case dwarf::DW_VIRTUALITY_virtual:
1957 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1958 case dwarf::DW_VIRTUALITY_pure_virtual:
1959 return Introduced ? MethodKind::PureIntroducingVirtual
1960 : MethodKind::PureVirtual;
1961 default:
1962 llvm_unreachable("unhandled virtuality case");
1963 }
1964
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001965 return MethodKind::Vanilla;
1966}
1967
Reid Klecknera8d57402016-06-03 15:58:20 +00001968static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1969 switch (Ty->getTag()) {
1970 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1971 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1972 }
1973 llvm_unreachable("unexpected tag");
1974}
1975
Reid Klecknere092dad2016-07-02 00:11:07 +00001976/// Return ClassOptions that should be present on both the forward declaration
1977/// and the defintion of a tag type.
1978static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1979 ClassOptions CO = ClassOptions::None;
1980
1981 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001982 // appear to give every type a linkage name, which may be problematic for us.
1983 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001984 if (!Ty->getIdentifier().empty())
1985 CO |= ClassOptions::HasUniqueName;
1986
1987 // Put the Nested flag on a type if it appears immediately inside a tag type.
1988 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1989 // here. That flag is only set on definitions, and not forward declarations.
1990 const DIScope *ImmediateScope = Ty->getScope().resolve();
1991 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1992 CO |= ClassOptions::Nested;
1993
Aaron Smithda0602c2018-10-02 20:28:15 +00001994 // Put the Scoped flag on function-local types. MSVC puts this flag for enum
1995 // type only when it has an immediate function scope. Clang never puts enums
1996 // inside DILexicalBlock scopes. Enum types, as generated by clang, are
1997 // always in function, class, or file scopes.
1998 if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
1999 if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
Reid Klecknere092dad2016-07-02 00:11:07 +00002000 CO |= ClassOptions::Scoped;
Aaron Smithda0602c2018-10-02 20:28:15 +00002001 } else {
2002 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
2003 Scope = Scope->getScope().resolve()) {
2004 if (isa<DISubprogram>(Scope)) {
2005 CO |= ClassOptions::Scoped;
2006 break;
2007 }
Reid Klecknere092dad2016-07-02 00:11:07 +00002008 }
2009 }
2010
2011 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00002012}
2013
Aaron Smith122d9e72018-03-06 18:20:22 +00002014void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
2015 switch (Ty->getTag()) {
2016 case dwarf::DW_TAG_class_type:
2017 case dwarf::DW_TAG_structure_type:
2018 case dwarf::DW_TAG_union_type:
2019 case dwarf::DW_TAG_enumeration_type:
2020 break;
2021 default:
2022 return;
2023 }
2024
2025 if (const auto *File = Ty->getFile()) {
2026 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
2027 TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
2028
2029 UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
2030 TypeTable.writeLeafType(USLR);
2031 }
2032}
2033
David Majnemer979cb882016-06-16 21:32:16 +00002034TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00002035 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00002036 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00002037 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00002038
David Majnemerda9548f2016-06-17 16:13:21 +00002039 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00002040 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00002041 } else {
Zachary Turner6900de12017-11-28 18:33:17 +00002042 ContinuationRecordBuilder ContinuationBuilder;
2043 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
David Majnemerda9548f2016-06-17 16:13:21 +00002044 for (const DINode *Element : Ty->getElements()) {
2045 // We assume that the frontend provides all members in source declaration
2046 // order, which is what MSVC does.
2047 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002048 EnumeratorRecord ER(MemberAccess::Public,
2049 APSInt::getUnsigned(Enumerator->getValue()),
2050 Enumerator->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00002051 ContinuationBuilder.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00002052 EnumeratorCount++;
2053 }
2054 }
Zachary Turner6900de12017-11-28 18:33:17 +00002055 FTI = TypeTable.insertRecord(ContinuationBuilder);
David Majnemerda9548f2016-06-17 16:13:21 +00002056 }
David Majnemer979cb882016-06-16 21:32:16 +00002057
David Majnemer6bdc24e2016-07-01 23:12:45 +00002058 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00002059
Zachary Turner4efa0a42016-11-08 22:24:53 +00002060 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2061 getTypeIndex(Ty->getBaseType()));
Aaron Smith122d9e72018-03-06 18:20:22 +00002062 TypeIndex EnumTI = TypeTable.writeLeafType(ER);
2063
2064 addUDTSrcLine(Ty, EnumTI);
2065
2066 return EnumTI;
David Majnemer979cb882016-06-16 21:32:16 +00002067}
2068
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002069//===----------------------------------------------------------------------===//
2070// ClassInfo
2071//===----------------------------------------------------------------------===//
2072
2073struct llvm::ClassInfo {
2074 struct MemberInfo {
2075 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00002076 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002077 };
2078 // [MemberInfo]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002079 using MemberList = std::vector<MemberInfo>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002080
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002081 using MethodsList = TinyPtrVector<const DISubprogram *>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002082 // MethodName -> MethodsList
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002083 using MethodsMap = MapVector<MDString *, MethodsList>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002084
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002085 /// Base classes.
2086 std::vector<const DIDerivedType *> Inheritance;
2087
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002088 /// Direct members.
2089 MemberList Members;
2090 // Direct overloaded methods gathered by name.
2091 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002092
Reid Kleckner9dac4732016-08-31 15:59:30 +00002093 TypeIndex VShapeTI;
2094
Reid Klecknere2e82062017-08-08 20:30:14 +00002095 std::vector<const DIType *> NestedTypes;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002096};
2097
2098void CodeViewDebug::clear() {
2099 assert(CurFn == nullptr);
2100 FileIdMap.clear();
2101 FnDebugInfo.clear();
2102 FileToFilepathMap.clear();
2103 LocalUDTs.clear();
2104 GlobalUDTs.clear();
2105 TypeIndices.clear();
2106 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002107}
2108
2109void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2110 const DIDerivedType *DDTy) {
2111 if (!DDTy->getName().empty()) {
2112 Info.Members.push_back({DDTy, 0});
2113 return;
2114 }
Shoaib Meenai03303a32018-02-27 21:48:41 +00002115
2116 // An unnamed member may represent a nested struct or union. Attempt to
2117 // interpret the unnamed member as a DICompositeType possibly wrapped in
2118 // qualifier types. Add all the indirect fields to the current record if that
2119 // succeeds, and drop the member if that fails.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002120 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00002121 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002122 const DIType *Ty = DDTy->getBaseType().resolve();
Shoaib Meenai03303a32018-02-27 21:48:41 +00002123 bool FullyResolved = false;
2124 while (!FullyResolved) {
2125 switch (Ty->getTag()) {
2126 case dwarf::DW_TAG_const_type:
2127 case dwarf::DW_TAG_volatile_type:
2128 // FIXME: we should apply the qualifier types to the indirect fields
2129 // rather than dropping them.
2130 Ty = cast<DIDerivedType>(Ty)->getBaseType().resolve();
2131 break;
2132 default:
2133 FullyResolved = true;
2134 break;
2135 }
2136 }
2137
2138 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2139 if (!DCTy)
2140 return;
2141
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002142 ClassInfo NestedInfo = collectClassInfo(DCTy);
2143 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002144 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002145 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002146}
2147
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002148ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2149 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002150 // Add elements to structure type.
2151 DINodeArray Elements = Ty->getElements();
2152 for (auto *Element : Elements) {
2153 // We assume that the frontend provides all members in source declaration
2154 // order, which is what MSVC does.
2155 if (!Element)
2156 continue;
2157 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00002158 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002159 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002160 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002161 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002162 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2163 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002164 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2165 DDTy->getName() == "__vtbl_ptr_type") {
2166 Info.VShapeTI = getTypeIndex(DDTy);
Reid Klecknere2e82062017-08-08 20:30:14 +00002167 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2168 Info.NestedTypes.push_back(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002169 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2170 // Ignore friend members. It appears that MSVC emitted info about
2171 // friends in the past, but modern versions do not.
2172 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002173 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
Reid Klecknere2e82062017-08-08 20:30:14 +00002174 Info.NestedTypes.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002175 }
2176 // Skip other unrecognized kinds of elements.
2177 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002178 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002179}
2180
Brock Wymab60532f2018-06-11 01:39:34 +00002181static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
2182 // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2183 // if a complete type should be emitted instead of a forward reference.
2184 return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2185 !Ty->isForwardDecl();
2186}
2187
Reid Klecknera8d57402016-06-03 15:58:20 +00002188TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
Brock Wymab60532f2018-06-11 01:39:34 +00002189 // Emit the complete type for unnamed structs. C++ classes with methods
2190 // which have a circular reference back to the class type are expected to
2191 // be named by the front-end and should not be "unnamed". C unnamed
2192 // structs should not have circular references.
2193 if (shouldAlwaysEmitCompleteClassType(Ty)) {
2194 // If this unnamed complete type is already in the process of being defined
2195 // then the description of the type is malformed and cannot be emitted
2196 // into CodeView correctly so report a fatal error.
2197 auto I = CompleteTypeIndices.find(Ty);
2198 if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2199 report_fatal_error("cannot debug circular reference to unnamed type");
2200 return getCompleteTypeIndex(Ty);
2201 }
2202
Reid Klecknera8d57402016-06-03 15:58:20 +00002203 // First, construct the forward decl. Don't look into Ty to compute the
2204 // forward decl options, since it might not be available in all TUs.
2205 TypeRecordKind Kind = getRecordKind(Ty);
2206 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00002207 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00002208 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00002209 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2210 FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002211 TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00002212 if (!Ty->isForwardDecl())
2213 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00002214 return FwdDeclTI;
2215}
2216
2217TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2218 // Construct the field list and complete type record.
2219 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00002220 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002221 TypeIndex FieldTI;
2222 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002223 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002224 bool ContainsNestedClass;
2225 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2226 lowerRecordFieldList(Ty);
2227
2228 if (ContainsNestedClass)
2229 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00002230
David Majnemer6bdc24e2016-07-01 23:12:45 +00002231 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00002232
Reid Klecknera8d57402016-06-03 15:58:20 +00002233 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00002234
Zachary Turner4efa0a42016-11-08 22:24:53 +00002235 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2236 SizeInBytes, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002237 TypeIndex ClassTI = TypeTable.writeLeafType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002238
Aaron Smith122d9e72018-03-06 18:20:22 +00002239 addUDTSrcLine(Ty, ClassTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002240
Zachary Turnera7b04172017-08-28 18:49:04 +00002241 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00002242
Hans Wennborg9a519a02016-06-22 21:22:13 +00002243 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002244}
2245
2246TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
Brock Wymab60532f2018-06-11 01:39:34 +00002247 // Emit the complete type for unnamed unions.
2248 if (shouldAlwaysEmitCompleteClassType(Ty))
2249 return getCompleteTypeIndex(Ty);
2250
Reid Klecknera8d57402016-06-03 15:58:20 +00002251 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00002252 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00002253 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00002254 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002255 TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00002256 if (!Ty->isForwardDecl())
2257 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00002258 return FwdDeclTI;
2259}
2260
2261TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00002262 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002263 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002264 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002265 bool ContainsNestedClass;
2266 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2267 lowerRecordFieldList(Ty);
2268
2269 if (ContainsNestedClass)
2270 CO |= ClassOptions::ContainsNestedClass;
2271
Reid Klecknera8d57402016-06-03 15:58:20 +00002272 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00002273 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002274
Zachary Turner4efa0a42016-11-08 22:24:53 +00002275 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2276 Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002277 TypeIndex UnionTI = TypeTable.writeLeafType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002278
Aaron Smith122d9e72018-03-06 18:20:22 +00002279 addUDTSrcLine(Ty, UnionTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002280
Zachary Turnera7b04172017-08-28 18:49:04 +00002281 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00002282
Hans Wennborg9a519a02016-06-22 21:22:13 +00002283 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002284}
2285
Adrian McCarthy820ca542016-07-06 19:49:51 +00002286std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00002287CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2288 // Manually count members. MSVC appears to count everything that generates a
2289 // field list record. Each individual overload in a method overload group
2290 // contributes to this count, even though the overload group is a single field
2291 // list record.
2292 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002293 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner6900de12017-11-28 18:33:17 +00002294 ContinuationRecordBuilder ContinuationBuilder;
2295 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002296
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002297 // Create base classes.
2298 for (const DIDerivedType *I : Info.Inheritance) {
2299 if (I->getFlags() & DINode::FlagVirtual) {
2300 // Virtual base.
Brock Wyma3db2b102018-05-14 21:21:22 +00002301 unsigned VBPtrOffset = I->getVBPtrOffset();
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002302 // FIXME: Despite the accessor name, the offset is really in bytes.
2303 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00002304 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2305 ? TypeRecordKind::IndirectVirtualBaseClass
2306 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002307 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00002308 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002309 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00002310 VBTableIndex);
2311
Zachary Turner6900de12017-11-28 18:33:17 +00002312 ContinuationBuilder.writeMemberType(VBCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002313 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002314 } else {
2315 assert(I->getOffsetInBits() % 8 == 0 &&
2316 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00002317 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2318 getTypeIndex(I->getBaseType()),
2319 I->getOffsetInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002320 ContinuationBuilder.writeMemberType(BCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002321 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002322 }
2323 }
2324
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002325 // Create members.
2326 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2327 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2328 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00002329 StringRef MemberName = Member->getName();
2330 MemberAccess Access =
2331 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002332
2333 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002334 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002335 ContinuationBuilder.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002336 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002337 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00002338 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002339
Reid Kleckner9dac4732016-08-31 15:59:30 +00002340 // Virtual function pointer member.
2341 if ((Member->getFlags() & DINode::FlagArtificial) &&
2342 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002343 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
Zachary Turner6900de12017-11-28 18:33:17 +00002344 ContinuationBuilder.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002345 MemberCount++;
2346 continue;
2347 }
2348
David Majnemer9319cbc2016-06-30 03:00:20 +00002349 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00002350 uint64_t MemberOffsetInBits =
2351 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002352 if (Member->isBitField()) {
2353 uint64_t StartBitOffset = MemberOffsetInBits;
2354 if (const auto *CI =
2355 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00002356 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002357 }
2358 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002359 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2360 StartBitOffset);
Zachary Turner6900de12017-11-28 18:33:17 +00002361 MemberBaseType = TypeTable.writeLeafType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00002362 }
2363 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002364 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2365 MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002366 ContinuationBuilder.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002367 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002368 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002369
2370 // Create methods
2371 for (auto &MethodItr : Info.Methods) {
2372 StringRef Name = MethodItr.first->getString();
2373
2374 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00002375 for (const DISubprogram *SP : MethodItr.second) {
2376 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2377 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002378
2379 unsigned VFTableOffset = -1;
2380 if (Introduced)
2381 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2382
Zachary Turner7251ede2016-11-02 17:05:19 +00002383 Methods.push_back(OneMethodRecord(
2384 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2385 translateMethodKindFlags(SP, Introduced),
2386 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002387 MemberCount++;
2388 }
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002389 assert(!Methods.empty() && "Empty methods map entry");
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002390 if (Methods.size() == 1)
Zachary Turner6900de12017-11-28 18:33:17 +00002391 ContinuationBuilder.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002392 else {
Zachary Turner6900de12017-11-28 18:33:17 +00002393 // FIXME: Make this use its own ContinuationBuilder so that
2394 // MethodOverloadList can be split correctly.
Zachary Turner4efa0a42016-11-08 22:24:53 +00002395 MethodOverloadListRecord MOLR(Methods);
Zachary Turner6900de12017-11-28 18:33:17 +00002396 TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2397
Zachary Turner4efa0a42016-11-08 22:24:53 +00002398 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00002399 ContinuationBuilder.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002400 }
2401 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002402
2403 // Create nested classes.
Reid Klecknere2e82062017-08-08 20:30:14 +00002404 for (const DIType *Nested : Info.NestedTypes) {
Adrian McCarthy820ca542016-07-06 19:49:51 +00002405 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00002406 ContinuationBuilder.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00002407 MemberCount++;
2408 }
2409
Zachary Turner6900de12017-11-28 18:33:17 +00002410 TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002411 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Reid Klecknere2e82062017-08-08 20:30:14 +00002412 !Info.NestedTypes.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00002413}
2414
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002415TypeIndex CodeViewDebug::getVBPTypeIndex() {
2416 if (!VBPType.getIndex()) {
2417 // Make a 'const int *' type.
2418 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner6900de12017-11-28 18:33:17 +00002419 TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002420
2421 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2422 : PointerKind::Near32;
2423 PointerMode PM = PointerMode::Pointer;
2424 PointerOptions PO = PointerOptions::None;
2425 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
Zachary Turner6900de12017-11-28 18:33:17 +00002426 VBPType = TypeTable.writeLeafType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002427 }
2428
2429 return VBPType;
2430}
2431
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002432TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002433 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002434 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002435
2436 // The null DIType is the void type. Don't try to hash it.
2437 if (!Ty)
2438 return TypeIndex::Void();
2439
Reid Klecknera8d57402016-06-03 15:58:20 +00002440 // Check if we've already translated this type. Don't try to do a
2441 // get-or-create style insertion that caches the hash lookup across the
2442 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002443 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002444 if (I != TypeIndices.end())
2445 return I->second;
2446
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002447 TypeLoweringScope S(*this);
2448 TypeIndex TI = lowerType(Ty, ClassTy);
2449 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002450}
2451
Bob Haarman223303c2017-08-29 20:59:25 +00002452TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
2453 DIType *Ty = TypeRef.resolve();
2454 PointerRecord PR(getTypeIndex(Ty),
2455 getPointerSizeInBytes() == 8 ? PointerKind::Near64
2456 : PointerKind::Near32,
2457 PointerMode::LValueReference, PointerOptions::None,
2458 Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002459 return TypeTable.writeLeafType(PR);
Bob Haarman223303c2017-08-29 20:59:25 +00002460}
2461
Reid Klecknera8d57402016-06-03 15:58:20 +00002462TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
2463 const DIType *Ty = TypeRef.resolve();
2464
2465 // The null DIType is the void type. Don't try to hash it.
2466 if (!Ty)
2467 return TypeIndex::Void();
2468
2469 // If this is a non-record type, the complete type index is the same as the
2470 // normal type index. Just call getTypeIndex.
2471 switch (Ty->getTag()) {
2472 case dwarf::DW_TAG_class_type:
2473 case dwarf::DW_TAG_structure_type:
2474 case dwarf::DW_TAG_union_type:
2475 break;
2476 default:
2477 return getTypeIndex(Ty);
2478 }
2479
Brock Wymab60532f2018-06-11 01:39:34 +00002480 // Check if we've already translated the complete record type.
Reid Klecknera8d57402016-06-03 15:58:20 +00002481 const auto *CTy = cast<DICompositeType>(Ty);
2482 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2483 if (!InsertResult.second)
2484 return InsertResult.first->second;
2485
Reid Kleckner643dd832016-06-22 17:15:28 +00002486 TypeLoweringScope S(*this);
2487
Reid Klecknera8d57402016-06-03 15:58:20 +00002488 // Make sure the forward declaration is emitted first. It's unclear if this
2489 // is necessary, but MSVC does it, and we should follow suit until we can show
2490 // otherwise.
Brock Wymab60532f2018-06-11 01:39:34 +00002491 // We only emit a forward declaration for named types.
2492 if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2493 TypeIndex FwdDeclTI = getTypeIndex(CTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002494
Brock Wymab60532f2018-06-11 01:39:34 +00002495 // Just use the forward decl if we don't have complete type info. This
2496 // might happen if the frontend is using modules and expects the complete
2497 // definition to be emitted elsewhere.
2498 if (CTy->isForwardDecl())
2499 return FwdDeclTI;
2500 }
Reid Klecknera8d57402016-06-03 15:58:20 +00002501
2502 TypeIndex TI;
2503 switch (CTy->getTag()) {
2504 case dwarf::DW_TAG_class_type:
2505 case dwarf::DW_TAG_structure_type:
2506 TI = lowerCompleteTypeClass(CTy);
2507 break;
2508 case dwarf::DW_TAG_union_type:
2509 TI = lowerCompleteTypeUnion(CTy);
2510 break;
2511 default:
2512 llvm_unreachable("not a record");
2513 }
2514
Brock Wymab60532f2018-06-11 01:39:34 +00002515 // Update the type index associated with this CompositeType. This cannot
2516 // use the 'InsertResult' iterator above because it is potentially
2517 // invalidated by map insertions which can occur while lowering the class
2518 // type above.
2519 CompleteTypeIndices[CTy] = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002520 return TI;
2521}
2522
Reid Kleckner643dd832016-06-22 17:15:28 +00002523/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00002524/// and do this until fixpoint, as each complete record type typically
2525/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00002526/// many other record types.
2527void CodeViewDebug::emitDeferredCompleteTypes() {
2528 SmallVector<const DICompositeType *, 4> TypesToEmit;
2529 while (!DeferredCompleteTypes.empty()) {
2530 std::swap(DeferredCompleteTypes, TypesToEmit);
2531 for (const DICompositeType *RecordTy : TypesToEmit)
2532 getCompleteTypeIndex(RecordTy);
2533 TypesToEmit.clear();
2534 }
2535}
2536
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002537void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2538 ArrayRef<LocalVariable> Locals) {
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002539 // Get the sorted list of parameters and emit them first.
2540 SmallVector<const LocalVariable *, 6> Params;
2541 for (const LocalVariable &L : Locals)
2542 if (L.DIVar->isParameter())
2543 Params.push_back(&L);
Fangrui Song0cac7262018-09-27 02:13:45 +00002544 llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2545 return L->DIVar->getArg() < R->DIVar->getArg();
2546 });
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002547 for (const LocalVariable *L : Params)
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002548 emitLocalVariable(FI, *L);
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002549
2550 // Next emit all non-parameters in the order that we found them.
2551 for (const LocalVariable &L : Locals)
2552 if (!L.DIVar->isParameter())
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002553 emitLocalVariable(FI, L);
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002554}
2555
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002556/// Only call this on endian-specific types like ulittle16_t and little32_t, or
2557/// structs composed of them.
2558template <typename T>
2559static void copyBytesForDefRange(SmallString<20> &BytePrefix,
2560 SymbolKind SymKind, const T &DefRangeHeader) {
2561 BytePrefix.resize(2 + sizeof(T));
2562 ulittle16_t SymKindLE = ulittle16_t(SymKind);
2563 memcpy(&BytePrefix[0], &SymKindLE, 2);
2564 memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
2565}
2566
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002567void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2568 const LocalVariable &Var) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002569 // LocalSym record, see SymbolRecord.h for more info.
2570 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2571 *LocalEnd = MMI->getContext().createTempSymbol();
2572 OS.AddComment("Record length");
2573 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2574 OS.EmitLabel(LocalBegin);
2575
2576 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00002577 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002578
Zachary Turner63a28462016-05-17 23:50:21 +00002579 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002580 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002581 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002582 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002583 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002584
2585 OS.AddComment("TypeIndex");
Reid Kleckner08f5fd52017-08-31 15:56:49 +00002586 TypeIndex TI = Var.UseReferenceType
2587 ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2588 : getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002589 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002590 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002591 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002592 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002593 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002594 OS.EmitLabel(LocalEnd);
2595
Reid Kleckner876330d2016-02-12 21:48:30 +00002596 // Calculate the on disk prefix of the appropriate def range record. The
2597 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2598 // should be big enough to hold all forms without memory allocation.
2599 SmallString<20> BytePrefix;
2600 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2601 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002602 if (DefRange.InMemory) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002603 int Offset = DefRange.DataOffset;
2604 unsigned Reg = DefRange.CVRegister;
2605
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00002606 // 32-bit x86 call sequences often use PUSH instructions, which disrupt
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002607 // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
Reid Kleckner2bcb2882018-11-03 00:41:52 +00002608 // instead. In frames without stack realignment, $T0 will be the CFA.
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002609 if (RegisterId(Reg) == RegisterId::ESP) {
2610 Reg = unsigned(RegisterId::VFRAME);
Reid Kleckner2bcb2882018-11-03 00:41:52 +00002611 Offset += FI.OffsetAdjustment;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002612 }
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002613
2614 // If we can use the chosen frame pointer for the frame and this isn't a
2615 // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2616 // Otherwise, use S_DEFRANGE_REGISTER_REL.
2617 EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
2618 if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2619 (bool(Flags & LocalSymFlags::IsParameter)
2620 ? (EncFP == FI.EncodedParamFramePtrReg)
2621 : (EncFP == FI.EncodedLocalFramePtrReg))) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002622 little32_t FPOffset = little32_t(Offset);
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002623 copyBytesForDefRange(BytePrefix, S_DEFRANGE_FRAMEPOINTER_REL, FPOffset);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002624 } else {
2625 uint16_t RegRelFlags = 0;
2626 if (DefRange.IsSubfield) {
2627 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2628 (DefRange.StructOffset
2629 << DefRangeRegisterRelSym::OffsetInParentShift);
2630 }
2631 DefRangeRegisterRelSym::Header DRHdr;
2632 DRHdr.Register = Reg;
2633 DRHdr.Flags = RegRelFlags;
2634 DRHdr.BasePointerOffset = Offset;
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002635 copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER_REL, DRHdr);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002636 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002637 } else {
2638 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002639 if (DefRange.IsSubfield) {
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002640 DefRangeSubfieldRegisterSym::Header DRHdr;
2641 DRHdr.Register = DefRange.CVRegister;
2642 DRHdr.MayHaveNoName = 0;
2643 DRHdr.OffsetInParent = DefRange.StructOffset;
2644 copyBytesForDefRange(BytePrefix, S_DEFRANGE_SUBFIELD_REGISTER, DRHdr);
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002645 } else {
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002646 DefRangeRegisterSym::Header DRHdr;
2647 DRHdr.Register = DefRange.CVRegister;
2648 DRHdr.MayHaveNoName = 0;
2649 copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER, DRHdr);
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002650 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002651 }
2652 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2653 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002654}
2655
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002656void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2657 const FunctionInfo& FI) {
2658 for (LexicalBlock *Block : Blocks)
2659 emitLexicalBlock(*Block, FI);
2660}
2661
2662/// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2663/// lexical block scope.
2664void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2665 const FunctionInfo& FI) {
2666 MCSymbol *RecordBegin = MMI->getContext().createTempSymbol(),
2667 *RecordEnd = MMI->getContext().createTempSymbol();
2668
2669 // Lexical block symbol record.
2670 OS.AddComment("Record length");
2671 OS.emitAbsoluteSymbolDiff(RecordEnd, RecordBegin, 2); // Record Length
2672 OS.EmitLabel(RecordBegin);
2673 OS.AddComment("Record kind: S_BLOCK32");
2674 OS.EmitIntValue(SymbolKind::S_BLOCK32, 2); // Record Kind
2675 OS.AddComment("PtrParent");
2676 OS.EmitIntValue(0, 4); // PtrParent
2677 OS.AddComment("PtrEnd");
2678 OS.EmitIntValue(0, 4); // PtrEnd
2679 OS.AddComment("Code size");
2680 OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size
2681 OS.AddComment("Function section relative address");
2682 OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset
2683 OS.AddComment("Function section index");
2684 OS.EmitCOFFSectionIndex(FI.Begin); // Func Symbol
2685 OS.AddComment("Lexical block name");
2686 emitNullTerminatedSymbolName(OS, Block.Name); // Name
2687 OS.EmitLabel(RecordEnd);
2688
2689 // Emit variables local to this lexical block.
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002690 emitLocalVariableList(FI, Block.Locals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002691
2692 // Emit lexical blocks contained within this block.
2693 emitLexicalBlockList(Block.Children, FI);
2694
2695 // Close the lexical block scope.
2696 OS.AddComment("Record length");
2697 OS.EmitIntValue(2, 2); // Record Length
2698 OS.AddComment("Record kind: S_END");
2699 OS.EmitIntValue(SymbolKind::S_END, 2); // Record Kind
2700}
2701
2702/// Convenience routine for collecting lexical block information for a list
2703/// of lexical scopes.
2704void CodeViewDebug::collectLexicalBlockInfo(
2705 SmallVectorImpl<LexicalScope *> &Scopes,
2706 SmallVectorImpl<LexicalBlock *> &Blocks,
2707 SmallVectorImpl<LocalVariable> &Locals) {
2708 for (LexicalScope *Scope : Scopes)
2709 collectLexicalBlockInfo(*Scope, Blocks, Locals);
2710}
2711
2712/// Populate the lexical blocks and local variable lists of the parent with
2713/// information about the specified lexical scope.
2714void CodeViewDebug::collectLexicalBlockInfo(
2715 LexicalScope &Scope,
2716 SmallVectorImpl<LexicalBlock *> &ParentBlocks,
2717 SmallVectorImpl<LocalVariable> &ParentLocals) {
2718 if (Scope.isAbstractScope())
2719 return;
2720
2721 auto LocalsIter = ScopeVariables.find(&Scope);
2722 if (LocalsIter == ScopeVariables.end()) {
2723 // This scope does not contain variables and can be eliminated.
2724 collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
2725 return;
2726 }
2727 SmallVectorImpl<LocalVariable> &Locals = LocalsIter->second;
2728
2729 const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
2730 if (!DILB) {
2731 // This scope is not a lexical block and can be eliminated, but keep any
2732 // local variables it contains.
2733 ParentLocals.append(Locals.begin(), Locals.end());
2734 collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
2735 return;
2736 }
2737
2738 const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
2739 if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second)) {
2740 // This lexical block scope has too many address ranges to represent in the
2741 // current CodeView format or does not have a valid address range.
2742 // Eliminate this lexical scope and promote any locals it contains to the
2743 // parent scope.
2744 //
2745 // For lexical scopes with multiple address ranges you may be tempted to
2746 // construct a single range covering every instruction where the block is
2747 // live and everything in between. Unfortunately, Visual Studio only
2748 // displays variables from the first matching lexical block scope. If the
2749 // first lexical block contains exception handling code or cold code which
2750 // is moved to the bottom of the routine creating a single range covering
2751 // nearly the entire routine, then it will hide all other lexical blocks
2752 // and the variables they contain.
2753 //
2754 ParentLocals.append(Locals.begin(), Locals.end());
2755 collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
2756 return;
2757 }
2758
2759 // Create a new CodeView lexical block for this lexical scope. If we've
2760 // seen this DILexicalBlock before then the scope tree is malformed and
2761 // we can handle this gracefully by not processing it a second time.
2762 auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
2763 if (!BlockInsertion.second)
2764 return;
2765
2766 // Create a lexical block containing the local variables and collect the
2767 // the lexical block information for the children.
2768 const InsnRange &Range = Ranges.front();
2769 assert(Range.first && Range.second);
2770 LexicalBlock &Block = BlockInsertion.first->second;
2771 Block.Begin = getLabelBeforeInsn(Range.first);
2772 Block.End = getLabelAfterInsn(Range.second);
2773 assert(Block.Begin && "missing label for scope begin");
2774 assert(Block.End && "missing label for scope end");
2775 Block.Name = DILB->getName();
2776 Block.Locals = std::move(Locals);
2777 ParentBlocks.push_back(&Block);
2778 collectLexicalBlockInfo(Scope.getChildren(), Block.Children, Block.Locals);
2779}
2780
David Blaikieb2fbb4b2017-02-16 18:48:33 +00002781void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002782 const Function &GV = MF->getFunction();
2783 assert(FnDebugInfo.count(&GV));
Reid Kleckner55baeef2018-03-15 21:12:21 +00002784 assert(CurFn == FnDebugInfo[&GV].get());
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002785
Matthias Braunf1caa282017-12-15 22:22:58 +00002786 collectVariableInfo(GV.getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002787
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002788 // Build the lexical block structure to emit for this routine.
2789 if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
2790 collectLexicalBlockInfo(*CFS, CurFn->ChildBlocks, CurFn->Locals);
2791
2792 // Clear the scope and variable information from the map which will not be
2793 // valid after we have finished processing this routine. This also prepares
2794 // the map for the subsequent routine.
2795 ScopeVariables.clear();
2796
Reid Kleckner2214ed82016-01-29 00:49:42 +00002797 // Don't emit anything if we don't have any line tables.
Brock Wyma94ece8f2018-04-16 16:53:57 +00002798 // Thunks are compiler-generated and probably won't have source correlation.
2799 if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002800 FnDebugInfo.erase(&GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002801 CurFn = nullptr;
2802 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002803 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002804
Reid Klecknere33c94f2017-09-05 20:14:58 +00002805 CurFn->Annotations = MF->getCodeViewAnnotations();
2806
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002807 CurFn->End = Asm->getFunctionEnd();
2808
Craig Topper353eda42014-04-24 06:44:33 +00002809 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002810}
2811
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002812void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002813 DebugHandlerBase::beginInstruction(MI);
2814
Shiva Chen801bf7e2018-05-09 02:42:00 +00002815 // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
2816 if (!Asm || !CurFn || MI->isDebugInstr() ||
David Majnemer67f684e2016-07-28 05:03:22 +00002817 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002818 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002819
2820 // If the first instruction of a new MBB has no location, find the first
2821 // instruction with a location and use that.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002822 DebugLoc DL = MI->getDebugLoc();
Reid Kleckner45a74622017-06-30 21:33:44 +00002823 if (!DL && MI->getParent() != PrevInstBB) {
2824 for (const auto &NextMI : *MI->getParent()) {
Shiva Chen801bf7e2018-05-09 02:42:00 +00002825 if (NextMI.isDebugInstr())
Reid Kleckner2de471d2017-07-31 21:03:08 +00002826 continue;
Reid Kleckner45a74622017-06-30 21:33:44 +00002827 DL = NextMI.getDebugLoc();
2828 if (DL)
2829 break;
2830 }
2831 }
2832 PrevInstBB = MI->getParent();
2833
2834 // If we still don't have a debug location, don't record a location.
2835 if (!DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002836 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002837
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002838 maybeRecordLocation(DL, Asm->MF);
2839}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002840
Zachary Turner8c099fe2017-05-30 16:36:15 +00002841MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002842 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2843 *EndLabel = MMI->getContext().createTempSymbol();
2844 OS.EmitIntValue(unsigned(Kind), 4);
2845 OS.AddComment("Subsection size");
2846 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2847 OS.EmitLabel(BeginLabel);
2848 return EndLabel;
2849}
2850
2851void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2852 OS.EmitLabel(EndLabel);
2853 // Every subsection must be aligned to a 4-byte boundary.
2854 OS.EmitValueToAlignment(4);
2855}
2856
David Majnemer3128b102016-06-15 18:00:01 +00002857void CodeViewDebug::emitDebugInfoForUDTs(
Zachary Turnera7b04172017-08-28 18:49:04 +00002858 ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2859 for (const auto &UDT : UDTs) {
2860 const DIType *T = UDT.second;
2861 assert(shouldEmitUdt(T));
2862
David Majnemer3128b102016-06-15 18:00:01 +00002863 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2864 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2865 OS.AddComment("Record length");
2866 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2867 OS.EmitLabel(UDTRecordBegin);
2868
2869 OS.AddComment("Record kind: S_UDT");
2870 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2871
2872 OS.AddComment("Type");
Zachary Turnera7b04172017-08-28 18:49:04 +00002873 OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
David Majnemer3128b102016-06-15 18:00:01 +00002874
2875 emitNullTerminatedSymbolName(OS, UDT.first);
2876 OS.EmitLabel(UDTRecordEnd);
2877 }
2878}
2879
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002880void CodeViewDebug::emitDebugInfoForGlobals() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002881 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2882 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002883 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002884 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2885 GV.getDebugInfo(GVEs);
2886 for (const auto *GVE : GVEs)
2887 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002888 }
2889
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002890 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2891 for (const MDNode *Node : CUs->operands()) {
2892 const auto *CU = cast<DICompileUnit>(Node);
2893
2894 // First, emit all globals that are not in a comdat in a single symbol
2895 // substream. MSVC doesn't like it if the substream is empty, so only open
2896 // it if we have at least one global to emit.
2897 switchToDebugSectionForSymbol(nullptr);
2898 MCSymbol *EndLabel = nullptr;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002899 for (const auto *GVE : CU->getGlobalVariables()) {
2900 if (const auto *GV = GlobalMap.lookup(GVE))
David Majnemer577be0f2016-06-15 00:19:52 +00002901 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002902 if (!EndLabel) {
2903 OS.AddComment("Symbol subsection for globals");
Zachary Turner8c099fe2017-05-30 16:36:15 +00002904 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002905 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002906 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2907 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002908 }
2909 }
2910 if (EndLabel)
2911 endCVSubsection(EndLabel);
2912
2913 // Second, emit each global that is in a comdat into its own .debug$S
2914 // section along with its own symbol substream.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002915 for (const auto *GVE : CU->getGlobalVariables()) {
2916 if (const auto *GV = GlobalMap.lookup(GVE)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002917 if (GV->hasComdat()) {
2918 MCSymbol *GVSym = Asm->getSymbol(GV);
2919 OS.AddComment("Symbol subsection for " +
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00002920 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002921 switchToDebugSectionForSymbol(GVSym);
Zachary Turner8c099fe2017-05-30 16:36:15 +00002922 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002923 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2924 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002925 endCVSubsection(EndLabel);
2926 }
2927 }
2928 }
2929 }
2930}
2931
Hans Wennborgb510b452016-06-23 16:33:53 +00002932void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2933 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2934 for (const MDNode *Node : CUs->operands()) {
2935 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2936 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2937 getTypeIndex(RT);
2938 // FIXME: Add to global/local DTU list.
2939 }
2940 }
2941 }
2942}
2943
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002944void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002945 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002946 MCSymbol *GVSym) {
2947 // DataSym record, see SymbolRecord.h for more info.
2948 // FIXME: Thread local data, etc
2949 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2950 *DataEnd = MMI->getContext().createTempSymbol();
Brock Wyma19e17b32018-02-11 21:26:46 +00002951 const unsigned FixedLengthOfThisRecord = 12;
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002952 OS.AddComment("Record length");
2953 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2954 OS.EmitLabel(DataBegin);
David Majnemer7abd2692016-07-06 21:07:47 +00002955 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002956 if (GV->isThreadLocal()) {
2957 OS.AddComment("Record kind: S_LTHREAD32");
2958 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2959 } else {
2960 OS.AddComment("Record kind: S_LDATA32");
2961 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2962 }
David Majnemer7abd2692016-07-06 21:07:47 +00002963 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002964 if (GV->isThreadLocal()) {
2965 OS.AddComment("Record kind: S_GTHREAD32");
2966 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2967 } else {
2968 OS.AddComment("Record kind: S_GDATA32");
2969 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2970 }
David Majnemer7abd2692016-07-06 21:07:47 +00002971 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002972 OS.AddComment("Type");
2973 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2974 OS.AddComment("DataOffset");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00002975 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002976 OS.AddComment("Segment");
2977 OS.EmitCOFFSectionIndex(GVSym);
2978 OS.AddComment("Name");
Brock Wyma19e17b32018-02-11 21:26:46 +00002979 emitNullTerminatedSymbolName(OS, DIGV->getName(), FixedLengthOfThisRecord);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002980 OS.EmitLabel(DataEnd);
2981}