blob: 1ffc589d7f9d7afff879e372cd69b815d656a9c5 [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"
34#include "llvm/CodeGen/MachineFunction.h"
35#include "llvm/CodeGen/MachineInstr.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineOperand.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000038#include "llvm/CodeGen/TargetFrameLowering.h"
39#include "llvm/CodeGen/TargetLoweringObjectFile.h"
40#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"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000076#include "llvm/Support/SMLoc.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000077#include "llvm/Support/ScopedPrinter.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000078#include "llvm/Target/TargetMachine.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000079#include <algorithm>
80#include <cassert>
81#include <cctype>
82#include <cstddef>
83#include <cstdint>
84#include <iterator>
85#include <limits>
86#include <string>
87#include <utility>
88#include <vector>
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000089
Reid Klecknerf9c275f2016-02-10 20:55:49 +000090using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000091using namespace llvm::codeview;
92
Zachary Turner048f8f92017-12-13 22:33:58 +000093static cl::opt<bool> EmitDebugGlobalHashes("emit-codeview-ghash-section",
94 cl::ReallyHidden, cl::init(false));
95
Reid Klecknerf9c275f2016-02-10 20:55:49 +000096CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
Eugene Zelenkofb69e662017-06-06 22:22:41 +000097 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +000098 // If module doesn't have named metadata anchors or COFF debug section
99 // is not available, skip any debug info related stuff.
100 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
101 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
102 Asm = nullptr;
103 return;
104 }
105
106 // Tell MMI that we have debug info.
107 MMI->setDebugInfoAvailability(true);
108}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000109
Reid Kleckner9533af42016-01-16 00:09:09 +0000110StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
111 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000112 if (!Filepath.empty())
113 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000114
Reid Kleckner9533af42016-01-16 00:09:09 +0000115 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
116
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000117 // Clang emits directory and relative filename info into the IR, but CodeView
118 // operates on full paths. We could change Clang to emit full paths too, but
119 // that would increase the IR size and probably not needed for other users.
120 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000121 if (Filename.find(':') == 1)
122 Filepath = Filename;
123 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000124 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000125
126 // Canonicalize the path. We have to do it textually because we may no longer
127 // have access the file in the filesystem.
128 // First, replace all slashes with backslashes.
129 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
130
131 // Remove all "\.\" with "\".
132 size_t Cursor = 0;
133 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
134 Filepath.erase(Cursor, 2);
135
136 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
137 // path should be well-formatted, e.g. start with a drive letter, etc.
138 Cursor = 0;
139 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
140 // Something's wrong if the path starts with "\..\", abort.
141 if (Cursor == 0)
142 break;
143
144 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
145 if (PrevSlash == std::string::npos)
146 // Something's wrong, abort.
147 break;
148
149 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
150 // The next ".." might be following the one we've just erased.
151 Cursor = PrevSlash;
152 }
153
154 // Remove all duplicate backslashes.
155 Cursor = 0;
156 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
157 Filepath.erase(Cursor, 1);
158
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000159 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000160}
161
Reid Kleckner2214ed82016-01-29 00:49:42 +0000162unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000163 StringRef FullPath = getFullFilepath(F);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000164 unsigned NextId = FileIdMap.size() + 1;
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000165 auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
Reid Kleckner2214ed82016-01-29 00:49:42 +0000166 if (Insertion.second) {
167 // We have to compute the full filepath and emit a .cv_file directive.
Scott Linder71603842018-02-12 19:45:54 +0000168 ArrayRef<uint8_t> ChecksumAsBytes;
169 FileChecksumKind CSKind = FileChecksumKind::None;
170 if (F->getChecksum()) {
171 std::string Checksum = fromHex(F->getChecksum()->Value);
172 void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
173 memcpy(CKMem, Checksum.data(), Checksum.size());
174 ChecksumAsBytes = ArrayRef<uint8_t>(
175 reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
176 switch (F->getChecksum()->Kind) {
177 case DIFile::CSK_MD5: CSKind = FileChecksumKind::MD5; break;
178 case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
179 }
180 }
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000181 bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
Scott Linder71603842018-02-12 19:45:54 +0000182 static_cast<unsigned>(CSKind));
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000183 (void)Success;
184 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000185 }
186 return Insertion.first->second;
187}
188
Reid Kleckner876330d2016-02-12 21:48:30 +0000189CodeViewDebug::InlineSite &
190CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
191 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000192 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
193 InlineSite *Site = &SiteInsertion.first->second;
194 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000195 unsigned ParentFuncId = CurFn->FuncId;
196 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
197 ParentFuncId =
198 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
199 .SiteFuncId;
200
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000201 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000202 OS.EmitCVInlineSiteIdDirective(
203 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
204 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000205 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000206 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000207 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000208 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000209 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000210}
211
David Majnemer6bdc24e2016-07-01 23:12:45 +0000212static StringRef getPrettyScopeName(const DIScope *Scope) {
213 StringRef ScopeName = Scope->getName();
214 if (!ScopeName.empty())
215 return ScopeName;
216
217 switch (Scope->getTag()) {
218 case dwarf::DW_TAG_enumeration_type:
219 case dwarf::DW_TAG_class_type:
220 case dwarf::DW_TAG_structure_type:
221 case dwarf::DW_TAG_union_type:
222 return "<unnamed-tag>";
223 case dwarf::DW_TAG_namespace:
224 return "`anonymous namespace'";
225 }
226
227 return StringRef();
228}
229
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000230static const DISubprogram *getQualifiedNameComponents(
231 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
232 const DISubprogram *ClosestSubprogram = nullptr;
233 while (Scope != nullptr) {
234 if (ClosestSubprogram == nullptr)
235 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000236 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000237 if (!ScopeName.empty())
238 QualifiedNameComponents.push_back(ScopeName);
239 Scope = Scope->getScope().resolve();
240 }
241 return ClosestSubprogram;
242}
243
244static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
245 StringRef TypeName) {
246 std::string FullyQualifiedName;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000247 for (StringRef QualifiedNameComponent :
248 llvm::reverse(QualifiedNameComponents)) {
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000249 FullyQualifiedName.append(QualifiedNameComponent);
250 FullyQualifiedName.append("::");
251 }
252 FullyQualifiedName.append(TypeName);
253 return FullyQualifiedName;
254}
255
256static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
257 SmallVector<StringRef, 5> QualifiedNameComponents;
258 getQualifiedNameComponents(Scope, QualifiedNameComponents);
259 return getQualifiedName(QualifiedNameComponents, Name);
260}
261
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000262struct CodeViewDebug::TypeLoweringScope {
263 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
264 ~TypeLoweringScope() {
265 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
266 // inner TypeLoweringScopes don't attempt to emit deferred types.
267 if (CVD.TypeEmissionLevel == 1)
268 CVD.emitDeferredCompleteTypes();
269 --CVD.TypeEmissionLevel;
270 }
271 CodeViewDebug &CVD;
272};
273
David Majnemer6bdc24e2016-07-01 23:12:45 +0000274static std::string getFullyQualifiedName(const DIScope *Ty) {
275 const DIScope *Scope = Ty->getScope().resolve();
276 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
277}
278
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000279TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
280 // No scope means global scope and that uses the zero index.
281 if (!Scope || isa<DIFile>(Scope))
282 return TypeIndex();
283
284 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
285
286 // Check if we've already translated this scope.
287 auto I = TypeIndices.find({Scope, nullptr});
288 if (I != TypeIndices.end())
289 return I->second;
290
291 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000292 std::string ScopeName = getFullyQualifiedName(Scope);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000293 StringIdRecord SID(TypeIndex(), ScopeName);
Zachary Turner6900de12017-11-28 18:33:17 +0000294 auto TI = TypeTable.writeLeafType(SID);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000295 return recordTypeIndexForDINode(Scope, TI);
296}
297
David Majnemer75c3ebf2016-06-02 17:13:53 +0000298TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000299 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000300
David Majnemer75c3ebf2016-06-02 17:13:53 +0000301 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000302 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000303 if (I != TypeIndices.end())
304 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000305
Reid Klecknerac945e22016-06-17 16:11:20 +0000306 // The display name includes function template arguments. Drop them to match
307 // MSVC.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000308 StringRef DisplayName = SP->getName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000309
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000310 const DIScope *Scope = SP->getScope().resolve();
311 TypeIndex TI;
312 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
313 // If the scope is a DICompositeType, then this must be a method. Member
314 // function types take some special handling, and require access to the
315 // subprogram.
316 TypeIndex ClassType = getTypeIndex(Class);
317 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
318 DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000319 TI = TypeTable.writeLeafType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000320 } else {
321 // Otherwise, this must be a free function.
322 TypeIndex ParentScope = getScopeIndex(Scope);
323 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000324 TI = TypeTable.writeLeafType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000325 }
326
327 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000328}
329
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000330TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
331 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000332 // Always use the method declaration as the key for the function type. The
333 // method declaration contains the this adjustment.
334 if (SP->getDeclaration())
335 SP = SP->getDeclaration();
336 assert(!SP->getDeclaration() && "should use declaration as key");
337
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000338 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
339 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000340 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000341 if (I != TypeIndices.end())
342 return I->second;
343
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000344 // Make sure complete type info for the class is emitted *after* the member
345 // function type, as the complete class type is likely to reference this
346 // member function type.
347 TypeLoweringScope S(*this);
Adrian McCarthyd91bf392017-09-13 20:53:55 +0000348 const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
349 TypeIndex TI = lowerTypeMemberFunction(
350 SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000351 return recordTypeIndexForDINode(SP, TI, Class);
352}
353
Amjad Aboudacee5682016-07-12 12:06:34 +0000354TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
355 TypeIndex TI,
356 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000357 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000358 (void)InsertResult;
359 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000360 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000361}
362
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000363unsigned CodeViewDebug::getPointerSizeInBytes() {
364 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
365}
366
Reid Kleckner876330d2016-02-12 21:48:30 +0000367void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
Reid Kleckner7ac8e502018-03-15 20:12:16 +0000368 const DILocation *InlinedAt) {
369 if (InlinedAt) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000370 // This variable was inlined. Associate it with the InlineSite.
371 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
372 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
373 Site.InlinedLocals.emplace_back(Var);
374 } else {
Reid Kleckner7ac8e502018-03-15 20:12:16 +0000375 // This variable goes in the main ProcSym.
376 CurFn->Locals.emplace_back(Var);
Reid Kleckner876330d2016-02-12 21:48:30 +0000377 }
378}
379
Reid Kleckner829365a2016-02-11 19:41:47 +0000380static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
381 const DILocation *Loc) {
382 auto B = Locs.begin(), E = Locs.end();
383 if (std::find(B, E, Loc) == E)
384 Locs.push_back(Loc);
385}
386
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000387void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000388 const MachineFunction *MF) {
389 // Skip this instruction if it has the same location as the previous one.
Reid Kleckner45a74622017-06-30 21:33:44 +0000390 if (!DL || DL == PrevInstLoc)
Reid Kleckner9533af42016-01-16 00:09:09 +0000391 return;
392
393 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000394 if (!Scope)
395 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000396
David Majnemerc3340db2016-01-13 01:05:23 +0000397 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000398 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
399 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
400 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000401 return;
402
Reid Kleckner2214ed82016-01-29 00:49:42 +0000403 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
404 if (CI.getStartColumn() != DL.getCol())
405 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000406
Reid Kleckner2214ed82016-01-29 00:49:42 +0000407 if (!CurFn->HaveLineInfo)
408 CurFn->HaveLineInfo = true;
409 unsigned FileId = 0;
Reid Kleckner45a74622017-06-30 21:33:44 +0000410 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
Reid Kleckner2214ed82016-01-29 00:49:42 +0000411 FileId = CurFn->LastFileId;
412 else
413 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
Reid Kleckner45a74622017-06-30 21:33:44 +0000414 PrevInstLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000415
416 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000417 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000418 const DILocation *Loc = DL.get();
419
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000420 // If this location was actually inlined from somewhere else, give it the ID
421 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000422 FuncId =
423 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000424
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000425 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000426 bool FirstLoc = true;
427 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000428 InlineSite &Site =
429 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000430 if (!FirstLoc)
431 addLocIfNotPresent(Site.ChildSites, Loc);
432 FirstLoc = false;
433 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000434 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000435 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000436 }
437
Reid Klecknerdac21b42016-02-03 21:15:48 +0000438 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000439 /*PrologueEnd=*/false, /*IsStmt=*/false,
440 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000441}
442
Reid Kleckner5d122f82016-05-25 23:16:12 +0000443void CodeViewDebug::emitCodeViewMagicVersion() {
444 OS.EmitValueToAlignment(4);
445 OS.AddComment("Debug section magic");
446 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
447}
448
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000449void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000450 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000451 return;
452
453 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000454
455 // The COFF .debug$S section consists of several subsections, each starting
456 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
457 // of the payload followed by the payload itself. The subsections are 4-byte
458 // aligned.
459
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000460 // Use the generic .debug$S section, and make a subsection for all the inlined
461 // subprograms.
462 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000463
Zachary Turner8c099fe2017-05-30 16:36:15 +0000464 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000465 emitCompilerInformation();
466 endCVSubsection(CompilerInfo);
467
Reid Kleckner5d122f82016-05-25 23:16:12 +0000468 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000469
Reid Kleckner2214ed82016-01-29 00:49:42 +0000470 // Emit per-function debug information.
471 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000472 if (!P.first->isDeclarationForLinker())
Reid Kleckner55baeef2018-03-15 21:12:21 +0000473 emitDebugInfoForFunction(P.first, *P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000474
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000475 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000476 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000477 emitDebugInfoForGlobals();
478
Hans Wennborgb510b452016-06-23 16:33:53 +0000479 // Emit retained types.
480 emitDebugInfoForRetainedTypes();
481
Reid Kleckner5d122f82016-05-25 23:16:12 +0000482 // Switch back to the generic .debug$S section after potentially processing
483 // comdat symbol sections.
484 switchToDebugSectionForSymbol(nullptr);
485
David Majnemer3128b102016-06-15 18:00:01 +0000486 // Emit UDT records for any types used by global variables.
487 if (!GlobalUDTs.empty()) {
Zachary Turner8c099fe2017-05-30 16:36:15 +0000488 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
David Majnemer3128b102016-06-15 18:00:01 +0000489 emitDebugInfoForUDTs(GlobalUDTs);
490 endCVSubsection(SymbolsEnd);
491 }
492
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000493 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000494 OS.AddComment("File index to string table offset subsection");
495 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000496
497 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000498 OS.AddComment("String table");
499 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000500
Zachary Turner048f8f92017-12-13 22:33:58 +0000501 // Emit type information and hashes last, so that any types we translate while
502 // emitting function info are included.
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000503 emitTypeInformation();
504
Zachary Turner048f8f92017-12-13 22:33:58 +0000505 if (EmitDebugGlobalHashes)
506 emitTypeGlobalHashes();
507
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000508 clear();
509}
510
Brock Wyma19e17b32018-02-11 21:26:46 +0000511static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
512 unsigned MaxFixedRecordLength = 0xF00) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000513 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
514 // after a fixed length portion of the record. The fixed length portion should
515 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
516 // overall record size is less than the maximum allowed.
Reid Klecknerbb96df62016-10-05 22:36:07 +0000517 SmallString<32> NullTerminatedString(
518 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000519 NullTerminatedString.push_back('\0');
520 OS.EmitBytes(NullTerminatedString);
521}
522
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000523void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000524 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000525 return;
526
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000527 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000528 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000529 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000530
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000531 SmallString<8> CommentPrefix;
532 if (OS.isVerboseAsm()) {
533 CommentPrefix += '\t';
534 CommentPrefix += Asm->MAI->getCommentString();
535 CommentPrefix += ' ';
536 }
537
Zachary Turner526f4f22017-05-19 19:26:58 +0000538 TypeTableCollection Table(TypeTable.records());
539 Optional<TypeIndex> B = Table.getFirst();
540 while (B) {
541 // This will fail if the record data is invalid.
542 CVType Record = Table.getType(*B);
543
Zachary Turner4efa0a42016-11-08 22:24:53 +0000544 if (OS.isVerboseAsm()) {
545 // Emit a block comment describing the type record for readability.
546 SmallString<512> CommentBlock;
547 raw_svector_ostream CommentOS(CommentBlock);
548 ScopedPrinter SP(CommentOS);
549 SP.setPrefix(CommentPrefix);
Zachary Turner526f4f22017-05-19 19:26:58 +0000550 TypeDumpVisitor TDV(Table, &SP, false);
551
552 Error E = codeview::visitTypeRecord(Record, *B, TDV);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000553 if (E) {
554 logAllUnhandledErrors(std::move(E), errs(), "error: ");
555 llvm_unreachable("produced malformed type record");
556 }
557 // emitRawComment will insert its own tab and comment string before
558 // the first line, so strip off our first one. It also prints its own
559 // newline.
560 OS.emitRawComment(
561 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Zachary Turner4efa0a42016-11-08 22:24:53 +0000562 }
Zachary Turner526f4f22017-05-19 19:26:58 +0000563 OS.EmitBinaryData(Record.str_data());
564 B = Table.getNext(*B);
565 }
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000566}
567
Zachary Turner048f8f92017-12-13 22:33:58 +0000568void CodeViewDebug::emitTypeGlobalHashes() {
569 if (TypeTable.empty())
570 return;
571
572 // Start the .debug$H section with the version and hash algorithm, currently
573 // hardcoded to version 0, SHA1.
574 OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
575
576 OS.EmitValueToAlignment(4);
577 OS.AddComment("Magic");
578 OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
579 OS.AddComment("Section Version");
580 OS.EmitIntValue(0, 2);
581 OS.AddComment("Hash Algorithm");
582 OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1), 2);
583
584 TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
585 for (const auto &GHR : TypeTable.hashes()) {
586 if (OS.isVerboseAsm()) {
587 // Emit an EOL-comment describing which TypeIndex this hash corresponds
588 // to, as well as the stringified SHA1 hash.
589 SmallString<32> Comment;
590 raw_svector_ostream CommentOS(Comment);
591 CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
592 OS.AddComment(Comment);
593 ++TI;
594 }
595 assert(GHR.Hash.size() % 20 == 0);
596 StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
597 GHR.Hash.size());
598 OS.EmitBinaryData(S);
599 }
600}
601
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000602static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
603 switch (DWLang) {
604 case dwarf::DW_LANG_C:
605 case dwarf::DW_LANG_C89:
606 case dwarf::DW_LANG_C99:
607 case dwarf::DW_LANG_C11:
608 case dwarf::DW_LANG_ObjC:
609 return SourceLanguage::C;
610 case dwarf::DW_LANG_C_plus_plus:
611 case dwarf::DW_LANG_C_plus_plus_03:
612 case dwarf::DW_LANG_C_plus_plus_11:
613 case dwarf::DW_LANG_C_plus_plus_14:
614 return SourceLanguage::Cpp;
615 case dwarf::DW_LANG_Fortran77:
616 case dwarf::DW_LANG_Fortran90:
617 case dwarf::DW_LANG_Fortran03:
618 case dwarf::DW_LANG_Fortran08:
619 return SourceLanguage::Fortran;
620 case dwarf::DW_LANG_Pascal83:
621 return SourceLanguage::Pascal;
622 case dwarf::DW_LANG_Cobol74:
623 case dwarf::DW_LANG_Cobol85:
624 return SourceLanguage::Cobol;
625 case dwarf::DW_LANG_Java:
626 return SourceLanguage::Java;
Reid Kleckner898ddf62017-07-24 16:16:42 +0000627 case dwarf::DW_LANG_D:
628 return SourceLanguage::D;
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000629 default:
630 // There's no CodeView representation for this language, and CV doesn't
631 // have an "unknown" option for the language field, so we'll use MASM,
632 // as it's very low level.
633 return SourceLanguage::Masm;
634 }
635}
636
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000637namespace {
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000638struct Version {
639 int Part[4];
640};
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000641} // end anonymous namespace
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000642
643// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
644// the version number.
645static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000646 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000647 int N = 0;
648 for (const char C : Name) {
649 if (isdigit(C)) {
650 V.Part[N] *= 10;
651 V.Part[N] += C - '0';
652 } else if (C == '.') {
653 ++N;
654 if (N >= 4)
655 return V;
656 } else if (N > 0)
657 return V;
658 }
659 return V;
660}
661
662static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
663 switch (Type) {
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000664 case Triple::ArchType::x86:
665 return CPUType::Pentium3;
666 case Triple::ArchType::x86_64:
667 return CPUType::X64;
668 case Triple::ArchType::thumb:
669 return CPUType::Thumb;
670 case Triple::ArchType::aarch64:
671 return CPUType::ARM64;
672 default:
673 report_fatal_error("target architecture doesn't map to a CodeView CPUType");
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000674 }
675}
676
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000677void CodeViewDebug::emitCompilerInformation() {
678 MCContext &Context = MMI->getContext();
679 MCSymbol *CompilerBegin = Context.createTempSymbol(),
680 *CompilerEnd = Context.createTempSymbol();
681 OS.AddComment("Record length");
682 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
683 OS.EmitLabel(CompilerBegin);
684 OS.AddComment("Record kind: S_COMPILE3");
685 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
686 uint32_t Flags = 0;
687
688 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
689 const MDNode *Node = *CUs->operands().begin();
690 const auto *CU = cast<DICompileUnit>(Node);
691
692 // The low byte of the flags indicates the source language.
693 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
694 // TODO: Figure out which other flags need to be set.
695
696 OS.AddComment("Flags and language");
697 OS.EmitIntValue(Flags, 4);
698
699 OS.AddComment("CPUType");
700 CPUType CPU =
701 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
702 OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
703
704 StringRef CompilerVersion = CU->getProducer();
705 Version FrontVer = parseVersion(CompilerVersion);
706 OS.AddComment("Frontend version");
707 for (int N = 0; N < 4; ++N)
708 OS.EmitIntValue(FrontVer.Part[N], 2);
709
710 // Some Microsoft tools, like Binscope, expect a backend version number of at
711 // least 8.something, so we'll coerce the LLVM version into a form that
712 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000713 int Major = 1000 * LLVM_VERSION_MAJOR +
714 10 * LLVM_VERSION_MINOR +
715 LLVM_VERSION_PATCH;
716 // Clamp it for builds that use unusually large version numbers.
717 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
718 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000719 OS.AddComment("Backend version");
720 for (int N = 0; N < 4; ++N)
721 OS.EmitIntValue(BackVer.Part[N], 2);
722
723 OS.AddComment("Null-terminated compiler version string");
724 emitNullTerminatedSymbolName(OS, CompilerVersion);
725
726 OS.EmitLabel(CompilerEnd);
727}
728
Reid Kleckner5d122f82016-05-25 23:16:12 +0000729void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000730 if (InlinedSubprograms.empty())
731 return;
732
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000733 OS.AddComment("Inlinee lines subsection");
Zachary Turner8c099fe2017-05-30 16:36:15 +0000734 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000735
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000736 // We emit the checksum info for files. This is used by debuggers to
737 // determine if a pdb matches the source before loading it. Visual Studio,
738 // for instance, will display a warning that the breakpoints are not valid if
739 // the pdb does not match the source.
David Majnemer30579ec2016-02-02 23:18:23 +0000740 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000741 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
742
743 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000744 assert(TypeIndices.count({SP, nullptr}));
745 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000746
David Majnemer30579ec2016-02-02 23:18:23 +0000747 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000748 unsigned FileId = maybeRecordFile(SP->getFile());
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000749 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000750 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000751 OS.AddBlankLine();
David Majnemer30579ec2016-02-02 23:18:23 +0000752 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000753 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000754 OS.AddComment("Offset into filechecksum table");
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000755 OS.EmitCVFileChecksumOffsetDirective(FileId);
David Majnemer30579ec2016-02-02 23:18:23 +0000756 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000757 OS.EmitIntValue(SP->getLine(), 4);
758 }
759
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000760 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000761}
762
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000763void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
764 const DILocation *InlinedAt,
765 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000766 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
767 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000768
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000769 assert(TypeIndices.count({Site.Inlinee, nullptr}));
770 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000771
772 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000773 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000774 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000775 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000776 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000777 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000778
Reid Klecknerdac21b42016-02-03 21:15:48 +0000779 OS.AddComment("PtrParent");
780 OS.EmitIntValue(0, 4);
781 OS.AddComment("PtrEnd");
782 OS.EmitIntValue(0, 4);
783 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000784 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000785
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000786 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
787 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000788
789 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000790 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000791
792 OS.EmitLabel(InlineEnd);
793
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000794 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000795
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000796 // Recurse on child inlined call sites before closing the scope.
797 for (const DILocation *ChildSite : Site.ChildSites) {
798 auto I = FI.InlineSites.find(ChildSite);
799 assert(I != FI.InlineSites.end() &&
800 "child site not in function inline site map");
801 emitInlinedCallSite(FI, ChildSite, I->second);
802 }
803
804 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000805 OS.AddComment("Record length");
806 OS.EmitIntValue(2, 2); // RecordLength
807 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000808 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000809}
810
Reid Kleckner5d122f82016-05-25 23:16:12 +0000811void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
812 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
813 // comdat key. A section may be comdat because of -ffunction-sections or
814 // because it is comdat in the IR.
815 MCSectionCOFF *GVSec =
816 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
817 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
818
819 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
820 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
821 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
822
823 OS.SwitchSection(DebugSec);
824
825 // Emit the magic version number if this is the first time we've switched to
826 // this section.
827 if (ComdatDebugSections.insert(DebugSec).second)
828 emitCodeViewMagicVersion();
829}
830
Reid Kleckner2214ed82016-01-29 00:49:42 +0000831void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
832 FunctionInfo &FI) {
Brock Wyma31cc1eb2018-01-30 13:16:50 +0000833 // For each function there is a separate subsection which holds the PC to
834 // file:line table.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000835 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000836 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000837
Reid Kleckner5d122f82016-05-25 23:16:12 +0000838 // Switch to the to a comdat section, if appropriate.
839 switchToDebugSectionForSymbol(Fn);
840
Reid Klecknerac945e22016-06-17 16:11:20 +0000841 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000842 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000843 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000844 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000845
846 // If we have a display name, build the fully qualified name by walking the
847 // chain of scopes.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000848 if (!SP->getName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000849 FuncName =
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000850 getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000851
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000852 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000853 if (FuncName.empty())
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +0000854 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000855
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000856 // Emit FPO data, but only on 32-bit x86. No other platforms use it.
857 if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
858 OS.EmitCVFPOData(Fn);
859
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000860 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000861 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Zachary Turner8c099fe2017-05-30 16:36:15 +0000862 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000863 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000864 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
865 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000866 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000867 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000868 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000869
Reid Kleckner4ad127f2016-09-14 21:49:21 +0000870 if (GV->hasLocalLinkage()) {
871 OS.AddComment("Record kind: S_LPROC32_ID");
872 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
873 } else {
874 OS.AddComment("Record kind: S_GPROC32_ID");
875 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
876 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000877
David Majnemer30579ec2016-02-02 23:18:23 +0000878 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000879 OS.AddComment("PtrParent");
880 OS.EmitIntValue(0, 4);
881 OS.AddComment("PtrEnd");
882 OS.EmitIntValue(0, 4);
883 OS.AddComment("PtrNext");
884 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000885 // This is the important bit that tells the debugger where the function
886 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000887 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000888 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000889 OS.AddComment("Offset after prologue");
890 OS.EmitIntValue(0, 4);
891 OS.AddComment("Offset before epilogue");
892 OS.EmitIntValue(0, 4);
893 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000894 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000895 OS.AddComment("Function section relative address");
Keno Fischerf7d84ee2017-01-02 03:00:19 +0000896 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000897 OS.AddComment("Function section index");
898 OS.EmitCOFFSectionIndex(Fn);
899 OS.AddComment("Flags");
900 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000901 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000902 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000903 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000904 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000905 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000906
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000907 emitLocalVariableList(FI.Locals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000908
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000909 // Emit inlined call site information. Only emit functions inlined directly
910 // into the parent function. We'll emit the other sites recursively as part
911 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000912 for (const DILocation *InlinedAt : FI.ChildSites) {
913 auto I = FI.InlineSites.find(InlinedAt);
914 assert(I != FI.InlineSites.end() &&
915 "child site not in function inline site map");
916 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000917 }
918
Reid Klecknere33c94f2017-09-05 20:14:58 +0000919 for (auto Annot : FI.Annotations) {
920 MCSymbol *Label = Annot.first;
921 MDTuple *Strs = cast<MDTuple>(Annot.second);
922 MCSymbol *AnnotBegin = MMI->getContext().createTempSymbol(),
923 *AnnotEnd = MMI->getContext().createTempSymbol();
924 OS.AddComment("Record length");
925 OS.emitAbsoluteSymbolDiff(AnnotEnd, AnnotBegin, 2);
926 OS.EmitLabel(AnnotBegin);
927 OS.AddComment("Record kind: S_ANNOTATION");
928 OS.EmitIntValue(SymbolKind::S_ANNOTATION, 2);
929 OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
930 // FIXME: Make sure we don't overflow the max record size.
931 OS.EmitCOFFSectionIndex(Label);
932 OS.EmitIntValue(Strs->getNumOperands(), 2);
933 for (Metadata *MD : Strs->operands()) {
934 // MDStrings are null terminated, so we can do EmitBytes and get the
935 // nice .asciz directive.
936 StringRef Str = cast<MDString>(MD)->getString();
937 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
938 OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
939 }
940 OS.EmitLabel(AnnotEnd);
941 }
942
David Majnemer3128b102016-06-15 18:00:01 +0000943 if (SP != nullptr)
944 emitDebugInfoForUDTs(LocalUDTs);
945
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000946 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000947 OS.AddComment("Record length");
948 OS.EmitIntValue(0x0002, 2);
949 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000950 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000951 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000952 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000953
Reid Kleckner2214ed82016-01-29 00:49:42 +0000954 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000955 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000956}
957
Reid Kleckner876330d2016-02-12 21:48:30 +0000958CodeViewDebug::LocalVarDefRange
959CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
960 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000961 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000962 DR.DataOffset = Offset;
963 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000964 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000965 DR.StructOffset = 0;
966 DR.CVRegister = CVRegister;
967 return DR;
968}
969
970CodeViewDebug::LocalVarDefRange
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000971CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
972 int Offset, bool IsSubfield,
973 uint16_t StructOffset) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000974 LocalVarDefRange DR;
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000975 DR.InMemory = InMemory;
976 DR.DataOffset = Offset;
977 DR.IsSubfield = IsSubfield;
978 DR.StructOffset = StructOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +0000979 DR.CVRegister = CVRegister;
980 return DR;
981}
982
Matthias Braunef331ef2016-11-30 23:48:50 +0000983void CodeViewDebug::collectVariableInfoFromMFTable(
Reid Kleckner876330d2016-02-12 21:48:30 +0000984 DenseSet<InlinedVariable> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +0000985 const MachineFunction &MF = *Asm->MF;
986 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +0000987 const TargetFrameLowering *TFI = TSI.getFrameLowering();
988 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
989
Matthias Braunef331ef2016-11-30 23:48:50 +0000990 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000991 if (!VI.Var)
992 continue;
993 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
994 "Expected inlined-at fields to agree");
995
Reid Kleckner876330d2016-02-12 21:48:30 +0000996 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000997 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
998
999 // If variable scope is not found then skip this variable.
1000 if (!Scope)
1001 continue;
1002
Reid Klecknerb5fced72017-05-09 19:59:29 +00001003 // If the variable has an attached offset expression, extract it.
1004 // FIXME: Try to handle DW_OP_deref as well.
1005 int64_t ExprOffset = 0;
1006 if (VI.Expr)
1007 if (!VI.Expr->extractIfOffset(ExprOffset))
1008 continue;
1009
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001010 // Get the frame register used and the offset.
1011 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001012 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1013 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001014
1015 // Calculate the label ranges.
Reid Klecknerb5fced72017-05-09 19:59:29 +00001016 LocalVarDefRange DefRange =
1017 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001018 for (const InsnRange &Range : Scope->getRanges()) {
1019 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1020 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +00001021 End = End ? End : Asm->getFunctionEnd();
1022 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001023 }
1024
Reid Kleckner876330d2016-02-12 21:48:30 +00001025 LocalVariable Var;
1026 Var.DIVar = VI.Var;
1027 Var.DefRanges.emplace_back(std::move(DefRange));
Reid Kleckner7ac8e502018-03-15 20:12:16 +00001028 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
Reid Kleckner876330d2016-02-12 21:48:30 +00001029 }
1030}
1031
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001032static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1033 return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1034}
1035
1036static bool needsReferenceType(const DbgVariableLocation &Loc) {
1037 return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1038}
1039
Bob Haarman223303c2017-08-29 20:59:25 +00001040void CodeViewDebug::calculateRanges(
1041 LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
1042 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1043
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001044 // Calculate the definition ranges.
Bob Haarman223303c2017-08-29 20:59:25 +00001045 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1046 const InsnRange &Range = *I;
1047 const MachineInstr *DVInst = Range.first;
1048 assert(DVInst->isDebugValue() && "Invalid History entry");
1049 // FIXME: Find a way to represent constant variables, since they are
1050 // relatively common.
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001051 Optional<DbgVariableLocation> Location =
1052 DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1053 if (!Location)
Bob Haarmana88bce12017-08-29 21:01:55 +00001054 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001055
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001056 // CodeView can only express variables in register and variables in memory
1057 // at a constant offset from a register. However, for variables passed
1058 // indirectly by pointer, it is common for that pointer to be spilled to a
1059 // stack location. For the special case of one offseted load followed by a
1060 // zero offset load (a pointer spilled to the stack), we change the type of
1061 // the local variable from a value type to a reference type. This tricks the
1062 // debugger into doing the load for us.
1063 if (Var.UseReferenceType) {
1064 // We're using a reference type. Drop the last zero offset load.
1065 if (canUseReferenceType(*Location))
1066 Location->LoadChain.pop_back();
1067 else
1068 continue;
1069 } else if (needsReferenceType(*Location)) {
1070 // This location can't be expressed without switching to a reference type.
1071 // Start over using that.
1072 Var.UseReferenceType = true;
Bob Haarman223303c2017-08-29 20:59:25 +00001073 Var.DefRanges.clear();
1074 calculateRanges(Var, Ranges);
1075 return;
1076 }
1077
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001078 // We can only handle a register or an offseted load of a register.
1079 if (Location->Register == 0 || Location->LoadChain.size() > 1)
Bob Haarman223303c2017-08-29 20:59:25 +00001080 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001081 {
1082 LocalVarDefRange DR;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001083 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001084 DR.InMemory = !Location->LoadChain.empty();
1085 DR.DataOffset =
1086 !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001087 if (Location->FragmentInfo) {
Bob Haarman223303c2017-08-29 20:59:25 +00001088 DR.IsSubfield = true;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001089 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
Bob Haarman223303c2017-08-29 20:59:25 +00001090 } else {
1091 DR.IsSubfield = false;
1092 DR.StructOffset = 0;
1093 }
1094
1095 if (Var.DefRanges.empty() ||
1096 Var.DefRanges.back().isDifferentLocation(DR)) {
1097 Var.DefRanges.emplace_back(std::move(DR));
1098 }
1099 }
1100
1101 // Compute the label range.
1102 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1103 const MCSymbol *End = getLabelAfterInsn(Range.second);
1104 if (!End) {
1105 // This range is valid until the next overlapping bitpiece. In the
1106 // common case, ranges will not be bitpieces, so they will overlap.
1107 auto J = std::next(I);
1108 const DIExpression *DIExpr = DVInst->getDebugExpression();
1109 while (J != E &&
Bjorn Petterssona223f8152018-03-12 18:02:39 +00001110 !DIExpr->fragmentsOverlap(J->first->getDebugExpression()))
Bob Haarman223303c2017-08-29 20:59:25 +00001111 ++J;
1112 if (J != E)
1113 End = getLabelBeforeInsn(J->first);
1114 else
1115 End = Asm->getFunctionEnd();
1116 }
1117
1118 // If the last range end is our begin, just extend the last range.
1119 // Otherwise make a new range.
1120 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1121 Var.DefRanges.back().Ranges;
1122 if (!R.empty() && R.back().second == Begin)
1123 R.back().second = End;
1124 else
1125 R.emplace_back(Begin, End);
1126
1127 // FIXME: Do more range combining.
1128 }
1129}
1130
Reid Kleckner876330d2016-02-12 21:48:30 +00001131void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1132 DenseSet<InlinedVariable> Processed;
1133 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +00001134 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +00001135
Reid Kleckner876330d2016-02-12 21:48:30 +00001136 for (const auto &I : DbgValues) {
1137 InlinedVariable IV = I.first;
1138 if (Processed.count(IV))
1139 continue;
1140 const DILocalVariable *DIVar = IV.first;
1141 const DILocation *InlinedAt = IV.second;
1142
1143 // Instruction ranges, specifying where IV is accessible.
1144 const auto &Ranges = I.second;
1145
1146 LexicalScope *Scope = nullptr;
1147 if (InlinedAt)
1148 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1149 else
1150 Scope = LScopes.findLexicalScope(DIVar->getScope());
1151 // If variable scope is not found then skip this variable.
1152 if (!Scope)
1153 continue;
1154
1155 LocalVariable Var;
1156 Var.DIVar = DIVar;
1157
Bob Haarman223303c2017-08-29 20:59:25 +00001158 calculateRanges(Var, Ranges);
Reid Kleckner7ac8e502018-03-15 20:12:16 +00001159 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001160 }
1161}
1162
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001163void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00001164 const Function &GV = MF->getFunction();
Reid Kleckner55baeef2018-03-15 21:12:21 +00001165 auto Insertion = FnDebugInfo.insert({&GV, llvm::make_unique<FunctionInfo>()});
1166 assert(!Insertion.second && "emitting function twice");
1167 CurFn = Insertion.first->second.get();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001168 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001169 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001170
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001171 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1172
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001173 // Find the end of the function prolog. First known non-DBG_VALUE and
1174 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001175 // FIXME: is there a simpler a way to do this? Can we just search
1176 // for the first instruction of the function, not the last of the prolog?
1177 DebugLoc PrologEndLoc;
1178 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001179 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001180 for (const auto &MI : MBB) {
Adrian Prantlfb31da12017-05-22 20:47:09 +00001181 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001182 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001183 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001184 break;
Adrian Prantlfb31da12017-05-22 20:47:09 +00001185 } else if (!MI.isMetaInstruction()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001186 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001187 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001188 }
1189 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001190
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001191 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001192 if (PrologEndLoc && !EmptyPrologue) {
1193 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001194 maybeRecordLocation(FnStartDL, MF);
1195 }
1196}
1197
Zachary Turnera7b04172017-08-28 18:49:04 +00001198static bool shouldEmitUdt(const DIType *T) {
Zachary Turner37c74742017-09-05 22:06:39 +00001199 if (!T)
1200 return false;
1201
1202 // MSVC does not emit UDTs for typedefs that are scoped to classes.
1203 if (T->getTag() == dwarf::DW_TAG_typedef) {
1204 if (DIScope *Scope = T->getScope().resolve()) {
1205 switch (Scope->getTag()) {
1206 case dwarf::DW_TAG_structure_type:
1207 case dwarf::DW_TAG_class_type:
1208 case dwarf::DW_TAG_union_type:
1209 return false;
1210 }
1211 }
1212 }
1213
Zachary Turnera7b04172017-08-28 18:49:04 +00001214 while (true) {
1215 if (!T || T->isForwardDecl())
1216 return false;
1217
1218 const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1219 if (!DT)
1220 return true;
1221 T = DT->getBaseType().resolve();
1222 }
1223 return true;
1224}
1225
1226void CodeViewDebug::addToUDTs(const DIType *Ty) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001227 // Don't record empty UDTs.
1228 if (Ty->getName().empty())
1229 return;
Zachary Turnera7b04172017-08-28 18:49:04 +00001230 if (!shouldEmitUdt(Ty))
1231 return;
Reid Klecknerad56ea32016-07-01 22:24:51 +00001232
Hans Wennborg4b63a982016-06-23 22:57:25 +00001233 SmallVector<StringRef, 5> QualifiedNameComponents;
1234 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1235 Ty->getScope().resolve(), QualifiedNameComponents);
1236
1237 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001238 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001239
Zachary Turnera7b04172017-08-28 18:49:04 +00001240 if (ClosestSubprogram == nullptr) {
1241 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1242 } else if (ClosestSubprogram == CurrentSubprogram) {
1243 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1244 }
Hans Wennborg4b63a982016-06-23 22:57:25 +00001245
1246 // TODO: What if the ClosestSubprogram is neither null or the current
1247 // subprogram? Currently, the UDT just gets dropped on the floor.
1248 //
1249 // The current behavior is not desirable. To get maximal fidelity, we would
1250 // need to perform all type translation before beginning emission of .debug$S
1251 // and then make LocalUDTs a member of FunctionInfo
1252}
1253
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001254TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001255 // Generic dispatch for lowering an unknown type.
1256 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001257 case dwarf::DW_TAG_array_type:
1258 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001259 case dwarf::DW_TAG_typedef:
1260 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001261 case dwarf::DW_TAG_base_type:
1262 return lowerTypeBasic(cast<DIBasicType>(Ty));
1263 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001264 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1265 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1266 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001267 case dwarf::DW_TAG_reference_type:
1268 case dwarf::DW_TAG_rvalue_reference_type:
1269 return lowerTypePointer(cast<DIDerivedType>(Ty));
1270 case dwarf::DW_TAG_ptr_to_member_type:
1271 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
Reid Kleckner3acdc672018-02-27 22:08:15 +00001272 case dwarf::DW_TAG_restrict_type:
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001273 case dwarf::DW_TAG_const_type:
1274 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001275 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001276 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001277 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001278 if (ClassTy) {
1279 // The member function type of a member function pointer has no
1280 // ThisAdjustment.
1281 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001282 /*ThisAdjustment=*/0,
1283 /*IsStaticMethod=*/false);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001284 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001285 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001286 case dwarf::DW_TAG_enumeration_type:
1287 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001288 case dwarf::DW_TAG_class_type:
1289 case dwarf::DW_TAG_structure_type:
1290 return lowerTypeClass(cast<DICompositeType>(Ty));
1291 case dwarf::DW_TAG_union_type:
1292 return lowerTypeUnion(cast<DICompositeType>(Ty));
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001293 case dwarf::DW_TAG_unspecified_type:
1294 return TypeIndex::None();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001295 default:
1296 // Use the null type index.
1297 return TypeIndex();
1298 }
1299}
1300
David Majnemerd065e232016-06-02 06:21:37 +00001301TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001302 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1303 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001304 StringRef TypeName = Ty->getName();
1305
Zachary Turnera7b04172017-08-28 18:49:04 +00001306 addToUDTs(Ty);
David Majnemer3128b102016-06-15 18:00:01 +00001307
David Majnemerd065e232016-06-02 06:21:37 +00001308 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001309 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001310 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001311 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001312 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001313 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001314
David Majnemerd065e232016-06-02 06:21:37 +00001315 return UnderlyingTypeIndex;
1316}
1317
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001318TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1319 DITypeRef ElementTypeRef = Ty->getBaseType();
1320 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1321 // IndexType is size_t, which depends on the bitness of the target.
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001322 TypeIndex IndexType = getPointerSizeInBytes() == 8
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001323 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1324 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001325
1326 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1327
Amjad Aboudacee5682016-07-12 12:06:34 +00001328 // Add subranges to array type.
1329 DINodeArray Elements = Ty->getElements();
1330 for (int i = Elements.size() - 1; i >= 0; --i) {
1331 const DINode *Element = Elements[i];
1332 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1333
1334 const DISubrange *Subrange = cast<DISubrange>(Element);
1335 assert(Subrange->getLowerBound() == 0 &&
1336 "codeview doesn't support subranges with lower bounds");
Sander de Smalenfdf40912018-01-24 09:56:07 +00001337 int64_t Count = -1;
1338 if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
1339 Count = CI->getSExtValue();
Amjad Aboudacee5682016-07-12 12:06:34 +00001340
Reid Klecknercd7bba02017-09-13 23:30:01 +00001341 // Forward declarations of arrays without a size and VLAs use a count of -1.
1342 // Emit a count of zero in these cases to match what MSVC does for arrays
1343 // without a size. MSVC doesn't support VLAs, so it's not clear what we
1344 // should do for them even if we could distinguish them.
Reid Kleckner6b78e162017-03-24 23:28:42 +00001345 if (Count == -1)
Reid Kleckner89af1122017-09-13 21:54:20 +00001346 Count = 0;
Amjad Aboudacee5682016-07-12 12:06:34 +00001347
Amjad Aboudacee5682016-07-12 12:06:34 +00001348 // Update the element size and element type index for subsequent subranges.
1349 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001350
1351 // If this is the outermost array, use the size from the array. It will be
Reid Kleckner6b78e162017-03-24 23:28:42 +00001352 // more accurate if we had a VLA or an incomplete element type size.
Reid Kleckner10762882016-09-09 17:29:36 +00001353 uint64_t ArraySize =
1354 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1355
1356 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001357 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00001358 ElementTypeIndex = TypeTable.writeLeafType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001359 }
1360
Amjad Aboudacee5682016-07-12 12:06:34 +00001361 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001362}
1363
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001364TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1365 TypeIndex Index;
1366 dwarf::TypeKind Kind;
1367 uint32_t ByteSize;
1368
1369 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001370 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001371
1372 SimpleTypeKind STK = SimpleTypeKind::None;
1373 switch (Kind) {
1374 case dwarf::DW_ATE_address:
1375 // FIXME: Translate
1376 break;
1377 case dwarf::DW_ATE_boolean:
1378 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001379 case 1: STK = SimpleTypeKind::Boolean8; break;
1380 case 2: STK = SimpleTypeKind::Boolean16; break;
1381 case 4: STK = SimpleTypeKind::Boolean32; break;
1382 case 8: STK = SimpleTypeKind::Boolean64; break;
1383 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001384 }
1385 break;
1386 case dwarf::DW_ATE_complex_float:
1387 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001388 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001389 case 4: STK = SimpleTypeKind::Complex32; break;
1390 case 8: STK = SimpleTypeKind::Complex64; break;
1391 case 10: STK = SimpleTypeKind::Complex80; break;
1392 case 16: STK = SimpleTypeKind::Complex128; break;
1393 }
1394 break;
1395 case dwarf::DW_ATE_float:
1396 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001397 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001398 case 4: STK = SimpleTypeKind::Float32; break;
1399 case 6: STK = SimpleTypeKind::Float48; break;
1400 case 8: STK = SimpleTypeKind::Float64; break;
1401 case 10: STK = SimpleTypeKind::Float80; break;
1402 case 16: STK = SimpleTypeKind::Float128; break;
1403 }
1404 break;
1405 case dwarf::DW_ATE_signed:
1406 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001407 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1408 case 2: STK = SimpleTypeKind::Int16Short; break;
1409 case 4: STK = SimpleTypeKind::Int32; break;
1410 case 8: STK = SimpleTypeKind::Int64Quad; break;
1411 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001412 }
1413 break;
1414 case dwarf::DW_ATE_unsigned:
1415 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001416 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1417 case 2: STK = SimpleTypeKind::UInt16Short; break;
1418 case 4: STK = SimpleTypeKind::UInt32; break;
1419 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1420 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001421 }
1422 break;
1423 case dwarf::DW_ATE_UTF:
1424 switch (ByteSize) {
1425 case 2: STK = SimpleTypeKind::Character16; break;
1426 case 4: STK = SimpleTypeKind::Character32; break;
1427 }
1428 break;
1429 case dwarf::DW_ATE_signed_char:
1430 if (ByteSize == 1)
1431 STK = SimpleTypeKind::SignedCharacter;
1432 break;
1433 case dwarf::DW_ATE_unsigned_char:
1434 if (ByteSize == 1)
1435 STK = SimpleTypeKind::UnsignedCharacter;
1436 break;
1437 default:
1438 break;
1439 }
1440
1441 // Apply some fixups based on the source-level type name.
1442 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1443 STK = SimpleTypeKind::Int32Long;
1444 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1445 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001446 if (STK == SimpleTypeKind::UInt16Short &&
1447 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001448 STK = SimpleTypeKind::WideCharacter;
1449 if ((STK == SimpleTypeKind::SignedCharacter ||
1450 STK == SimpleTypeKind::UnsignedCharacter) &&
1451 Ty->getName() == "char")
1452 STK = SimpleTypeKind::NarrowCharacter;
1453
1454 return TypeIndex(STK);
1455}
1456
Reid Kleckner3acdc672018-02-27 22:08:15 +00001457TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1458 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001459 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1460
Reid Kleckner3acdc672018-02-27 22:08:15 +00001461 // Pointers to simple types without any options can use SimpleTypeMode, rather
1462 // than having a dedicated pointer type record.
1463 if (PointeeTI.isSimple() && PO == PointerOptions::None &&
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001464 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1465 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1466 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1467 ? SimpleTypeMode::NearPointer64
1468 : SimpleTypeMode::NearPointer32;
1469 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1470 }
1471
1472 PointerKind PK =
1473 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1474 PointerMode PM = PointerMode::Pointer;
1475 switch (Ty->getTag()) {
1476 default: llvm_unreachable("not a pointer tag type");
1477 case dwarf::DW_TAG_pointer_type:
1478 PM = PointerMode::Pointer;
1479 break;
1480 case dwarf::DW_TAG_reference_type:
1481 PM = PointerMode::LValueReference;
1482 break;
1483 case dwarf::DW_TAG_rvalue_reference_type:
1484 PM = PointerMode::RValueReference;
1485 break;
1486 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001487
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001488 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00001489 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001490}
1491
Reid Kleckner6fa15462016-06-17 22:14:39 +00001492static PointerToMemberRepresentation
1493translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1494 // SizeInBytes being zero generally implies that the member pointer type was
1495 // incomplete, which can happen if it is part of a function prototype. In this
1496 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001497 if (IsPMF) {
1498 switch (Flags & DINode::FlagPtrToMemberRep) {
1499 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001500 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1501 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001502 case DINode::FlagSingleInheritance:
1503 return PointerToMemberRepresentation::SingleInheritanceFunction;
1504 case DINode::FlagMultipleInheritance:
1505 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1506 case DINode::FlagVirtualInheritance:
1507 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1508 }
1509 } else {
1510 switch (Flags & DINode::FlagPtrToMemberRep) {
1511 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001512 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1513 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001514 case DINode::FlagSingleInheritance:
1515 return PointerToMemberRepresentation::SingleInheritanceData;
1516 case DINode::FlagMultipleInheritance:
1517 return PointerToMemberRepresentation::MultipleInheritanceData;
1518 case DINode::FlagVirtualInheritance:
1519 return PointerToMemberRepresentation::VirtualInheritanceData;
1520 }
1521 }
1522 llvm_unreachable("invalid ptr to member representation");
1523}
1524
Reid Kleckner3acdc672018-02-27 22:08:15 +00001525TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1526 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001527 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1528 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001529 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001530 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1531 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001532 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1533 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1534 : PointerMode::PointerToDataMember;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001535
Reid Kleckner6fa15462016-06-17 22:14:39 +00001536 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1537 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1538 MemberPointerInfo MPI(
1539 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001540 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner6900de12017-11-28 18:33:17 +00001541 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001542}
1543
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001544/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1545/// have a translation, use the NearC convention.
1546static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1547 switch (DwarfCC) {
1548 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1549 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1550 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1551 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1552 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1553 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1554 }
1555 return CallingConvention::NearC;
1556}
1557
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001558TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1559 ModifierOptions Mods = ModifierOptions::None;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001560 PointerOptions PO = PointerOptions::None;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001561 bool IsModifier = true;
1562 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001563 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001564 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001565 switch (BaseTy->getTag()) {
1566 case dwarf::DW_TAG_const_type:
1567 Mods |= ModifierOptions::Const;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001568 PO |= PointerOptions::Const;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001569 break;
1570 case dwarf::DW_TAG_volatile_type:
1571 Mods |= ModifierOptions::Volatile;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001572 PO |= PointerOptions::Volatile;
1573 break;
1574 case dwarf::DW_TAG_restrict_type:
1575 // Only pointer types be marked with __restrict. There is no known flag
1576 // for __restrict in LF_MODIFIER records.
1577 PO |= PointerOptions::Restrict;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001578 break;
1579 default:
1580 IsModifier = false;
1581 break;
1582 }
1583 if (IsModifier)
1584 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1585 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001586
1587 // Check if the inner type will use an LF_POINTER record. If so, the
1588 // qualifiers will go in the LF_POINTER record. This comes up for types like
1589 // 'int *const' and 'int *__restrict', not the more common cases like 'const
1590 // char *'.
1591 if (BaseTy) {
1592 switch (BaseTy->getTag()) {
1593 case dwarf::DW_TAG_pointer_type:
1594 case dwarf::DW_TAG_reference_type:
1595 case dwarf::DW_TAG_rvalue_reference_type:
1596 return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
1597 case dwarf::DW_TAG_ptr_to_member_type:
1598 return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
1599 default:
1600 break;
1601 }
1602 }
1603
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001604 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Reid Kleckner3acdc672018-02-27 22:08:15 +00001605
1606 // Return the base type index if there aren't any modifiers. For example, the
1607 // metadata could contain restrict wrappers around non-pointer types.
1608 if (Mods == ModifierOptions::None)
1609 return ModifiedTI;
1610
Zachary Turner4efa0a42016-11-08 22:24:53 +00001611 ModifierRecord MR(ModifiedTI, Mods);
Zachary Turner6900de12017-11-28 18:33:17 +00001612 return TypeTable.writeLeafType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001613}
1614
David Majnemer75c3ebf2016-06-02 17:13:53 +00001615TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1616 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1617 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1618 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1619
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001620 // MSVC uses type none for variadic argument.
1621 if (ReturnAndArgTypeIndices.size() > 1 &&
1622 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1623 ReturnAndArgTypeIndices.back() = TypeIndex::None();
1624 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001625 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1626 ArrayRef<TypeIndex> ArgTypeIndices = None;
1627 if (!ReturnAndArgTypeIndices.empty()) {
1628 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1629 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1630 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1631 }
1632
1633 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001634 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001635
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001636 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1637
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001638 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1639 ArgTypeIndices.size(), ArgListIndex);
Zachary Turner6900de12017-11-28 18:33:17 +00001640 return TypeTable.writeLeafType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001641}
1642
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001643TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001644 const DIType *ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001645 int ThisAdjustment,
1646 bool IsStaticMethod) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001647 // Lower the containing class type.
1648 TypeIndex ClassType = getTypeIndex(ClassTy);
1649
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001650 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1651 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1652 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1653
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001654 // MSVC uses type none for variadic argument.
1655 if (ReturnAndArgTypeIndices.size() > 1 &&
1656 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1657 ReturnAndArgTypeIndices.back() = TypeIndex::None();
1658 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001659 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1660 ArrayRef<TypeIndex> ArgTypeIndices = None;
1661 if (!ReturnAndArgTypeIndices.empty()) {
1662 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1663 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1664 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1665 }
Reid Kleckner87288b92017-09-15 00:59:07 +00001666 TypeIndex ThisTypeIndex;
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001667 if (!IsStaticMethod && !ArgTypeIndices.empty()) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001668 ThisTypeIndex = ArgTypeIndices.front();
1669 ArgTypeIndices = ArgTypeIndices.drop_front();
1670 }
1671
1672 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001673 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001674
1675 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1676
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001677 // TODO: Need to use the correct values for FunctionOptions.
Zachary Turner4efa0a42016-11-08 22:24:53 +00001678 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1679 FunctionOptions::None, ArgTypeIndices.size(),
1680 ArgListIndex, ThisAdjustment);
Zachary Turner6900de12017-11-28 18:33:17 +00001681 return TypeTable.writeLeafType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001682}
1683
Reid Kleckner9dac4732016-08-31 15:59:30 +00001684TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001685 unsigned VSlotCount =
1686 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
Reid Kleckner9dac4732016-08-31 15:59:30 +00001687 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001688
1689 VFTableShapeRecord VFTSR(Slots);
Zachary Turner6900de12017-11-28 18:33:17 +00001690 return TypeTable.writeLeafType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001691}
1692
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001693static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1694 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001695 case DINode::FlagPrivate: return MemberAccess::Private;
1696 case DINode::FlagPublic: return MemberAccess::Public;
1697 case DINode::FlagProtected: return MemberAccess::Protected;
1698 case 0:
1699 // If there was no explicit access control, provide the default for the tag.
1700 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1701 : MemberAccess::Public;
1702 }
1703 llvm_unreachable("access flags are exclusive");
1704}
1705
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001706static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1707 if (SP->isArtificial())
1708 return MethodOptions::CompilerGenerated;
1709
1710 // FIXME: Handle other MethodOptions.
1711
1712 return MethodOptions::None;
1713}
1714
1715static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1716 bool Introduced) {
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001717 if (SP->getFlags() & DINode::FlagStaticMember)
1718 return MethodKind::Static;
1719
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001720 switch (SP->getVirtuality()) {
1721 case dwarf::DW_VIRTUALITY_none:
1722 break;
1723 case dwarf::DW_VIRTUALITY_virtual:
1724 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1725 case dwarf::DW_VIRTUALITY_pure_virtual:
1726 return Introduced ? MethodKind::PureIntroducingVirtual
1727 : MethodKind::PureVirtual;
1728 default:
1729 llvm_unreachable("unhandled virtuality case");
1730 }
1731
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001732 return MethodKind::Vanilla;
1733}
1734
Reid Klecknera8d57402016-06-03 15:58:20 +00001735static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1736 switch (Ty->getTag()) {
1737 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1738 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1739 }
1740 llvm_unreachable("unexpected tag");
1741}
1742
Reid Klecknere092dad2016-07-02 00:11:07 +00001743/// Return ClassOptions that should be present on both the forward declaration
1744/// and the defintion of a tag type.
1745static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1746 ClassOptions CO = ClassOptions::None;
1747
1748 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001749 // appear to give every type a linkage name, which may be problematic for us.
1750 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001751 if (!Ty->getIdentifier().empty())
1752 CO |= ClassOptions::HasUniqueName;
1753
1754 // Put the Nested flag on a type if it appears immediately inside a tag type.
1755 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1756 // here. That flag is only set on definitions, and not forward declarations.
1757 const DIScope *ImmediateScope = Ty->getScope().resolve();
1758 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1759 CO |= ClassOptions::Nested;
1760
1761 // Put the Scoped flag on function-local types.
1762 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1763 Scope = Scope->getScope().resolve()) {
1764 if (isa<DISubprogram>(Scope)) {
1765 CO |= ClassOptions::Scoped;
1766 break;
1767 }
1768 }
1769
1770 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001771}
1772
Aaron Smith122d9e72018-03-06 18:20:22 +00001773void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
1774 switch (Ty->getTag()) {
1775 case dwarf::DW_TAG_class_type:
1776 case dwarf::DW_TAG_structure_type:
1777 case dwarf::DW_TAG_union_type:
1778 case dwarf::DW_TAG_enumeration_type:
1779 break;
1780 default:
1781 return;
1782 }
1783
1784 if (const auto *File = Ty->getFile()) {
1785 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
1786 TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
1787
1788 UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
1789 TypeTable.writeLeafType(USLR);
1790 }
1791}
1792
David Majnemer979cb882016-06-16 21:32:16 +00001793TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001794 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001795 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001796 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001797
David Majnemerda9548f2016-06-17 16:13:21 +00001798 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001799 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001800 } else {
Zachary Turner6900de12017-11-28 18:33:17 +00001801 ContinuationRecordBuilder ContinuationBuilder;
1802 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
David Majnemerda9548f2016-06-17 16:13:21 +00001803 for (const DINode *Element : Ty->getElements()) {
1804 // We assume that the frontend provides all members in source declaration
1805 // order, which is what MSVC does.
1806 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001807 EnumeratorRecord ER(MemberAccess::Public,
1808 APSInt::getUnsigned(Enumerator->getValue()),
1809 Enumerator->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00001810 ContinuationBuilder.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00001811 EnumeratorCount++;
1812 }
1813 }
Zachary Turner6900de12017-11-28 18:33:17 +00001814 FTI = TypeTable.insertRecord(ContinuationBuilder);
David Majnemerda9548f2016-06-17 16:13:21 +00001815 }
David Majnemer979cb882016-06-16 21:32:16 +00001816
David Majnemer6bdc24e2016-07-01 23:12:45 +00001817 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001818
Zachary Turner4efa0a42016-11-08 22:24:53 +00001819 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1820 getTypeIndex(Ty->getBaseType()));
Aaron Smith122d9e72018-03-06 18:20:22 +00001821 TypeIndex EnumTI = TypeTable.writeLeafType(ER);
1822
1823 addUDTSrcLine(Ty, EnumTI);
1824
1825 return EnumTI;
David Majnemer979cb882016-06-16 21:32:16 +00001826}
1827
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001828//===----------------------------------------------------------------------===//
1829// ClassInfo
1830//===----------------------------------------------------------------------===//
1831
1832struct llvm::ClassInfo {
1833 struct MemberInfo {
1834 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001835 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001836 };
1837 // [MemberInfo]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001838 using MemberList = std::vector<MemberInfo>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001839
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001840 using MethodsList = TinyPtrVector<const DISubprogram *>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001841 // MethodName -> MethodsList
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001842 using MethodsMap = MapVector<MDString *, MethodsList>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001843
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001844 /// Base classes.
1845 std::vector<const DIDerivedType *> Inheritance;
1846
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001847 /// Direct members.
1848 MemberList Members;
1849 // Direct overloaded methods gathered by name.
1850 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001851
Reid Kleckner9dac4732016-08-31 15:59:30 +00001852 TypeIndex VShapeTI;
1853
Reid Klecknere2e82062017-08-08 20:30:14 +00001854 std::vector<const DIType *> NestedTypes;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001855};
1856
1857void CodeViewDebug::clear() {
1858 assert(CurFn == nullptr);
1859 FileIdMap.clear();
1860 FnDebugInfo.clear();
1861 FileToFilepathMap.clear();
1862 LocalUDTs.clear();
1863 GlobalUDTs.clear();
1864 TypeIndices.clear();
1865 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001866}
1867
1868void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1869 const DIDerivedType *DDTy) {
1870 if (!DDTy->getName().empty()) {
1871 Info.Members.push_back({DDTy, 0});
1872 return;
1873 }
Shoaib Meenai03303a32018-02-27 21:48:41 +00001874
1875 // An unnamed member may represent a nested struct or union. Attempt to
1876 // interpret the unnamed member as a DICompositeType possibly wrapped in
1877 // qualifier types. Add all the indirect fields to the current record if that
1878 // succeeds, and drop the member if that fails.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001879 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00001880 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001881 const DIType *Ty = DDTy->getBaseType().resolve();
Shoaib Meenai03303a32018-02-27 21:48:41 +00001882 bool FullyResolved = false;
1883 while (!FullyResolved) {
1884 switch (Ty->getTag()) {
1885 case dwarf::DW_TAG_const_type:
1886 case dwarf::DW_TAG_volatile_type:
1887 // FIXME: we should apply the qualifier types to the indirect fields
1888 // rather than dropping them.
1889 Ty = cast<DIDerivedType>(Ty)->getBaseType().resolve();
1890 break;
1891 default:
1892 FullyResolved = true;
1893 break;
1894 }
1895 }
1896
1897 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
1898 if (!DCTy)
1899 return;
1900
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001901 ClassInfo NestedInfo = collectClassInfo(DCTy);
1902 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001903 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001904 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001905}
1906
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001907ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1908 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001909 // Add elements to structure type.
1910 DINodeArray Elements = Ty->getElements();
1911 for (auto *Element : Elements) {
1912 // We assume that the frontend provides all members in source declaration
1913 // order, which is what MSVC does.
1914 if (!Element)
1915 continue;
1916 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001917 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001918 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001919 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001920 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001921 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1922 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001923 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1924 DDTy->getName() == "__vtbl_ptr_type") {
1925 Info.VShapeTI = getTypeIndex(DDTy);
Reid Klecknere2e82062017-08-08 20:30:14 +00001926 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
1927 Info.NestedTypes.push_back(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001928 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1929 // Ignore friend members. It appears that MSVC emitted info about
1930 // friends in the past, but modern versions do not.
1931 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001932 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
Reid Klecknere2e82062017-08-08 20:30:14 +00001933 Info.NestedTypes.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001934 }
1935 // Skip other unrecognized kinds of elements.
1936 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001937 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001938}
1939
Reid Klecknera8d57402016-06-03 15:58:20 +00001940TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1941 // First, construct the forward decl. Don't look into Ty to compute the
1942 // forward decl options, since it might not be available in all TUs.
1943 TypeRecordKind Kind = getRecordKind(Ty);
1944 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001945 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001946 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001947 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
1948 FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00001949 TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001950 if (!Ty->isForwardDecl())
1951 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001952 return FwdDeclTI;
1953}
1954
1955TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1956 // Construct the field list and complete type record.
1957 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00001958 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001959 TypeIndex FieldTI;
1960 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001961 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001962 bool ContainsNestedClass;
1963 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1964 lowerRecordFieldList(Ty);
1965
1966 if (ContainsNestedClass)
1967 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00001968
David Majnemer6bdc24e2016-07-01 23:12:45 +00001969 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001970
Reid Klecknera8d57402016-06-03 15:58:20 +00001971 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001972
Zachary Turner4efa0a42016-11-08 22:24:53 +00001973 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
1974 SizeInBytes, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00001975 TypeIndex ClassTI = TypeTable.writeLeafType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001976
Aaron Smith122d9e72018-03-06 18:20:22 +00001977 addUDTSrcLine(Ty, ClassTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001978
Zachary Turnera7b04172017-08-28 18:49:04 +00001979 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001980
Hans Wennborg9a519a02016-06-22 21:22:13 +00001981 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001982}
1983
1984TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1985 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001986 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001987 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001988 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00001989 TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001990 if (!Ty->isForwardDecl())
1991 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001992 return FwdDeclTI;
1993}
1994
1995TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00001996 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001997 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001998 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001999 bool ContainsNestedClass;
2000 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2001 lowerRecordFieldList(Ty);
2002
2003 if (ContainsNestedClass)
2004 CO |= ClassOptions::ContainsNestedClass;
2005
Reid Klecknera8d57402016-06-03 15:58:20 +00002006 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00002007 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002008
Zachary Turner4efa0a42016-11-08 22:24:53 +00002009 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2010 Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002011 TypeIndex UnionTI = TypeTable.writeLeafType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002012
Aaron Smith122d9e72018-03-06 18:20:22 +00002013 addUDTSrcLine(Ty, UnionTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002014
Zachary Turnera7b04172017-08-28 18:49:04 +00002015 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00002016
Hans Wennborg9a519a02016-06-22 21:22:13 +00002017 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002018}
2019
Adrian McCarthy820ca542016-07-06 19:49:51 +00002020std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00002021CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2022 // Manually count members. MSVC appears to count everything that generates a
2023 // field list record. Each individual overload in a method overload group
2024 // contributes to this count, even though the overload group is a single field
2025 // list record.
2026 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002027 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner6900de12017-11-28 18:33:17 +00002028 ContinuationRecordBuilder ContinuationBuilder;
2029 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002030
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002031 // Create base classes.
2032 for (const DIDerivedType *I : Info.Inheritance) {
2033 if (I->getFlags() & DINode::FlagVirtual) {
2034 // Virtual base.
2035 // FIXME: Emit VBPtrOffset when the frontend provides it.
2036 unsigned VBPtrOffset = 0;
2037 // FIXME: Despite the accessor name, the offset is really in bytes.
2038 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00002039 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2040 ? TypeRecordKind::IndirectVirtualBaseClass
2041 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002042 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00002043 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002044 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00002045 VBTableIndex);
2046
Zachary Turner6900de12017-11-28 18:33:17 +00002047 ContinuationBuilder.writeMemberType(VBCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002048 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002049 } else {
2050 assert(I->getOffsetInBits() % 8 == 0 &&
2051 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00002052 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2053 getTypeIndex(I->getBaseType()),
2054 I->getOffsetInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002055 ContinuationBuilder.writeMemberType(BCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002056 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002057 }
2058 }
2059
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002060 // Create members.
2061 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2062 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2063 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00002064 StringRef MemberName = Member->getName();
2065 MemberAccess Access =
2066 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002067
2068 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002069 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002070 ContinuationBuilder.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002071 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002072 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00002073 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002074
Reid Kleckner9dac4732016-08-31 15:59:30 +00002075 // Virtual function pointer member.
2076 if ((Member->getFlags() & DINode::FlagArtificial) &&
2077 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002078 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
Zachary Turner6900de12017-11-28 18:33:17 +00002079 ContinuationBuilder.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002080 MemberCount++;
2081 continue;
2082 }
2083
David Majnemer9319cbc2016-06-30 03:00:20 +00002084 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00002085 uint64_t MemberOffsetInBits =
2086 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002087 if (Member->isBitField()) {
2088 uint64_t StartBitOffset = MemberOffsetInBits;
2089 if (const auto *CI =
2090 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00002091 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002092 }
2093 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002094 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2095 StartBitOffset);
Zachary Turner6900de12017-11-28 18:33:17 +00002096 MemberBaseType = TypeTable.writeLeafType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00002097 }
2098 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002099 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2100 MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002101 ContinuationBuilder.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002102 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002103 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002104
2105 // Create methods
2106 for (auto &MethodItr : Info.Methods) {
2107 StringRef Name = MethodItr.first->getString();
2108
2109 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00002110 for (const DISubprogram *SP : MethodItr.second) {
2111 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2112 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002113
2114 unsigned VFTableOffset = -1;
2115 if (Introduced)
2116 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2117
Zachary Turner7251ede2016-11-02 17:05:19 +00002118 Methods.push_back(OneMethodRecord(
2119 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2120 translateMethodKindFlags(SP, Introduced),
2121 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002122 MemberCount++;
2123 }
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002124 assert(!Methods.empty() && "Empty methods map entry");
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002125 if (Methods.size() == 1)
Zachary Turner6900de12017-11-28 18:33:17 +00002126 ContinuationBuilder.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002127 else {
Zachary Turner6900de12017-11-28 18:33:17 +00002128 // FIXME: Make this use its own ContinuationBuilder so that
2129 // MethodOverloadList can be split correctly.
Zachary Turner4efa0a42016-11-08 22:24:53 +00002130 MethodOverloadListRecord MOLR(Methods);
Zachary Turner6900de12017-11-28 18:33:17 +00002131 TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2132
Zachary Turner4efa0a42016-11-08 22:24:53 +00002133 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00002134 ContinuationBuilder.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002135 }
2136 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002137
2138 // Create nested classes.
Reid Klecknere2e82062017-08-08 20:30:14 +00002139 for (const DIType *Nested : Info.NestedTypes) {
Adrian McCarthy820ca542016-07-06 19:49:51 +00002140 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00002141 ContinuationBuilder.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00002142 MemberCount++;
2143 }
2144
Zachary Turner6900de12017-11-28 18:33:17 +00002145 TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002146 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Reid Klecknere2e82062017-08-08 20:30:14 +00002147 !Info.NestedTypes.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00002148}
2149
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002150TypeIndex CodeViewDebug::getVBPTypeIndex() {
2151 if (!VBPType.getIndex()) {
2152 // Make a 'const int *' type.
2153 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner6900de12017-11-28 18:33:17 +00002154 TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002155
2156 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2157 : PointerKind::Near32;
2158 PointerMode PM = PointerMode::Pointer;
2159 PointerOptions PO = PointerOptions::None;
2160 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
Zachary Turner6900de12017-11-28 18:33:17 +00002161 VBPType = TypeTable.writeLeafType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002162 }
2163
2164 return VBPType;
2165}
2166
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002167TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002168 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002169 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002170
2171 // The null DIType is the void type. Don't try to hash it.
2172 if (!Ty)
2173 return TypeIndex::Void();
2174
Reid Klecknera8d57402016-06-03 15:58:20 +00002175 // Check if we've already translated this type. Don't try to do a
2176 // get-or-create style insertion that caches the hash lookup across the
2177 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002178 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002179 if (I != TypeIndices.end())
2180 return I->second;
2181
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002182 TypeLoweringScope S(*this);
2183 TypeIndex TI = lowerType(Ty, ClassTy);
2184 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002185}
2186
Bob Haarman223303c2017-08-29 20:59:25 +00002187TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
2188 DIType *Ty = TypeRef.resolve();
2189 PointerRecord PR(getTypeIndex(Ty),
2190 getPointerSizeInBytes() == 8 ? PointerKind::Near64
2191 : PointerKind::Near32,
2192 PointerMode::LValueReference, PointerOptions::None,
2193 Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002194 return TypeTable.writeLeafType(PR);
Bob Haarman223303c2017-08-29 20:59:25 +00002195}
2196
Reid Klecknera8d57402016-06-03 15:58:20 +00002197TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
2198 const DIType *Ty = TypeRef.resolve();
2199
2200 // The null DIType is the void type. Don't try to hash it.
2201 if (!Ty)
2202 return TypeIndex::Void();
2203
2204 // If this is a non-record type, the complete type index is the same as the
2205 // normal type index. Just call getTypeIndex.
2206 switch (Ty->getTag()) {
2207 case dwarf::DW_TAG_class_type:
2208 case dwarf::DW_TAG_structure_type:
2209 case dwarf::DW_TAG_union_type:
2210 break;
2211 default:
2212 return getTypeIndex(Ty);
2213 }
2214
Brock Wymaf52e1922018-03-13 15:56:20 +00002215 // Check if we've already translated the complete record type. Lowering a
2216 // complete type should never trigger lowering another complete type, so we
2217 // can reuse the hash table lookup result.
Reid Klecknera8d57402016-06-03 15:58:20 +00002218 const auto *CTy = cast<DICompositeType>(Ty);
2219 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2220 if (!InsertResult.second)
2221 return InsertResult.first->second;
2222
Reid Kleckner643dd832016-06-22 17:15:28 +00002223 TypeLoweringScope S(*this);
2224
Reid Klecknera8d57402016-06-03 15:58:20 +00002225 // Make sure the forward declaration is emitted first. It's unclear if this
2226 // is necessary, but MSVC does it, and we should follow suit until we can show
2227 // otherwise.
Brock Wymaf52e1922018-03-13 15:56:20 +00002228 TypeIndex FwdDeclTI = getTypeIndex(CTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002229
Brock Wymaf52e1922018-03-13 15:56:20 +00002230 // Just use the forward decl if we don't have complete type info. This might
2231 // happen if the frontend is using modules and expects the complete definition
2232 // to be emitted elsewhere.
2233 if (CTy->isForwardDecl())
2234 return FwdDeclTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002235
2236 TypeIndex TI;
2237 switch (CTy->getTag()) {
2238 case dwarf::DW_TAG_class_type:
2239 case dwarf::DW_TAG_structure_type:
2240 TI = lowerCompleteTypeClass(CTy);
2241 break;
2242 case dwarf::DW_TAG_union_type:
2243 TI = lowerCompleteTypeUnion(CTy);
2244 break;
2245 default:
2246 llvm_unreachable("not a record");
2247 }
2248
Brock Wymaf52e1922018-03-13 15:56:20 +00002249 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002250 return TI;
2251}
2252
Reid Kleckner643dd832016-06-22 17:15:28 +00002253/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00002254/// and do this until fixpoint, as each complete record type typically
2255/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00002256/// many other record types.
2257void CodeViewDebug::emitDeferredCompleteTypes() {
2258 SmallVector<const DICompositeType *, 4> TypesToEmit;
2259 while (!DeferredCompleteTypes.empty()) {
2260 std::swap(DeferredCompleteTypes, TypesToEmit);
2261 for (const DICompositeType *RecordTy : TypesToEmit)
2262 getCompleteTypeIndex(RecordTy);
2263 TypesToEmit.clear();
2264 }
2265}
2266
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002267void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
2268 // Get the sorted list of parameters and emit them first.
2269 SmallVector<const LocalVariable *, 6> Params;
2270 for (const LocalVariable &L : Locals)
2271 if (L.DIVar->isParameter())
2272 Params.push_back(&L);
2273 std::sort(Params.begin(), Params.end(),
2274 [](const LocalVariable *L, const LocalVariable *R) {
2275 return L->DIVar->getArg() < R->DIVar->getArg();
2276 });
2277 for (const LocalVariable *L : Params)
2278 emitLocalVariable(*L);
2279
2280 // Next emit all non-parameters in the order that we found them.
2281 for (const LocalVariable &L : Locals)
2282 if (!L.DIVar->isParameter())
2283 emitLocalVariable(L);
2284}
2285
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002286void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2287 // LocalSym record, see SymbolRecord.h for more info.
2288 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2289 *LocalEnd = MMI->getContext().createTempSymbol();
2290 OS.AddComment("Record length");
2291 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2292 OS.EmitLabel(LocalBegin);
2293
2294 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00002295 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002296
Zachary Turner63a28462016-05-17 23:50:21 +00002297 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002298 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002299 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002300 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002301 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002302
2303 OS.AddComment("TypeIndex");
Reid Kleckner08f5fd52017-08-31 15:56:49 +00002304 TypeIndex TI = Var.UseReferenceType
2305 ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2306 : getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002307 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002308 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002309 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002310 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002311 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002312 OS.EmitLabel(LocalEnd);
2313
Reid Kleckner876330d2016-02-12 21:48:30 +00002314 // Calculate the on disk prefix of the appropriate def range record. The
2315 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2316 // should be big enough to hold all forms without memory allocation.
2317 SmallString<20> BytePrefix;
2318 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2319 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002320 if (DefRange.InMemory) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002321 uint16_t RegRelFlags = 0;
2322 if (DefRange.IsSubfield) {
2323 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2324 (DefRange.StructOffset
2325 << DefRangeRegisterRelSym::OffsetInParentShift);
2326 }
Zachary Turner46225b12016-12-16 22:48:14 +00002327 DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
2328 Sym.Hdr.Register = DefRange.CVRegister;
2329 Sym.Hdr.Flags = RegRelFlags;
2330 Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +00002331 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00002332 BytePrefix +=
2333 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00002334 BytePrefix +=
Zachary Turner46225b12016-12-16 22:48:14 +00002335 StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
Reid Kleckner876330d2016-02-12 21:48:30 +00002336 } else {
2337 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002338 if (DefRange.IsSubfield) {
2339 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002340 DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2341 Sym.Hdr.Register = DefRange.CVRegister;
2342 Sym.Hdr.MayHaveNoName = 0;
2343 Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2344
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002345 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2346 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2347 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002348 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2349 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002350 } else {
2351 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002352 DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2353 Sym.Hdr.Register = DefRange.CVRegister;
2354 Sym.Hdr.MayHaveNoName = 0;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002355 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2356 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2357 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002358 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2359 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002360 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002361 }
2362 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2363 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002364}
2365
David Blaikieb2fbb4b2017-02-16 18:48:33 +00002366void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002367 const Function &GV = MF->getFunction();
2368 assert(FnDebugInfo.count(&GV));
Reid Kleckner55baeef2018-03-15 21:12:21 +00002369 assert(CurFn == FnDebugInfo[&GV].get());
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002370
Matthias Braunf1caa282017-12-15 22:22:58 +00002371 collectVariableInfo(GV.getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002372
Reid Kleckner2214ed82016-01-29 00:49:42 +00002373 // Don't emit anything if we don't have any line tables.
2374 if (!CurFn->HaveLineInfo) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002375 FnDebugInfo.erase(&GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002376 CurFn = nullptr;
2377 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002378 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002379
Reid Klecknere33c94f2017-09-05 20:14:58 +00002380 CurFn->Annotations = MF->getCodeViewAnnotations();
2381
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002382 CurFn->End = Asm->getFunctionEnd();
2383
Craig Topper353eda42014-04-24 06:44:33 +00002384 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002385}
2386
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002387void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002388 DebugHandlerBase::beginInstruction(MI);
2389
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002390 // Ignore DBG_VALUE locations and function prologue.
David Majnemer67f684e2016-07-28 05:03:22 +00002391 if (!Asm || !CurFn || MI->isDebugValue() ||
2392 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002393 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002394
2395 // If the first instruction of a new MBB has no location, find the first
2396 // instruction with a location and use that.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002397 DebugLoc DL = MI->getDebugLoc();
Reid Kleckner45a74622017-06-30 21:33:44 +00002398 if (!DL && MI->getParent() != PrevInstBB) {
2399 for (const auto &NextMI : *MI->getParent()) {
Reid Kleckner2de471d2017-07-31 21:03:08 +00002400 if (NextMI.isDebugValue())
2401 continue;
Reid Kleckner45a74622017-06-30 21:33:44 +00002402 DL = NextMI.getDebugLoc();
2403 if (DL)
2404 break;
2405 }
2406 }
2407 PrevInstBB = MI->getParent();
2408
2409 // If we still don't have a debug location, don't record a location.
2410 if (!DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002411 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002412
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002413 maybeRecordLocation(DL, Asm->MF);
2414}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002415
Zachary Turner8c099fe2017-05-30 16:36:15 +00002416MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002417 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2418 *EndLabel = MMI->getContext().createTempSymbol();
2419 OS.EmitIntValue(unsigned(Kind), 4);
2420 OS.AddComment("Subsection size");
2421 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2422 OS.EmitLabel(BeginLabel);
2423 return EndLabel;
2424}
2425
2426void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2427 OS.EmitLabel(EndLabel);
2428 // Every subsection must be aligned to a 4-byte boundary.
2429 OS.EmitValueToAlignment(4);
2430}
2431
David Majnemer3128b102016-06-15 18:00:01 +00002432void CodeViewDebug::emitDebugInfoForUDTs(
Zachary Turnera7b04172017-08-28 18:49:04 +00002433 ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2434 for (const auto &UDT : UDTs) {
2435 const DIType *T = UDT.second;
2436 assert(shouldEmitUdt(T));
2437
David Majnemer3128b102016-06-15 18:00:01 +00002438 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2439 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2440 OS.AddComment("Record length");
2441 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2442 OS.EmitLabel(UDTRecordBegin);
2443
2444 OS.AddComment("Record kind: S_UDT");
2445 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2446
2447 OS.AddComment("Type");
Zachary Turnera7b04172017-08-28 18:49:04 +00002448 OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
David Majnemer3128b102016-06-15 18:00:01 +00002449
2450 emitNullTerminatedSymbolName(OS, UDT.first);
2451 OS.EmitLabel(UDTRecordEnd);
2452 }
2453}
2454
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002455void CodeViewDebug::emitDebugInfoForGlobals() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002456 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2457 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002458 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002459 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2460 GV.getDebugInfo(GVEs);
2461 for (const auto *GVE : GVEs)
2462 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002463 }
2464
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002465 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2466 for (const MDNode *Node : CUs->operands()) {
2467 const auto *CU = cast<DICompileUnit>(Node);
2468
2469 // First, emit all globals that are not in a comdat in a single symbol
2470 // substream. MSVC doesn't like it if the substream is empty, so only open
2471 // it if we have at least one global to emit.
2472 switchToDebugSectionForSymbol(nullptr);
2473 MCSymbol *EndLabel = nullptr;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002474 for (const auto *GVE : CU->getGlobalVariables()) {
2475 if (const auto *GV = GlobalMap.lookup(GVE))
David Majnemer577be0f2016-06-15 00:19:52 +00002476 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002477 if (!EndLabel) {
2478 OS.AddComment("Symbol subsection for globals");
Zachary Turner8c099fe2017-05-30 16:36:15 +00002479 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002480 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002481 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2482 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002483 }
2484 }
2485 if (EndLabel)
2486 endCVSubsection(EndLabel);
2487
2488 // Second, emit each global that is in a comdat into its own .debug$S
2489 // section along with its own symbol substream.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002490 for (const auto *GVE : CU->getGlobalVariables()) {
2491 if (const auto *GV = GlobalMap.lookup(GVE)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002492 if (GV->hasComdat()) {
2493 MCSymbol *GVSym = Asm->getSymbol(GV);
2494 OS.AddComment("Symbol subsection for " +
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00002495 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002496 switchToDebugSectionForSymbol(GVSym);
Zachary Turner8c099fe2017-05-30 16:36:15 +00002497 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002498 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2499 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002500 endCVSubsection(EndLabel);
2501 }
2502 }
2503 }
2504 }
2505}
2506
Hans Wennborgb510b452016-06-23 16:33:53 +00002507void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2508 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2509 for (const MDNode *Node : CUs->operands()) {
2510 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2511 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2512 getTypeIndex(RT);
2513 // FIXME: Add to global/local DTU list.
2514 }
2515 }
2516 }
2517}
2518
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002519void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002520 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002521 MCSymbol *GVSym) {
2522 // DataSym record, see SymbolRecord.h for more info.
2523 // FIXME: Thread local data, etc
2524 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2525 *DataEnd = MMI->getContext().createTempSymbol();
Brock Wyma19e17b32018-02-11 21:26:46 +00002526 const unsigned FixedLengthOfThisRecord = 12;
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002527 OS.AddComment("Record length");
2528 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2529 OS.EmitLabel(DataBegin);
David Majnemer7abd2692016-07-06 21:07:47 +00002530 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002531 if (GV->isThreadLocal()) {
2532 OS.AddComment("Record kind: S_LTHREAD32");
2533 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2534 } else {
2535 OS.AddComment("Record kind: S_LDATA32");
2536 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2537 }
David Majnemer7abd2692016-07-06 21:07:47 +00002538 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002539 if (GV->isThreadLocal()) {
2540 OS.AddComment("Record kind: S_GTHREAD32");
2541 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2542 } else {
2543 OS.AddComment("Record kind: S_GDATA32");
2544 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2545 }
David Majnemer7abd2692016-07-06 21:07:47 +00002546 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002547 OS.AddComment("Type");
2548 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2549 OS.AddComment("DataOffset");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00002550 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002551 OS.AddComment("Segment");
2552 OS.EmitCOFFSectionIndex(GVSym);
2553 OS.AddComment("Name");
Brock Wyma19e17b32018-02-11 21:26:46 +00002554 emitNullTerminatedSymbolName(OS, DIGV->getName(), FixedLengthOfThisRecord);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002555 OS.EmitLabel(DataEnd);
2556}