blob: 11c28ba6d9ad04eb7debe629248039386c191624 [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.
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000168 std::string Checksum = fromHex(F->getChecksum());
169 void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
170 memcpy(CKMem, Checksum.data(), Checksum.size());
171 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
172 Checksum.size());
173 DIFile::ChecksumKind ChecksumKind = F->getChecksumKind();
174 bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
175 static_cast<unsigned>(ChecksumKind));
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000176 (void)Success;
177 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000178 }
179 return Insertion.first->second;
180}
181
Reid Kleckner876330d2016-02-12 21:48:30 +0000182CodeViewDebug::InlineSite &
183CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
184 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000185 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
186 InlineSite *Site = &SiteInsertion.first->second;
187 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000188 unsigned ParentFuncId = CurFn->FuncId;
189 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
190 ParentFuncId =
191 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
192 .SiteFuncId;
193
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000194 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000195 OS.EmitCVInlineSiteIdDirective(
196 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
197 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000198 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000199 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000200 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000201 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000202 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000203}
204
David Majnemer6bdc24e2016-07-01 23:12:45 +0000205static StringRef getPrettyScopeName(const DIScope *Scope) {
206 StringRef ScopeName = Scope->getName();
207 if (!ScopeName.empty())
208 return ScopeName;
209
210 switch (Scope->getTag()) {
211 case dwarf::DW_TAG_enumeration_type:
212 case dwarf::DW_TAG_class_type:
213 case dwarf::DW_TAG_structure_type:
214 case dwarf::DW_TAG_union_type:
215 return "<unnamed-tag>";
216 case dwarf::DW_TAG_namespace:
217 return "`anonymous namespace'";
218 }
219
220 return StringRef();
221}
222
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000223static const DISubprogram *getQualifiedNameComponents(
224 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
225 const DISubprogram *ClosestSubprogram = nullptr;
226 while (Scope != nullptr) {
227 if (ClosestSubprogram == nullptr)
228 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000229 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000230 if (!ScopeName.empty())
231 QualifiedNameComponents.push_back(ScopeName);
232 Scope = Scope->getScope().resolve();
233 }
234 return ClosestSubprogram;
235}
236
237static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
238 StringRef TypeName) {
239 std::string FullyQualifiedName;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000240 for (StringRef QualifiedNameComponent :
241 llvm::reverse(QualifiedNameComponents)) {
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000242 FullyQualifiedName.append(QualifiedNameComponent);
243 FullyQualifiedName.append("::");
244 }
245 FullyQualifiedName.append(TypeName);
246 return FullyQualifiedName;
247}
248
249static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
250 SmallVector<StringRef, 5> QualifiedNameComponents;
251 getQualifiedNameComponents(Scope, QualifiedNameComponents);
252 return getQualifiedName(QualifiedNameComponents, Name);
253}
254
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000255struct CodeViewDebug::TypeLoweringScope {
256 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
257 ~TypeLoweringScope() {
258 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
259 // inner TypeLoweringScopes don't attempt to emit deferred types.
260 if (CVD.TypeEmissionLevel == 1)
261 CVD.emitDeferredCompleteTypes();
262 --CVD.TypeEmissionLevel;
263 }
264 CodeViewDebug &CVD;
265};
266
David Majnemer6bdc24e2016-07-01 23:12:45 +0000267static std::string getFullyQualifiedName(const DIScope *Ty) {
268 const DIScope *Scope = Ty->getScope().resolve();
269 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
270}
271
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000272TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
273 // No scope means global scope and that uses the zero index.
274 if (!Scope || isa<DIFile>(Scope))
275 return TypeIndex();
276
277 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
278
279 // Check if we've already translated this scope.
280 auto I = TypeIndices.find({Scope, nullptr});
281 if (I != TypeIndices.end())
282 return I->second;
283
284 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000285 std::string ScopeName = getFullyQualifiedName(Scope);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000286 StringIdRecord SID(TypeIndex(), ScopeName);
Zachary Turner6900de12017-11-28 18:33:17 +0000287 auto TI = TypeTable.writeLeafType(SID);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000288 return recordTypeIndexForDINode(Scope, TI);
289}
290
David Majnemer75c3ebf2016-06-02 17:13:53 +0000291TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000292 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000293
David Majnemer75c3ebf2016-06-02 17:13:53 +0000294 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000295 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000296 if (I != TypeIndices.end())
297 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000298
Reid Klecknerac945e22016-06-17 16:11:20 +0000299 // The display name includes function template arguments. Drop them to match
300 // MSVC.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000301 StringRef DisplayName = SP->getName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000302
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000303 const DIScope *Scope = SP->getScope().resolve();
304 TypeIndex TI;
305 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
306 // If the scope is a DICompositeType, then this must be a method. Member
307 // function types take some special handling, and require access to the
308 // subprogram.
309 TypeIndex ClassType = getTypeIndex(Class);
310 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
311 DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000312 TI = TypeTable.writeLeafType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000313 } else {
314 // Otherwise, this must be a free function.
315 TypeIndex ParentScope = getScopeIndex(Scope);
316 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000317 TI = TypeTable.writeLeafType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000318 }
319
320 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000321}
322
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000323TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
324 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000325 // Always use the method declaration as the key for the function type. The
326 // method declaration contains the this adjustment.
327 if (SP->getDeclaration())
328 SP = SP->getDeclaration();
329 assert(!SP->getDeclaration() && "should use declaration as key");
330
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000331 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
332 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000333 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000334 if (I != TypeIndices.end())
335 return I->second;
336
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000337 // Make sure complete type info for the class is emitted *after* the member
338 // function type, as the complete class type is likely to reference this
339 // member function type.
340 TypeLoweringScope S(*this);
Adrian McCarthyd91bf392017-09-13 20:53:55 +0000341 const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
342 TypeIndex TI = lowerTypeMemberFunction(
343 SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000344 return recordTypeIndexForDINode(SP, TI, Class);
345}
346
Amjad Aboudacee5682016-07-12 12:06:34 +0000347TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
348 TypeIndex TI,
349 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000350 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000351 (void)InsertResult;
352 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000353 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000354}
355
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000356unsigned CodeViewDebug::getPointerSizeInBytes() {
357 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
358}
359
Reid Kleckner876330d2016-02-12 21:48:30 +0000360void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
361 const DILocation *InlinedAt) {
362 if (InlinedAt) {
363 // This variable was inlined. Associate it with the InlineSite.
364 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
365 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
366 Site.InlinedLocals.emplace_back(Var);
367 } else {
368 // This variable goes in the main ProcSym.
369 CurFn->Locals.emplace_back(Var);
370 }
371}
372
Reid Kleckner829365a2016-02-11 19:41:47 +0000373static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
374 const DILocation *Loc) {
375 auto B = Locs.begin(), E = Locs.end();
376 if (std::find(B, E, Loc) == E)
377 Locs.push_back(Loc);
378}
379
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000380void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000381 const MachineFunction *MF) {
382 // Skip this instruction if it has the same location as the previous one.
Reid Kleckner45a74622017-06-30 21:33:44 +0000383 if (!DL || DL == PrevInstLoc)
Reid Kleckner9533af42016-01-16 00:09:09 +0000384 return;
385
386 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000387 if (!Scope)
388 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000389
David Majnemerc3340db2016-01-13 01:05:23 +0000390 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000391 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
392 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
393 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000394 return;
395
Reid Kleckner2214ed82016-01-29 00:49:42 +0000396 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
397 if (CI.getStartColumn() != DL.getCol())
398 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000399
Reid Kleckner2214ed82016-01-29 00:49:42 +0000400 if (!CurFn->HaveLineInfo)
401 CurFn->HaveLineInfo = true;
402 unsigned FileId = 0;
Reid Kleckner45a74622017-06-30 21:33:44 +0000403 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
Reid Kleckner2214ed82016-01-29 00:49:42 +0000404 FileId = CurFn->LastFileId;
405 else
406 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
Reid Kleckner45a74622017-06-30 21:33:44 +0000407 PrevInstLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000408
409 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000410 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000411 const DILocation *Loc = DL.get();
412
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000413 // If this location was actually inlined from somewhere else, give it the ID
414 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000415 FuncId =
416 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000417
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000418 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000419 bool FirstLoc = true;
420 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000421 InlineSite &Site =
422 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000423 if (!FirstLoc)
424 addLocIfNotPresent(Site.ChildSites, Loc);
425 FirstLoc = false;
426 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000427 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000428 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000429 }
430
Reid Klecknerdac21b42016-02-03 21:15:48 +0000431 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000432 /*PrologueEnd=*/false, /*IsStmt=*/false,
433 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000434}
435
Reid Kleckner5d122f82016-05-25 23:16:12 +0000436void CodeViewDebug::emitCodeViewMagicVersion() {
437 OS.EmitValueToAlignment(4);
438 OS.AddComment("Debug section magic");
439 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
440}
441
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000442void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000443 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000444 return;
445
446 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000447
448 // The COFF .debug$S section consists of several subsections, each starting
449 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
450 // of the payload followed by the payload itself. The subsections are 4-byte
451 // aligned.
452
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000453 // Use the generic .debug$S section, and make a subsection for all the inlined
454 // subprograms.
455 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000456
Zachary Turner8c099fe2017-05-30 16:36:15 +0000457 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000458 emitCompilerInformation();
459 endCVSubsection(CompilerInfo);
460
Reid Kleckner5d122f82016-05-25 23:16:12 +0000461 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000462
Reid Kleckner2214ed82016-01-29 00:49:42 +0000463 // Emit per-function debug information.
464 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000465 if (!P.first->isDeclarationForLinker())
466 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000467
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000468 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000469 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000470 emitDebugInfoForGlobals();
471
Hans Wennborgb510b452016-06-23 16:33:53 +0000472 // Emit retained types.
473 emitDebugInfoForRetainedTypes();
474
Reid Kleckner5d122f82016-05-25 23:16:12 +0000475 // Switch back to the generic .debug$S section after potentially processing
476 // comdat symbol sections.
477 switchToDebugSectionForSymbol(nullptr);
478
David Majnemer3128b102016-06-15 18:00:01 +0000479 // Emit UDT records for any types used by global variables.
480 if (!GlobalUDTs.empty()) {
Zachary Turner8c099fe2017-05-30 16:36:15 +0000481 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
David Majnemer3128b102016-06-15 18:00:01 +0000482 emitDebugInfoForUDTs(GlobalUDTs);
483 endCVSubsection(SymbolsEnd);
484 }
485
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000486 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000487 OS.AddComment("File index to string table offset subsection");
488 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000489
490 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000491 OS.AddComment("String table");
492 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000493
Zachary Turner048f8f92017-12-13 22:33:58 +0000494 // Emit type information and hashes last, so that any types we translate while
495 // emitting function info are included.
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000496 emitTypeInformation();
497
Zachary Turner048f8f92017-12-13 22:33:58 +0000498 if (EmitDebugGlobalHashes)
499 emitTypeGlobalHashes();
500
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000501 clear();
502}
503
David Majnemerb9456a52016-03-14 05:15:09 +0000504static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000505 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
506 // after a fixed length portion of the record. The fixed length portion should
507 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
508 // overall record size is less than the maximum allowed.
509 unsigned MaxFixedRecordLength = 0xF00;
510 SmallString<32> NullTerminatedString(
511 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000512 NullTerminatedString.push_back('\0');
513 OS.EmitBytes(NullTerminatedString);
514}
515
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000516void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000517 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000518 return;
519
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000520 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000521 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000522 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000523
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000524 SmallString<8> CommentPrefix;
525 if (OS.isVerboseAsm()) {
526 CommentPrefix += '\t';
527 CommentPrefix += Asm->MAI->getCommentString();
528 CommentPrefix += ' ';
529 }
530
Zachary Turner526f4f22017-05-19 19:26:58 +0000531 TypeTableCollection Table(TypeTable.records());
532 Optional<TypeIndex> B = Table.getFirst();
533 while (B) {
534 // This will fail if the record data is invalid.
535 CVType Record = Table.getType(*B);
536
Zachary Turner4efa0a42016-11-08 22:24:53 +0000537 if (OS.isVerboseAsm()) {
538 // Emit a block comment describing the type record for readability.
539 SmallString<512> CommentBlock;
540 raw_svector_ostream CommentOS(CommentBlock);
541 ScopedPrinter SP(CommentOS);
542 SP.setPrefix(CommentPrefix);
Zachary Turner526f4f22017-05-19 19:26:58 +0000543 TypeDumpVisitor TDV(Table, &SP, false);
544
545 Error E = codeview::visitTypeRecord(Record, *B, TDV);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000546 if (E) {
547 logAllUnhandledErrors(std::move(E), errs(), "error: ");
548 llvm_unreachable("produced malformed type record");
549 }
550 // emitRawComment will insert its own tab and comment string before
551 // the first line, so strip off our first one. It also prints its own
552 // newline.
553 OS.emitRawComment(
554 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Zachary Turner4efa0a42016-11-08 22:24:53 +0000555 }
Zachary Turner526f4f22017-05-19 19:26:58 +0000556 OS.EmitBinaryData(Record.str_data());
557 B = Table.getNext(*B);
558 }
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000559}
560
Zachary Turner048f8f92017-12-13 22:33:58 +0000561void CodeViewDebug::emitTypeGlobalHashes() {
562 if (TypeTable.empty())
563 return;
564
565 // Start the .debug$H section with the version and hash algorithm, currently
566 // hardcoded to version 0, SHA1.
567 OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
568
569 OS.EmitValueToAlignment(4);
570 OS.AddComment("Magic");
571 OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
572 OS.AddComment("Section Version");
573 OS.EmitIntValue(0, 2);
574 OS.AddComment("Hash Algorithm");
575 OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1), 2);
576
577 TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
578 for (const auto &GHR : TypeTable.hashes()) {
579 if (OS.isVerboseAsm()) {
580 // Emit an EOL-comment describing which TypeIndex this hash corresponds
581 // to, as well as the stringified SHA1 hash.
582 SmallString<32> Comment;
583 raw_svector_ostream CommentOS(Comment);
584 CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
585 OS.AddComment(Comment);
586 ++TI;
587 }
588 assert(GHR.Hash.size() % 20 == 0);
589 StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
590 GHR.Hash.size());
591 OS.EmitBinaryData(S);
592 }
593}
594
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000595static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
596 switch (DWLang) {
597 case dwarf::DW_LANG_C:
598 case dwarf::DW_LANG_C89:
599 case dwarf::DW_LANG_C99:
600 case dwarf::DW_LANG_C11:
601 case dwarf::DW_LANG_ObjC:
602 return SourceLanguage::C;
603 case dwarf::DW_LANG_C_plus_plus:
604 case dwarf::DW_LANG_C_plus_plus_03:
605 case dwarf::DW_LANG_C_plus_plus_11:
606 case dwarf::DW_LANG_C_plus_plus_14:
607 return SourceLanguage::Cpp;
608 case dwarf::DW_LANG_Fortran77:
609 case dwarf::DW_LANG_Fortran90:
610 case dwarf::DW_LANG_Fortran03:
611 case dwarf::DW_LANG_Fortran08:
612 return SourceLanguage::Fortran;
613 case dwarf::DW_LANG_Pascal83:
614 return SourceLanguage::Pascal;
615 case dwarf::DW_LANG_Cobol74:
616 case dwarf::DW_LANG_Cobol85:
617 return SourceLanguage::Cobol;
618 case dwarf::DW_LANG_Java:
619 return SourceLanguage::Java;
Reid Kleckner898ddf62017-07-24 16:16:42 +0000620 case dwarf::DW_LANG_D:
621 return SourceLanguage::D;
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000622 default:
623 // There's no CodeView representation for this language, and CV doesn't
624 // have an "unknown" option for the language field, so we'll use MASM,
625 // as it's very low level.
626 return SourceLanguage::Masm;
627 }
628}
629
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000630namespace {
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000631struct Version {
632 int Part[4];
633};
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000634} // end anonymous namespace
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000635
636// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
637// the version number.
638static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000639 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000640 int N = 0;
641 for (const char C : Name) {
642 if (isdigit(C)) {
643 V.Part[N] *= 10;
644 V.Part[N] += C - '0';
645 } else if (C == '.') {
646 ++N;
647 if (N >= 4)
648 return V;
649 } else if (N > 0)
650 return V;
651 }
652 return V;
653}
654
655static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
656 switch (Type) {
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000657 case Triple::ArchType::x86:
658 return CPUType::Pentium3;
659 case Triple::ArchType::x86_64:
660 return CPUType::X64;
661 case Triple::ArchType::thumb:
662 return CPUType::Thumb;
663 case Triple::ArchType::aarch64:
664 return CPUType::ARM64;
665 default:
666 report_fatal_error("target architecture doesn't map to a CodeView CPUType");
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000667 }
668}
669
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000670void CodeViewDebug::emitCompilerInformation() {
671 MCContext &Context = MMI->getContext();
672 MCSymbol *CompilerBegin = Context.createTempSymbol(),
673 *CompilerEnd = Context.createTempSymbol();
674 OS.AddComment("Record length");
675 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
676 OS.EmitLabel(CompilerBegin);
677 OS.AddComment("Record kind: S_COMPILE3");
678 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
679 uint32_t Flags = 0;
680
681 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
682 const MDNode *Node = *CUs->operands().begin();
683 const auto *CU = cast<DICompileUnit>(Node);
684
685 // The low byte of the flags indicates the source language.
686 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
687 // TODO: Figure out which other flags need to be set.
688
689 OS.AddComment("Flags and language");
690 OS.EmitIntValue(Flags, 4);
691
692 OS.AddComment("CPUType");
693 CPUType CPU =
694 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
695 OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
696
697 StringRef CompilerVersion = CU->getProducer();
698 Version FrontVer = parseVersion(CompilerVersion);
699 OS.AddComment("Frontend version");
700 for (int N = 0; N < 4; ++N)
701 OS.EmitIntValue(FrontVer.Part[N], 2);
702
703 // Some Microsoft tools, like Binscope, expect a backend version number of at
704 // least 8.something, so we'll coerce the LLVM version into a form that
705 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000706 int Major = 1000 * LLVM_VERSION_MAJOR +
707 10 * LLVM_VERSION_MINOR +
708 LLVM_VERSION_PATCH;
709 // Clamp it for builds that use unusually large version numbers.
710 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
711 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000712 OS.AddComment("Backend version");
713 for (int N = 0; N < 4; ++N)
714 OS.EmitIntValue(BackVer.Part[N], 2);
715
716 OS.AddComment("Null-terminated compiler version string");
717 emitNullTerminatedSymbolName(OS, CompilerVersion);
718
719 OS.EmitLabel(CompilerEnd);
720}
721
Reid Kleckner5d122f82016-05-25 23:16:12 +0000722void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000723 if (InlinedSubprograms.empty())
724 return;
725
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000726 OS.AddComment("Inlinee lines subsection");
Zachary Turner8c099fe2017-05-30 16:36:15 +0000727 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000728
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000729 // We emit the checksum info for files. This is used by debuggers to
730 // determine if a pdb matches the source before loading it. Visual Studio,
731 // for instance, will display a warning that the breakpoints are not valid if
732 // the pdb does not match the source.
David Majnemer30579ec2016-02-02 23:18:23 +0000733 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000734 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
735
736 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000737 assert(TypeIndices.count({SP, nullptr}));
738 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000739
David Majnemer30579ec2016-02-02 23:18:23 +0000740 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000741 unsigned FileId = maybeRecordFile(SP->getFile());
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000742 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000743 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000744 OS.AddBlankLine();
David Majnemer30579ec2016-02-02 23:18:23 +0000745 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000746 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000747 OS.AddComment("Offset into filechecksum table");
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000748 OS.EmitCVFileChecksumOffsetDirective(FileId);
David Majnemer30579ec2016-02-02 23:18:23 +0000749 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000750 OS.EmitIntValue(SP->getLine(), 4);
751 }
752
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000753 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000754}
755
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000756void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
757 const DILocation *InlinedAt,
758 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000759 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
760 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000761
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000762 assert(TypeIndices.count({Site.Inlinee, nullptr}));
763 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000764
765 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000766 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000767 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000768 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000769 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000770 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000771
Reid Klecknerdac21b42016-02-03 21:15:48 +0000772 OS.AddComment("PtrParent");
773 OS.EmitIntValue(0, 4);
774 OS.AddComment("PtrEnd");
775 OS.EmitIntValue(0, 4);
776 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000777 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000778
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000779 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
780 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000781
782 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000783 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000784
785 OS.EmitLabel(InlineEnd);
786
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000787 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000788
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000789 // Recurse on child inlined call sites before closing the scope.
790 for (const DILocation *ChildSite : Site.ChildSites) {
791 auto I = FI.InlineSites.find(ChildSite);
792 assert(I != FI.InlineSites.end() &&
793 "child site not in function inline site map");
794 emitInlinedCallSite(FI, ChildSite, I->second);
795 }
796
797 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000798 OS.AddComment("Record length");
799 OS.EmitIntValue(2, 2); // RecordLength
800 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000801 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000802}
803
Reid Kleckner5d122f82016-05-25 23:16:12 +0000804void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
805 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
806 // comdat key. A section may be comdat because of -ffunction-sections or
807 // because it is comdat in the IR.
808 MCSectionCOFF *GVSec =
809 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
810 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
811
812 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
813 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
814 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
815
816 OS.SwitchSection(DebugSec);
817
818 // Emit the magic version number if this is the first time we've switched to
819 // this section.
820 if (ComdatDebugSections.insert(DebugSec).second)
821 emitCodeViewMagicVersion();
822}
823
Reid Kleckner2214ed82016-01-29 00:49:42 +0000824void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
825 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000826 // For each function there is a separate subsection
827 // which holds the PC to file:line table.
828 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000829 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000830
Reid Kleckner5d122f82016-05-25 23:16:12 +0000831 // Switch to the to a comdat section, if appropriate.
832 switchToDebugSectionForSymbol(Fn);
833
Reid Klecknerac945e22016-06-17 16:11:20 +0000834 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000835 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000836 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000837 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000838
839 // If we have a display name, build the fully qualified name by walking the
840 // chain of scopes.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000841 if (!SP->getName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000842 FuncName =
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000843 getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000844
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000845 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000846 if (FuncName.empty())
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +0000847 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000848
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000849 // Emit FPO data, but only on 32-bit x86. No other platforms use it.
850 if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
851 OS.EmitCVFPOData(Fn);
852
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000853 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000854 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Zachary Turner8c099fe2017-05-30 16:36:15 +0000855 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000856 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000857 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
858 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000859 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000860 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000861 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000862
Reid Kleckner4ad127f2016-09-14 21:49:21 +0000863 if (GV->hasLocalLinkage()) {
864 OS.AddComment("Record kind: S_LPROC32_ID");
865 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
866 } else {
867 OS.AddComment("Record kind: S_GPROC32_ID");
868 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
869 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000870
David Majnemer30579ec2016-02-02 23:18:23 +0000871 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000872 OS.AddComment("PtrParent");
873 OS.EmitIntValue(0, 4);
874 OS.AddComment("PtrEnd");
875 OS.EmitIntValue(0, 4);
876 OS.AddComment("PtrNext");
877 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000878 // This is the important bit that tells the debugger where the function
879 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000880 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000881 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000882 OS.AddComment("Offset after prologue");
883 OS.EmitIntValue(0, 4);
884 OS.AddComment("Offset before epilogue");
885 OS.EmitIntValue(0, 4);
886 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000887 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000888 OS.AddComment("Function section relative address");
Keno Fischerf7d84ee2017-01-02 03:00:19 +0000889 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000890 OS.AddComment("Function section index");
891 OS.EmitCOFFSectionIndex(Fn);
892 OS.AddComment("Flags");
893 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000894 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000895 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000896 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000897 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000898 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000899
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000900 emitLocalVariableList(FI.Locals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000901
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000902 // Emit inlined call site information. Only emit functions inlined directly
903 // into the parent function. We'll emit the other sites recursively as part
904 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000905 for (const DILocation *InlinedAt : FI.ChildSites) {
906 auto I = FI.InlineSites.find(InlinedAt);
907 assert(I != FI.InlineSites.end() &&
908 "child site not in function inline site map");
909 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000910 }
911
Reid Klecknere33c94f2017-09-05 20:14:58 +0000912 for (auto Annot : FI.Annotations) {
913 MCSymbol *Label = Annot.first;
914 MDTuple *Strs = cast<MDTuple>(Annot.second);
915 MCSymbol *AnnotBegin = MMI->getContext().createTempSymbol(),
916 *AnnotEnd = MMI->getContext().createTempSymbol();
917 OS.AddComment("Record length");
918 OS.emitAbsoluteSymbolDiff(AnnotEnd, AnnotBegin, 2);
919 OS.EmitLabel(AnnotBegin);
920 OS.AddComment("Record kind: S_ANNOTATION");
921 OS.EmitIntValue(SymbolKind::S_ANNOTATION, 2);
922 OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
923 // FIXME: Make sure we don't overflow the max record size.
924 OS.EmitCOFFSectionIndex(Label);
925 OS.EmitIntValue(Strs->getNumOperands(), 2);
926 for (Metadata *MD : Strs->operands()) {
927 // MDStrings are null terminated, so we can do EmitBytes and get the
928 // nice .asciz directive.
929 StringRef Str = cast<MDString>(MD)->getString();
930 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
931 OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
932 }
933 OS.EmitLabel(AnnotEnd);
934 }
935
David Majnemer3128b102016-06-15 18:00:01 +0000936 if (SP != nullptr)
937 emitDebugInfoForUDTs(LocalUDTs);
938
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000939 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000940 OS.AddComment("Record length");
941 OS.EmitIntValue(0x0002, 2);
942 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000943 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000944 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000945 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000946
Reid Kleckner2214ed82016-01-29 00:49:42 +0000947 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000948 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000949}
950
Reid Kleckner876330d2016-02-12 21:48:30 +0000951CodeViewDebug::LocalVarDefRange
952CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
953 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000954 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000955 DR.DataOffset = Offset;
956 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000957 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000958 DR.StructOffset = 0;
959 DR.CVRegister = CVRegister;
960 return DR;
961}
962
963CodeViewDebug::LocalVarDefRange
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000964CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
965 int Offset, bool IsSubfield,
966 uint16_t StructOffset) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000967 LocalVarDefRange DR;
Reid Kleckner2b3e6422016-10-05 21:21:33 +0000968 DR.InMemory = InMemory;
969 DR.DataOffset = Offset;
970 DR.IsSubfield = IsSubfield;
971 DR.StructOffset = StructOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +0000972 DR.CVRegister = CVRegister;
973 return DR;
974}
975
Matthias Braunef331ef2016-11-30 23:48:50 +0000976void CodeViewDebug::collectVariableInfoFromMFTable(
Reid Kleckner876330d2016-02-12 21:48:30 +0000977 DenseSet<InlinedVariable> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +0000978 const MachineFunction &MF = *Asm->MF;
979 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +0000980 const TargetFrameLowering *TFI = TSI.getFrameLowering();
981 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
982
Matthias Braunef331ef2016-11-30 23:48:50 +0000983 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000984 if (!VI.Var)
985 continue;
986 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
987 "Expected inlined-at fields to agree");
988
Reid Kleckner876330d2016-02-12 21:48:30 +0000989 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000990 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
991
992 // If variable scope is not found then skip this variable.
993 if (!Scope)
994 continue;
995
Reid Klecknerb5fced72017-05-09 19:59:29 +0000996 // If the variable has an attached offset expression, extract it.
997 // FIXME: Try to handle DW_OP_deref as well.
998 int64_t ExprOffset = 0;
999 if (VI.Expr)
1000 if (!VI.Expr->extractIfOffset(ExprOffset))
1001 continue;
1002
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001003 // Get the frame register used and the offset.
1004 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001005 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1006 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001007
1008 // Calculate the label ranges.
Reid Klecknerb5fced72017-05-09 19:59:29 +00001009 LocalVarDefRange DefRange =
1010 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001011 for (const InsnRange &Range : Scope->getRanges()) {
1012 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1013 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +00001014 End = End ? End : Asm->getFunctionEnd();
1015 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001016 }
1017
Reid Kleckner876330d2016-02-12 21:48:30 +00001018 LocalVariable Var;
1019 Var.DIVar = VI.Var;
1020 Var.DefRanges.emplace_back(std::move(DefRange));
1021 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
1022 }
1023}
1024
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001025static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1026 return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1027}
1028
1029static bool needsReferenceType(const DbgVariableLocation &Loc) {
1030 return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1031}
1032
Bob Haarman223303c2017-08-29 20:59:25 +00001033void CodeViewDebug::calculateRanges(
1034 LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
1035 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1036
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001037 // Calculate the definition ranges.
Bob Haarman223303c2017-08-29 20:59:25 +00001038 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1039 const InsnRange &Range = *I;
1040 const MachineInstr *DVInst = Range.first;
1041 assert(DVInst->isDebugValue() && "Invalid History entry");
1042 // FIXME: Find a way to represent constant variables, since they are
1043 // relatively common.
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001044 Optional<DbgVariableLocation> Location =
1045 DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1046 if (!Location)
Bob Haarmana88bce12017-08-29 21:01:55 +00001047 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001048
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001049 // CodeView can only express variables in register and variables in memory
1050 // at a constant offset from a register. However, for variables passed
1051 // indirectly by pointer, it is common for that pointer to be spilled to a
1052 // stack location. For the special case of one offseted load followed by a
1053 // zero offset load (a pointer spilled to the stack), we change the type of
1054 // the local variable from a value type to a reference type. This tricks the
1055 // debugger into doing the load for us.
1056 if (Var.UseReferenceType) {
1057 // We're using a reference type. Drop the last zero offset load.
1058 if (canUseReferenceType(*Location))
1059 Location->LoadChain.pop_back();
1060 else
1061 continue;
1062 } else if (needsReferenceType(*Location)) {
1063 // This location can't be expressed without switching to a reference type.
1064 // Start over using that.
1065 Var.UseReferenceType = true;
Bob Haarman223303c2017-08-29 20:59:25 +00001066 Var.DefRanges.clear();
1067 calculateRanges(Var, Ranges);
1068 return;
1069 }
1070
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001071 // We can only handle a register or an offseted load of a register.
1072 if (Location->Register == 0 || Location->LoadChain.size() > 1)
Bob Haarman223303c2017-08-29 20:59:25 +00001073 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001074 {
1075 LocalVarDefRange DR;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001076 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001077 DR.InMemory = !Location->LoadChain.empty();
1078 DR.DataOffset =
1079 !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001080 if (Location->FragmentInfo) {
Bob Haarman223303c2017-08-29 20:59:25 +00001081 DR.IsSubfield = true;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001082 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
Bob Haarman223303c2017-08-29 20:59:25 +00001083 } else {
1084 DR.IsSubfield = false;
1085 DR.StructOffset = 0;
1086 }
1087
1088 if (Var.DefRanges.empty() ||
1089 Var.DefRanges.back().isDifferentLocation(DR)) {
1090 Var.DefRanges.emplace_back(std::move(DR));
1091 }
1092 }
1093
1094 // Compute the label range.
1095 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1096 const MCSymbol *End = getLabelAfterInsn(Range.second);
1097 if (!End) {
1098 // This range is valid until the next overlapping bitpiece. In the
1099 // common case, ranges will not be bitpieces, so they will overlap.
1100 auto J = std::next(I);
1101 const DIExpression *DIExpr = DVInst->getDebugExpression();
1102 while (J != E &&
1103 !fragmentsOverlap(DIExpr, J->first->getDebugExpression()))
1104 ++J;
1105 if (J != E)
1106 End = getLabelBeforeInsn(J->first);
1107 else
1108 End = Asm->getFunctionEnd();
1109 }
1110
1111 // If the last range end is our begin, just extend the last range.
1112 // Otherwise make a new range.
1113 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1114 Var.DefRanges.back().Ranges;
1115 if (!R.empty() && R.back().second == Begin)
1116 R.back().second = End;
1117 else
1118 R.emplace_back(Begin, End);
1119
1120 // FIXME: Do more range combining.
1121 }
1122}
1123
Reid Kleckner876330d2016-02-12 21:48:30 +00001124void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1125 DenseSet<InlinedVariable> Processed;
1126 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +00001127 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +00001128
Reid Kleckner876330d2016-02-12 21:48:30 +00001129 for (const auto &I : DbgValues) {
1130 InlinedVariable IV = I.first;
1131 if (Processed.count(IV))
1132 continue;
1133 const DILocalVariable *DIVar = IV.first;
1134 const DILocation *InlinedAt = IV.second;
1135
1136 // Instruction ranges, specifying where IV is accessible.
1137 const auto &Ranges = I.second;
1138
1139 LexicalScope *Scope = nullptr;
1140 if (InlinedAt)
1141 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1142 else
1143 Scope = LScopes.findLexicalScope(DIVar->getScope());
1144 // If variable scope is not found then skip this variable.
1145 if (!Scope)
1146 continue;
1147
1148 LocalVariable Var;
1149 Var.DIVar = DIVar;
1150
Bob Haarman223303c2017-08-29 20:59:25 +00001151 calculateRanges(Var, Ranges);
Reid Kleckner876330d2016-02-12 21:48:30 +00001152 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001153 }
1154}
1155
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001156void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00001157 const Function &GV = MF->getFunction();
1158 assert(FnDebugInfo.count(&GV) == false);
1159 CurFn = &FnDebugInfo[&GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +00001160 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001161 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001162
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001163 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1164
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001165 // Find the end of the function prolog. First known non-DBG_VALUE and
1166 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001167 // FIXME: is there a simpler a way to do this? Can we just search
1168 // for the first instruction of the function, not the last of the prolog?
1169 DebugLoc PrologEndLoc;
1170 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001171 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001172 for (const auto &MI : MBB) {
Adrian Prantlfb31da12017-05-22 20:47:09 +00001173 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001174 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001175 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001176 break;
Adrian Prantlfb31da12017-05-22 20:47:09 +00001177 } else if (!MI.isMetaInstruction()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001178 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001179 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001180 }
1181 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001182
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001183 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001184 if (PrologEndLoc && !EmptyPrologue) {
1185 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001186 maybeRecordLocation(FnStartDL, MF);
1187 }
1188}
1189
Zachary Turnera7b04172017-08-28 18:49:04 +00001190static bool shouldEmitUdt(const DIType *T) {
Zachary Turner37c74742017-09-05 22:06:39 +00001191 if (!T)
1192 return false;
1193
1194 // MSVC does not emit UDTs for typedefs that are scoped to classes.
1195 if (T->getTag() == dwarf::DW_TAG_typedef) {
1196 if (DIScope *Scope = T->getScope().resolve()) {
1197 switch (Scope->getTag()) {
1198 case dwarf::DW_TAG_structure_type:
1199 case dwarf::DW_TAG_class_type:
1200 case dwarf::DW_TAG_union_type:
1201 return false;
1202 }
1203 }
1204 }
1205
Zachary Turnera7b04172017-08-28 18:49:04 +00001206 while (true) {
1207 if (!T || T->isForwardDecl())
1208 return false;
1209
1210 const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1211 if (!DT)
1212 return true;
1213 T = DT->getBaseType().resolve();
1214 }
1215 return true;
1216}
1217
1218void CodeViewDebug::addToUDTs(const DIType *Ty) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001219 // Don't record empty UDTs.
1220 if (Ty->getName().empty())
1221 return;
Zachary Turnera7b04172017-08-28 18:49:04 +00001222 if (!shouldEmitUdt(Ty))
1223 return;
Reid Klecknerad56ea32016-07-01 22:24:51 +00001224
Hans Wennborg4b63a982016-06-23 22:57:25 +00001225 SmallVector<StringRef, 5> QualifiedNameComponents;
1226 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1227 Ty->getScope().resolve(), QualifiedNameComponents);
1228
1229 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001230 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001231
Zachary Turnera7b04172017-08-28 18:49:04 +00001232 if (ClosestSubprogram == nullptr) {
1233 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1234 } else if (ClosestSubprogram == CurrentSubprogram) {
1235 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1236 }
Hans Wennborg4b63a982016-06-23 22:57:25 +00001237
1238 // TODO: What if the ClosestSubprogram is neither null or the current
1239 // subprogram? Currently, the UDT just gets dropped on the floor.
1240 //
1241 // The current behavior is not desirable. To get maximal fidelity, we would
1242 // need to perform all type translation before beginning emission of .debug$S
1243 // and then make LocalUDTs a member of FunctionInfo
1244}
1245
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001246TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001247 // Generic dispatch for lowering an unknown type.
1248 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001249 case dwarf::DW_TAG_array_type:
1250 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001251 case dwarf::DW_TAG_typedef:
1252 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001253 case dwarf::DW_TAG_base_type:
1254 return lowerTypeBasic(cast<DIBasicType>(Ty));
1255 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001256 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1257 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1258 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001259 case dwarf::DW_TAG_reference_type:
1260 case dwarf::DW_TAG_rvalue_reference_type:
1261 return lowerTypePointer(cast<DIDerivedType>(Ty));
1262 case dwarf::DW_TAG_ptr_to_member_type:
1263 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1264 case dwarf::DW_TAG_const_type:
1265 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001266 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001267 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001268 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001269 if (ClassTy) {
1270 // The member function type of a member function pointer has no
1271 // ThisAdjustment.
1272 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001273 /*ThisAdjustment=*/0,
1274 /*IsStaticMethod=*/false);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001275 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001276 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001277 case dwarf::DW_TAG_enumeration_type:
1278 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001279 case dwarf::DW_TAG_class_type:
1280 case dwarf::DW_TAG_structure_type:
1281 return lowerTypeClass(cast<DICompositeType>(Ty));
1282 case dwarf::DW_TAG_union_type:
1283 return lowerTypeUnion(cast<DICompositeType>(Ty));
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001284 case dwarf::DW_TAG_unspecified_type:
1285 return TypeIndex::None();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001286 default:
1287 // Use the null type index.
1288 return TypeIndex();
1289 }
1290}
1291
David Majnemerd065e232016-06-02 06:21:37 +00001292TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001293 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1294 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001295 StringRef TypeName = Ty->getName();
1296
Zachary Turnera7b04172017-08-28 18:49:04 +00001297 addToUDTs(Ty);
David Majnemer3128b102016-06-15 18:00:01 +00001298
David Majnemerd065e232016-06-02 06:21:37 +00001299 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001300 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001301 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001302 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001303 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001304 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001305
David Majnemerd065e232016-06-02 06:21:37 +00001306 return UnderlyingTypeIndex;
1307}
1308
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001309TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1310 DITypeRef ElementTypeRef = Ty->getBaseType();
1311 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1312 // IndexType is size_t, which depends on the bitness of the target.
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001313 TypeIndex IndexType = Asm->TM.getPointerSize() == 8
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001314 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1315 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001316
1317 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1318
Amjad Aboudacee5682016-07-12 12:06:34 +00001319 // Add subranges to array type.
1320 DINodeArray Elements = Ty->getElements();
1321 for (int i = Elements.size() - 1; i >= 0; --i) {
1322 const DINode *Element = Elements[i];
1323 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1324
1325 const DISubrange *Subrange = cast<DISubrange>(Element);
1326 assert(Subrange->getLowerBound() == 0 &&
1327 "codeview doesn't support subranges with lower bounds");
1328 int64_t Count = Subrange->getCount();
1329
Reid Klecknercd7bba02017-09-13 23:30:01 +00001330 // Forward declarations of arrays without a size and VLAs use a count of -1.
1331 // Emit a count of zero in these cases to match what MSVC does for arrays
1332 // without a size. MSVC doesn't support VLAs, so it's not clear what we
1333 // should do for them even if we could distinguish them.
Reid Kleckner6b78e162017-03-24 23:28:42 +00001334 if (Count == -1)
Reid Kleckner89af1122017-09-13 21:54:20 +00001335 Count = 0;
Amjad Aboudacee5682016-07-12 12:06:34 +00001336
Amjad Aboudacee5682016-07-12 12:06:34 +00001337 // Update the element size and element type index for subsequent subranges.
1338 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001339
1340 // If this is the outermost array, use the size from the array. It will be
Reid Kleckner6b78e162017-03-24 23:28:42 +00001341 // more accurate if we had a VLA or an incomplete element type size.
Reid Kleckner10762882016-09-09 17:29:36 +00001342 uint64_t ArraySize =
1343 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1344
1345 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001346 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00001347 ElementTypeIndex = TypeTable.writeLeafType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001348 }
1349
Amjad Aboudacee5682016-07-12 12:06:34 +00001350 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001351}
1352
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001353TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1354 TypeIndex Index;
1355 dwarf::TypeKind Kind;
1356 uint32_t ByteSize;
1357
1358 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001359 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001360
1361 SimpleTypeKind STK = SimpleTypeKind::None;
1362 switch (Kind) {
1363 case dwarf::DW_ATE_address:
1364 // FIXME: Translate
1365 break;
1366 case dwarf::DW_ATE_boolean:
1367 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001368 case 1: STK = SimpleTypeKind::Boolean8; break;
1369 case 2: STK = SimpleTypeKind::Boolean16; break;
1370 case 4: STK = SimpleTypeKind::Boolean32; break;
1371 case 8: STK = SimpleTypeKind::Boolean64; break;
1372 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001373 }
1374 break;
1375 case dwarf::DW_ATE_complex_float:
1376 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001377 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001378 case 4: STK = SimpleTypeKind::Complex32; break;
1379 case 8: STK = SimpleTypeKind::Complex64; break;
1380 case 10: STK = SimpleTypeKind::Complex80; break;
1381 case 16: STK = SimpleTypeKind::Complex128; break;
1382 }
1383 break;
1384 case dwarf::DW_ATE_float:
1385 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001386 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001387 case 4: STK = SimpleTypeKind::Float32; break;
1388 case 6: STK = SimpleTypeKind::Float48; break;
1389 case 8: STK = SimpleTypeKind::Float64; break;
1390 case 10: STK = SimpleTypeKind::Float80; break;
1391 case 16: STK = SimpleTypeKind::Float128; break;
1392 }
1393 break;
1394 case dwarf::DW_ATE_signed:
1395 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001396 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1397 case 2: STK = SimpleTypeKind::Int16Short; break;
1398 case 4: STK = SimpleTypeKind::Int32; break;
1399 case 8: STK = SimpleTypeKind::Int64Quad; break;
1400 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001401 }
1402 break;
1403 case dwarf::DW_ATE_unsigned:
1404 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001405 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1406 case 2: STK = SimpleTypeKind::UInt16Short; break;
1407 case 4: STK = SimpleTypeKind::UInt32; break;
1408 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1409 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001410 }
1411 break;
1412 case dwarf::DW_ATE_UTF:
1413 switch (ByteSize) {
1414 case 2: STK = SimpleTypeKind::Character16; break;
1415 case 4: STK = SimpleTypeKind::Character32; break;
1416 }
1417 break;
1418 case dwarf::DW_ATE_signed_char:
1419 if (ByteSize == 1)
1420 STK = SimpleTypeKind::SignedCharacter;
1421 break;
1422 case dwarf::DW_ATE_unsigned_char:
1423 if (ByteSize == 1)
1424 STK = SimpleTypeKind::UnsignedCharacter;
1425 break;
1426 default:
1427 break;
1428 }
1429
1430 // Apply some fixups based on the source-level type name.
1431 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1432 STK = SimpleTypeKind::Int32Long;
1433 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1434 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001435 if (STK == SimpleTypeKind::UInt16Short &&
1436 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001437 STK = SimpleTypeKind::WideCharacter;
1438 if ((STK == SimpleTypeKind::SignedCharacter ||
1439 STK == SimpleTypeKind::UnsignedCharacter) &&
1440 Ty->getName() == "char")
1441 STK = SimpleTypeKind::NarrowCharacter;
1442
1443 return TypeIndex(STK);
1444}
1445
1446TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1447 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1448
1449 // Pointers to simple types can use SimpleTypeMode, rather than having a
1450 // dedicated pointer type record.
1451 if (PointeeTI.isSimple() &&
1452 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1453 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1454 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1455 ? SimpleTypeMode::NearPointer64
1456 : SimpleTypeMode::NearPointer32;
1457 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1458 }
1459
1460 PointerKind PK =
1461 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1462 PointerMode PM = PointerMode::Pointer;
1463 switch (Ty->getTag()) {
1464 default: llvm_unreachable("not a pointer tag type");
1465 case dwarf::DW_TAG_pointer_type:
1466 PM = PointerMode::Pointer;
1467 break;
1468 case dwarf::DW_TAG_reference_type:
1469 PM = PointerMode::LValueReference;
1470 break;
1471 case dwarf::DW_TAG_rvalue_reference_type:
1472 PM = PointerMode::RValueReference;
1473 break;
1474 }
1475 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1476 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1477 // do.
1478 PointerOptions PO = PointerOptions::None;
1479 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00001480 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001481}
1482
Reid Kleckner6fa15462016-06-17 22:14:39 +00001483static PointerToMemberRepresentation
1484translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1485 // SizeInBytes being zero generally implies that the member pointer type was
1486 // incomplete, which can happen if it is part of a function prototype. In this
1487 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001488 if (IsPMF) {
1489 switch (Flags & DINode::FlagPtrToMemberRep) {
1490 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001491 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1492 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001493 case DINode::FlagSingleInheritance:
1494 return PointerToMemberRepresentation::SingleInheritanceFunction;
1495 case DINode::FlagMultipleInheritance:
1496 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1497 case DINode::FlagVirtualInheritance:
1498 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1499 }
1500 } else {
1501 switch (Flags & DINode::FlagPtrToMemberRep) {
1502 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001503 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1504 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001505 case DINode::FlagSingleInheritance:
1506 return PointerToMemberRepresentation::SingleInheritanceData;
1507 case DINode::FlagMultipleInheritance:
1508 return PointerToMemberRepresentation::MultipleInheritanceData;
1509 case DINode::FlagVirtualInheritance:
1510 return PointerToMemberRepresentation::VirtualInheritanceData;
1511 }
1512 }
1513 llvm_unreachable("invalid ptr to member representation");
1514}
1515
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001516TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1517 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1518 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001519 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001520 PointerKind PK = Asm->TM.getPointerSize() == 8 ? PointerKind::Near64
1521 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001522 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1523 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1524 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001525 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001526 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1527 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1528 MemberPointerInfo MPI(
1529 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001530 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner6900de12017-11-28 18:33:17 +00001531 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001532}
1533
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001534/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1535/// have a translation, use the NearC convention.
1536static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1537 switch (DwarfCC) {
1538 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1539 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1540 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1541 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1542 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1543 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1544 }
1545 return CallingConvention::NearC;
1546}
1547
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001548TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1549 ModifierOptions Mods = ModifierOptions::None;
1550 bool IsModifier = true;
1551 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001552 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001553 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001554 switch (BaseTy->getTag()) {
1555 case dwarf::DW_TAG_const_type:
1556 Mods |= ModifierOptions::Const;
1557 break;
1558 case dwarf::DW_TAG_volatile_type:
1559 Mods |= ModifierOptions::Volatile;
1560 break;
1561 default:
1562 IsModifier = false;
1563 break;
1564 }
1565 if (IsModifier)
1566 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1567 }
1568 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001569 ModifierRecord MR(ModifiedTI, Mods);
Zachary Turner6900de12017-11-28 18:33:17 +00001570 return TypeTable.writeLeafType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001571}
1572
David Majnemer75c3ebf2016-06-02 17:13:53 +00001573TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1574 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1575 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1576 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1577
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001578 // MSVC uses type none for variadic argument.
1579 if (ReturnAndArgTypeIndices.size() > 1 &&
1580 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1581 ReturnAndArgTypeIndices.back() = TypeIndex::None();
1582 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001583 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1584 ArrayRef<TypeIndex> ArgTypeIndices = None;
1585 if (!ReturnAndArgTypeIndices.empty()) {
1586 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1587 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1588 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1589 }
1590
1591 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001592 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001593
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001594 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1595
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001596 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1597 ArgTypeIndices.size(), ArgListIndex);
Zachary Turner6900de12017-11-28 18:33:17 +00001598 return TypeTable.writeLeafType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001599}
1600
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001601TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001602 const DIType *ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001603 int ThisAdjustment,
1604 bool IsStaticMethod) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001605 // Lower the containing class type.
1606 TypeIndex ClassType = getTypeIndex(ClassTy);
1607
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001608 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1609 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1610 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1611
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001612 // MSVC uses type none for variadic argument.
1613 if (ReturnAndArgTypeIndices.size() > 1 &&
1614 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1615 ReturnAndArgTypeIndices.back() = TypeIndex::None();
1616 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001617 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1618 ArrayRef<TypeIndex> ArgTypeIndices = None;
1619 if (!ReturnAndArgTypeIndices.empty()) {
1620 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1621 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1622 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1623 }
Reid Kleckner87288b92017-09-15 00:59:07 +00001624 TypeIndex ThisTypeIndex;
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001625 if (!IsStaticMethod && !ArgTypeIndices.empty()) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001626 ThisTypeIndex = ArgTypeIndices.front();
1627 ArgTypeIndices = ArgTypeIndices.drop_front();
1628 }
1629
1630 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001631 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001632
1633 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1634
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001635 // TODO: Need to use the correct values for FunctionOptions.
Zachary Turner4efa0a42016-11-08 22:24:53 +00001636 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1637 FunctionOptions::None, ArgTypeIndices.size(),
1638 ArgListIndex, ThisAdjustment);
Zachary Turner6900de12017-11-28 18:33:17 +00001639 return TypeTable.writeLeafType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001640}
1641
Reid Kleckner9dac4732016-08-31 15:59:30 +00001642TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001643 unsigned VSlotCount =
1644 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
Reid Kleckner9dac4732016-08-31 15:59:30 +00001645 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001646
1647 VFTableShapeRecord VFTSR(Slots);
Zachary Turner6900de12017-11-28 18:33:17 +00001648 return TypeTable.writeLeafType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001649}
1650
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001651static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1652 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001653 case DINode::FlagPrivate: return MemberAccess::Private;
1654 case DINode::FlagPublic: return MemberAccess::Public;
1655 case DINode::FlagProtected: return MemberAccess::Protected;
1656 case 0:
1657 // If there was no explicit access control, provide the default for the tag.
1658 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1659 : MemberAccess::Public;
1660 }
1661 llvm_unreachable("access flags are exclusive");
1662}
1663
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001664static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1665 if (SP->isArtificial())
1666 return MethodOptions::CompilerGenerated;
1667
1668 // FIXME: Handle other MethodOptions.
1669
1670 return MethodOptions::None;
1671}
1672
1673static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1674 bool Introduced) {
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001675 if (SP->getFlags() & DINode::FlagStaticMember)
1676 return MethodKind::Static;
1677
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001678 switch (SP->getVirtuality()) {
1679 case dwarf::DW_VIRTUALITY_none:
1680 break;
1681 case dwarf::DW_VIRTUALITY_virtual:
1682 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1683 case dwarf::DW_VIRTUALITY_pure_virtual:
1684 return Introduced ? MethodKind::PureIntroducingVirtual
1685 : MethodKind::PureVirtual;
1686 default:
1687 llvm_unreachable("unhandled virtuality case");
1688 }
1689
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001690 return MethodKind::Vanilla;
1691}
1692
Reid Klecknera8d57402016-06-03 15:58:20 +00001693static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1694 switch (Ty->getTag()) {
1695 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1696 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1697 }
1698 llvm_unreachable("unexpected tag");
1699}
1700
Reid Klecknere092dad2016-07-02 00:11:07 +00001701/// Return ClassOptions that should be present on both the forward declaration
1702/// and the defintion of a tag type.
1703static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1704 ClassOptions CO = ClassOptions::None;
1705
1706 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001707 // appear to give every type a linkage name, which may be problematic for us.
1708 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001709 if (!Ty->getIdentifier().empty())
1710 CO |= ClassOptions::HasUniqueName;
1711
1712 // Put the Nested flag on a type if it appears immediately inside a tag type.
1713 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1714 // here. That flag is only set on definitions, and not forward declarations.
1715 const DIScope *ImmediateScope = Ty->getScope().resolve();
1716 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1717 CO |= ClassOptions::Nested;
1718
1719 // Put the Scoped flag on function-local types.
1720 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1721 Scope = Scope->getScope().resolve()) {
1722 if (isa<DISubprogram>(Scope)) {
1723 CO |= ClassOptions::Scoped;
1724 break;
1725 }
1726 }
1727
1728 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001729}
1730
David Majnemer979cb882016-06-16 21:32:16 +00001731TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001732 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001733 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001734 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001735
David Majnemerda9548f2016-06-17 16:13:21 +00001736 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001737 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001738 } else {
Zachary Turner6900de12017-11-28 18:33:17 +00001739 ContinuationRecordBuilder ContinuationBuilder;
1740 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
David Majnemerda9548f2016-06-17 16:13:21 +00001741 for (const DINode *Element : Ty->getElements()) {
1742 // We assume that the frontend provides all members in source declaration
1743 // order, which is what MSVC does.
1744 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001745 EnumeratorRecord ER(MemberAccess::Public,
1746 APSInt::getUnsigned(Enumerator->getValue()),
1747 Enumerator->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00001748 ContinuationBuilder.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00001749 EnumeratorCount++;
1750 }
1751 }
Zachary Turner6900de12017-11-28 18:33:17 +00001752 FTI = TypeTable.insertRecord(ContinuationBuilder);
David Majnemerda9548f2016-06-17 16:13:21 +00001753 }
David Majnemer979cb882016-06-16 21:32:16 +00001754
David Majnemer6bdc24e2016-07-01 23:12:45 +00001755 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001756
Zachary Turner4efa0a42016-11-08 22:24:53 +00001757 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1758 getTypeIndex(Ty->getBaseType()));
Zachary Turner6900de12017-11-28 18:33:17 +00001759 return TypeTable.writeLeafType(ER);
David Majnemer979cb882016-06-16 21:32:16 +00001760}
1761
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001762//===----------------------------------------------------------------------===//
1763// ClassInfo
1764//===----------------------------------------------------------------------===//
1765
1766struct llvm::ClassInfo {
1767 struct MemberInfo {
1768 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001769 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001770 };
1771 // [MemberInfo]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001772 using MemberList = std::vector<MemberInfo>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001773
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001774 using MethodsList = TinyPtrVector<const DISubprogram *>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001775 // MethodName -> MethodsList
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001776 using MethodsMap = MapVector<MDString *, MethodsList>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001777
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001778 /// Base classes.
1779 std::vector<const DIDerivedType *> Inheritance;
1780
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001781 /// Direct members.
1782 MemberList Members;
1783 // Direct overloaded methods gathered by name.
1784 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001785
Reid Kleckner9dac4732016-08-31 15:59:30 +00001786 TypeIndex VShapeTI;
1787
Reid Klecknere2e82062017-08-08 20:30:14 +00001788 std::vector<const DIType *> NestedTypes;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001789};
1790
1791void CodeViewDebug::clear() {
1792 assert(CurFn == nullptr);
1793 FileIdMap.clear();
1794 FnDebugInfo.clear();
1795 FileToFilepathMap.clear();
1796 LocalUDTs.clear();
1797 GlobalUDTs.clear();
1798 TypeIndices.clear();
1799 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001800}
1801
1802void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1803 const DIDerivedType *DDTy) {
1804 if (!DDTy->getName().empty()) {
1805 Info.Members.push_back({DDTy, 0});
1806 return;
1807 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001808 // An unnamed member must represent a nested struct or union. Add all the
1809 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001810 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00001811 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001812 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001813 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001814 ClassInfo NestedInfo = collectClassInfo(DCTy);
1815 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001816 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001817 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001818}
1819
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001820ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1821 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001822 // Add elements to structure type.
1823 DINodeArray Elements = Ty->getElements();
1824 for (auto *Element : Elements) {
1825 // We assume that the frontend provides all members in source declaration
1826 // order, which is what MSVC does.
1827 if (!Element)
1828 continue;
1829 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001830 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001831 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001832 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001833 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001834 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1835 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001836 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1837 DDTy->getName() == "__vtbl_ptr_type") {
1838 Info.VShapeTI = getTypeIndex(DDTy);
Reid Klecknere2e82062017-08-08 20:30:14 +00001839 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
1840 Info.NestedTypes.push_back(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001841 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1842 // Ignore friend members. It appears that MSVC emitted info about
1843 // friends in the past, but modern versions do not.
1844 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001845 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
Reid Klecknere2e82062017-08-08 20:30:14 +00001846 Info.NestedTypes.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001847 }
1848 // Skip other unrecognized kinds of elements.
1849 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001850 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001851}
1852
Reid Klecknera8d57402016-06-03 15:58:20 +00001853TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1854 // First, construct the forward decl. Don't look into Ty to compute the
1855 // forward decl options, since it might not be available in all TUs.
1856 TypeRecordKind Kind = getRecordKind(Ty);
1857 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001858 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001859 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001860 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
1861 FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00001862 TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001863 if (!Ty->isForwardDecl())
1864 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001865 return FwdDeclTI;
1866}
1867
1868TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1869 // Construct the field list and complete type record.
1870 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00001871 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001872 TypeIndex FieldTI;
1873 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001874 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001875 bool ContainsNestedClass;
1876 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1877 lowerRecordFieldList(Ty);
1878
1879 if (ContainsNestedClass)
1880 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00001881
David Majnemer6bdc24e2016-07-01 23:12:45 +00001882 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001883
Reid Klecknera8d57402016-06-03 15:58:20 +00001884 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001885
Zachary Turner4efa0a42016-11-08 22:24:53 +00001886 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
1887 SizeInBytes, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00001888 TypeIndex ClassTI = TypeTable.writeLeafType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001889
Saleem Abdulrasool87f03382017-05-03 21:39:01 +00001890 if (const auto *File = Ty->getFile()) {
1891 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
Zachary Turner6900de12017-11-28 18:33:17 +00001892 TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
1893
Saleem Abdulrasool87f03382017-05-03 21:39:01 +00001894 UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine());
Zachary Turner6900de12017-11-28 18:33:17 +00001895 TypeTable.writeLeafType(USLR);
Saleem Abdulrasool87f03382017-05-03 21:39:01 +00001896 }
Hans Wennborg9a519a02016-06-22 21:22:13 +00001897
Zachary Turnera7b04172017-08-28 18:49:04 +00001898 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001899
Hans Wennborg9a519a02016-06-22 21:22:13 +00001900 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001901}
1902
1903TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1904 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001905 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001906 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001907 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00001908 TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00001909 if (!Ty->isForwardDecl())
1910 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001911 return FwdDeclTI;
1912}
1913
1914TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00001915 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001916 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001917 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001918 bool ContainsNestedClass;
1919 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1920 lowerRecordFieldList(Ty);
1921
1922 if (ContainsNestedClass)
1923 CO |= ClassOptions::ContainsNestedClass;
1924
Reid Klecknera8d57402016-06-03 15:58:20 +00001925 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00001926 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001927
Zachary Turner4efa0a42016-11-08 22:24:53 +00001928 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
1929 Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00001930 TypeIndex UnionTI = TypeTable.writeLeafType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001931
Zachary Turner4efa0a42016-11-08 22:24:53 +00001932 StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
Zachary Turner6900de12017-11-28 18:33:17 +00001933 TypeIndex SIRI = TypeTable.writeLeafType(SIR);
1934
Zachary Turner4efa0a42016-11-08 22:24:53 +00001935 UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine());
Zachary Turner6900de12017-11-28 18:33:17 +00001936 TypeTable.writeLeafType(USLR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001937
Zachary Turnera7b04172017-08-28 18:49:04 +00001938 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001939
Hans Wennborg9a519a02016-06-22 21:22:13 +00001940 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001941}
1942
Adrian McCarthy820ca542016-07-06 19:49:51 +00001943std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00001944CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1945 // Manually count members. MSVC appears to count everything that generates a
1946 // field list record. Each individual overload in a method overload group
1947 // contributes to this count, even though the overload group is a single field
1948 // list record.
1949 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001950 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner6900de12017-11-28 18:33:17 +00001951 ContinuationRecordBuilder ContinuationBuilder;
1952 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001953
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001954 // Create base classes.
1955 for (const DIDerivedType *I : Info.Inheritance) {
1956 if (I->getFlags() & DINode::FlagVirtual) {
1957 // Virtual base.
1958 // FIXME: Emit VBPtrOffset when the frontend provides it.
1959 unsigned VBPtrOffset = 0;
1960 // FIXME: Despite the accessor name, the offset is really in bytes.
1961 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00001962 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
1963 ? TypeRecordKind::IndirectVirtualBaseClass
1964 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00001965 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00001966 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001967 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00001968 VBTableIndex);
1969
Zachary Turner6900de12017-11-28 18:33:17 +00001970 ContinuationBuilder.writeMemberType(VBCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001971 } else {
1972 assert(I->getOffsetInBits() % 8 == 0 &&
1973 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00001974 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
1975 getTypeIndex(I->getBaseType()),
1976 I->getOffsetInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00001977 ContinuationBuilder.writeMemberType(BCR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001978 }
1979 }
1980
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001981 // Create members.
1982 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1983 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1984 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00001985 StringRef MemberName = Member->getName();
1986 MemberAccess Access =
1987 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001988
1989 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001990 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00001991 ContinuationBuilder.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001992 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001993 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001994 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001995
Reid Kleckner9dac4732016-08-31 15:59:30 +00001996 // Virtual function pointer member.
1997 if ((Member->getFlags() & DINode::FlagArtificial) &&
1998 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001999 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
Zachary Turner6900de12017-11-28 18:33:17 +00002000 ContinuationBuilder.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002001 MemberCount++;
2002 continue;
2003 }
2004
David Majnemer9319cbc2016-06-30 03:00:20 +00002005 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00002006 uint64_t MemberOffsetInBits =
2007 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002008 if (Member->isBitField()) {
2009 uint64_t StartBitOffset = MemberOffsetInBits;
2010 if (const auto *CI =
2011 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00002012 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002013 }
2014 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002015 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2016 StartBitOffset);
Zachary Turner6900de12017-11-28 18:33:17 +00002017 MemberBaseType = TypeTable.writeLeafType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00002018 }
2019 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002020 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2021 MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002022 ContinuationBuilder.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002023 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002024 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002025
2026 // Create methods
2027 for (auto &MethodItr : Info.Methods) {
2028 StringRef Name = MethodItr.first->getString();
2029
2030 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00002031 for (const DISubprogram *SP : MethodItr.second) {
2032 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2033 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002034
2035 unsigned VFTableOffset = -1;
2036 if (Introduced)
2037 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2038
Zachary Turner7251ede2016-11-02 17:05:19 +00002039 Methods.push_back(OneMethodRecord(
2040 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2041 translateMethodKindFlags(SP, Introduced),
2042 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002043 MemberCount++;
2044 }
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002045 assert(!Methods.empty() && "Empty methods map entry");
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002046 if (Methods.size() == 1)
Zachary Turner6900de12017-11-28 18:33:17 +00002047 ContinuationBuilder.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002048 else {
Zachary Turner6900de12017-11-28 18:33:17 +00002049 // FIXME: Make this use its own ContinuationBuilder so that
2050 // MethodOverloadList can be split correctly.
Zachary Turner4efa0a42016-11-08 22:24:53 +00002051 MethodOverloadListRecord MOLR(Methods);
Zachary Turner6900de12017-11-28 18:33:17 +00002052 TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2053
Zachary Turner4efa0a42016-11-08 22:24:53 +00002054 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00002055 ContinuationBuilder.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002056 }
2057 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002058
2059 // Create nested classes.
Reid Klecknere2e82062017-08-08 20:30:14 +00002060 for (const DIType *Nested : Info.NestedTypes) {
Adrian McCarthy820ca542016-07-06 19:49:51 +00002061 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00002062 ContinuationBuilder.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00002063 MemberCount++;
2064 }
2065
Zachary Turner6900de12017-11-28 18:33:17 +00002066 TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002067 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Reid Klecknere2e82062017-08-08 20:30:14 +00002068 !Info.NestedTypes.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00002069}
2070
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002071TypeIndex CodeViewDebug::getVBPTypeIndex() {
2072 if (!VBPType.getIndex()) {
2073 // Make a 'const int *' type.
2074 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner6900de12017-11-28 18:33:17 +00002075 TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002076
2077 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2078 : PointerKind::Near32;
2079 PointerMode PM = PointerMode::Pointer;
2080 PointerOptions PO = PointerOptions::None;
2081 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
Zachary Turner6900de12017-11-28 18:33:17 +00002082 VBPType = TypeTable.writeLeafType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002083 }
2084
2085 return VBPType;
2086}
2087
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002088TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002089 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002090 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002091
2092 // The null DIType is the void type. Don't try to hash it.
2093 if (!Ty)
2094 return TypeIndex::Void();
2095
Reid Klecknera8d57402016-06-03 15:58:20 +00002096 // Check if we've already translated this type. Don't try to do a
2097 // get-or-create style insertion that caches the hash lookup across the
2098 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002099 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002100 if (I != TypeIndices.end())
2101 return I->second;
2102
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002103 TypeLoweringScope S(*this);
2104 TypeIndex TI = lowerType(Ty, ClassTy);
2105 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002106}
2107
Bob Haarman223303c2017-08-29 20:59:25 +00002108TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
2109 DIType *Ty = TypeRef.resolve();
2110 PointerRecord PR(getTypeIndex(Ty),
2111 getPointerSizeInBytes() == 8 ? PointerKind::Near64
2112 : PointerKind::Near32,
2113 PointerMode::LValueReference, PointerOptions::None,
2114 Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002115 return TypeTable.writeLeafType(PR);
Bob Haarman223303c2017-08-29 20:59:25 +00002116}
2117
Reid Klecknera8d57402016-06-03 15:58:20 +00002118TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
2119 const DIType *Ty = TypeRef.resolve();
2120
2121 // The null DIType is the void type. Don't try to hash it.
2122 if (!Ty)
2123 return TypeIndex::Void();
2124
2125 // If this is a non-record type, the complete type index is the same as the
2126 // normal type index. Just call getTypeIndex.
2127 switch (Ty->getTag()) {
2128 case dwarf::DW_TAG_class_type:
2129 case dwarf::DW_TAG_structure_type:
2130 case dwarf::DW_TAG_union_type:
2131 break;
2132 default:
2133 return getTypeIndex(Ty);
2134 }
2135
2136 // Check if we've already translated the complete record type. Lowering a
2137 // complete type should never trigger lowering another complete type, so we
2138 // can reuse the hash table lookup result.
2139 const auto *CTy = cast<DICompositeType>(Ty);
2140 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2141 if (!InsertResult.second)
2142 return InsertResult.first->second;
2143
Reid Kleckner643dd832016-06-22 17:15:28 +00002144 TypeLoweringScope S(*this);
2145
Reid Klecknera8d57402016-06-03 15:58:20 +00002146 // Make sure the forward declaration is emitted first. It's unclear if this
2147 // is necessary, but MSVC does it, and we should follow suit until we can show
2148 // otherwise.
2149 TypeIndex FwdDeclTI = getTypeIndex(CTy);
2150
2151 // Just use the forward decl if we don't have complete type info. This might
2152 // happen if the frontend is using modules and expects the complete definition
2153 // to be emitted elsewhere.
2154 if (CTy->isForwardDecl())
2155 return FwdDeclTI;
2156
2157 TypeIndex TI;
2158 switch (CTy->getTag()) {
2159 case dwarf::DW_TAG_class_type:
2160 case dwarf::DW_TAG_structure_type:
2161 TI = lowerCompleteTypeClass(CTy);
2162 break;
2163 case dwarf::DW_TAG_union_type:
2164 TI = lowerCompleteTypeUnion(CTy);
2165 break;
2166 default:
2167 llvm_unreachable("not a record");
2168 }
2169
2170 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002171 return TI;
2172}
2173
Reid Kleckner643dd832016-06-22 17:15:28 +00002174/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00002175/// and do this until fixpoint, as each complete record type typically
2176/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00002177/// many other record types.
2178void CodeViewDebug::emitDeferredCompleteTypes() {
2179 SmallVector<const DICompositeType *, 4> TypesToEmit;
2180 while (!DeferredCompleteTypes.empty()) {
2181 std::swap(DeferredCompleteTypes, TypesToEmit);
2182 for (const DICompositeType *RecordTy : TypesToEmit)
2183 getCompleteTypeIndex(RecordTy);
2184 TypesToEmit.clear();
2185 }
2186}
2187
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002188void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
2189 // Get the sorted list of parameters and emit them first.
2190 SmallVector<const LocalVariable *, 6> Params;
2191 for (const LocalVariable &L : Locals)
2192 if (L.DIVar->isParameter())
2193 Params.push_back(&L);
2194 std::sort(Params.begin(), Params.end(),
2195 [](const LocalVariable *L, const LocalVariable *R) {
2196 return L->DIVar->getArg() < R->DIVar->getArg();
2197 });
2198 for (const LocalVariable *L : Params)
2199 emitLocalVariable(*L);
2200
2201 // Next emit all non-parameters in the order that we found them.
2202 for (const LocalVariable &L : Locals)
2203 if (!L.DIVar->isParameter())
2204 emitLocalVariable(L);
2205}
2206
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002207void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2208 // LocalSym record, see SymbolRecord.h for more info.
2209 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2210 *LocalEnd = MMI->getContext().createTempSymbol();
2211 OS.AddComment("Record length");
2212 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2213 OS.EmitLabel(LocalBegin);
2214
2215 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00002216 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002217
Zachary Turner63a28462016-05-17 23:50:21 +00002218 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002219 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002220 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002221 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002222 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002223
2224 OS.AddComment("TypeIndex");
Reid Kleckner08f5fd52017-08-31 15:56:49 +00002225 TypeIndex TI = Var.UseReferenceType
2226 ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2227 : getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002228 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002229 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002230 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002231 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002232 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002233 OS.EmitLabel(LocalEnd);
2234
Reid Kleckner876330d2016-02-12 21:48:30 +00002235 // Calculate the on disk prefix of the appropriate def range record. The
2236 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2237 // should be big enough to hold all forms without memory allocation.
2238 SmallString<20> BytePrefix;
2239 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2240 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002241 if (DefRange.InMemory) {
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002242 uint16_t RegRelFlags = 0;
2243 if (DefRange.IsSubfield) {
2244 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2245 (DefRange.StructOffset
2246 << DefRangeRegisterRelSym::OffsetInParentShift);
2247 }
Zachary Turner46225b12016-12-16 22:48:14 +00002248 DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
2249 Sym.Hdr.Register = DefRange.CVRegister;
2250 Sym.Hdr.Flags = RegRelFlags;
2251 Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
Reid Kleckner876330d2016-02-12 21:48:30 +00002252 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00002253 BytePrefix +=
2254 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00002255 BytePrefix +=
Zachary Turner46225b12016-12-16 22:48:14 +00002256 StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
Reid Kleckner876330d2016-02-12 21:48:30 +00002257 } else {
2258 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002259 if (DefRange.IsSubfield) {
2260 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002261 DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2262 Sym.Hdr.Register = DefRange.CVRegister;
2263 Sym.Hdr.MayHaveNoName = 0;
2264 Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2265
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002266 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2267 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2268 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002269 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2270 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002271 } else {
2272 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002273 DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2274 Sym.Hdr.Register = DefRange.CVRegister;
2275 Sym.Hdr.MayHaveNoName = 0;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002276 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2277 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2278 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002279 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2280 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002281 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002282 }
2283 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2284 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002285}
2286
David Blaikieb2fbb4b2017-02-16 18:48:33 +00002287void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002288 const Function &GV = MF->getFunction();
2289 assert(FnDebugInfo.count(&GV));
2290 assert(CurFn == &FnDebugInfo[&GV]);
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002291
Matthias Braunf1caa282017-12-15 22:22:58 +00002292 collectVariableInfo(GV.getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002293
Reid Kleckner2214ed82016-01-29 00:49:42 +00002294 // Don't emit anything if we don't have any line tables.
2295 if (!CurFn->HaveLineInfo) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002296 FnDebugInfo.erase(&GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002297 CurFn = nullptr;
2298 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002299 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002300
Reid Klecknere33c94f2017-09-05 20:14:58 +00002301 CurFn->Annotations = MF->getCodeViewAnnotations();
2302
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002303 CurFn->End = Asm->getFunctionEnd();
2304
Craig Topper353eda42014-04-24 06:44:33 +00002305 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002306}
2307
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002308void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002309 DebugHandlerBase::beginInstruction(MI);
2310
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002311 // Ignore DBG_VALUE locations and function prologue.
David Majnemer67f684e2016-07-28 05:03:22 +00002312 if (!Asm || !CurFn || MI->isDebugValue() ||
2313 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002314 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002315
2316 // If the first instruction of a new MBB has no location, find the first
2317 // instruction with a location and use that.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002318 DebugLoc DL = MI->getDebugLoc();
Reid Kleckner45a74622017-06-30 21:33:44 +00002319 if (!DL && MI->getParent() != PrevInstBB) {
2320 for (const auto &NextMI : *MI->getParent()) {
Reid Kleckner2de471d2017-07-31 21:03:08 +00002321 if (NextMI.isDebugValue())
2322 continue;
Reid Kleckner45a74622017-06-30 21:33:44 +00002323 DL = NextMI.getDebugLoc();
2324 if (DL)
2325 break;
2326 }
2327 }
2328 PrevInstBB = MI->getParent();
2329
2330 // If we still don't have a debug location, don't record a location.
2331 if (!DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002332 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002333
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002334 maybeRecordLocation(DL, Asm->MF);
2335}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002336
Zachary Turner8c099fe2017-05-30 16:36:15 +00002337MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002338 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2339 *EndLabel = MMI->getContext().createTempSymbol();
2340 OS.EmitIntValue(unsigned(Kind), 4);
2341 OS.AddComment("Subsection size");
2342 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2343 OS.EmitLabel(BeginLabel);
2344 return EndLabel;
2345}
2346
2347void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2348 OS.EmitLabel(EndLabel);
2349 // Every subsection must be aligned to a 4-byte boundary.
2350 OS.EmitValueToAlignment(4);
2351}
2352
David Majnemer3128b102016-06-15 18:00:01 +00002353void CodeViewDebug::emitDebugInfoForUDTs(
Zachary Turnera7b04172017-08-28 18:49:04 +00002354 ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2355 for (const auto &UDT : UDTs) {
2356 const DIType *T = UDT.second;
2357 assert(shouldEmitUdt(T));
2358
David Majnemer3128b102016-06-15 18:00:01 +00002359 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2360 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2361 OS.AddComment("Record length");
2362 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2363 OS.EmitLabel(UDTRecordBegin);
2364
2365 OS.AddComment("Record kind: S_UDT");
2366 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2367
2368 OS.AddComment("Type");
Zachary Turnera7b04172017-08-28 18:49:04 +00002369 OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
David Majnemer3128b102016-06-15 18:00:01 +00002370
2371 emitNullTerminatedSymbolName(OS, UDT.first);
2372 OS.EmitLabel(UDTRecordEnd);
2373 }
2374}
2375
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002376void CodeViewDebug::emitDebugInfoForGlobals() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002377 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2378 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002379 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002380 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2381 GV.getDebugInfo(GVEs);
2382 for (const auto *GVE : GVEs)
2383 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002384 }
2385
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002386 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2387 for (const MDNode *Node : CUs->operands()) {
2388 const auto *CU = cast<DICompileUnit>(Node);
2389
2390 // First, emit all globals that are not in a comdat in a single symbol
2391 // substream. MSVC doesn't like it if the substream is empty, so only open
2392 // it if we have at least one global to emit.
2393 switchToDebugSectionForSymbol(nullptr);
2394 MCSymbol *EndLabel = nullptr;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002395 for (const auto *GVE : CU->getGlobalVariables()) {
2396 if (const auto *GV = GlobalMap.lookup(GVE))
David Majnemer577be0f2016-06-15 00:19:52 +00002397 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002398 if (!EndLabel) {
2399 OS.AddComment("Symbol subsection for globals");
Zachary Turner8c099fe2017-05-30 16:36:15 +00002400 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002401 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002402 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2403 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002404 }
2405 }
2406 if (EndLabel)
2407 endCVSubsection(EndLabel);
2408
2409 // Second, emit each global that is in a comdat into its own .debug$S
2410 // section along with its own symbol substream.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002411 for (const auto *GVE : CU->getGlobalVariables()) {
2412 if (const auto *GV = GlobalMap.lookup(GVE)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002413 if (GV->hasComdat()) {
2414 MCSymbol *GVSym = Asm->getSymbol(GV);
2415 OS.AddComment("Symbol subsection for " +
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00002416 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002417 switchToDebugSectionForSymbol(GVSym);
Zachary Turner8c099fe2017-05-30 16:36:15 +00002418 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002419 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2420 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002421 endCVSubsection(EndLabel);
2422 }
2423 }
2424 }
2425 }
2426}
2427
Hans Wennborgb510b452016-06-23 16:33:53 +00002428void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2429 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2430 for (const MDNode *Node : CUs->operands()) {
2431 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2432 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2433 getTypeIndex(RT);
2434 // FIXME: Add to global/local DTU list.
2435 }
2436 }
2437 }
2438}
2439
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002440void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002441 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002442 MCSymbol *GVSym) {
2443 // DataSym record, see SymbolRecord.h for more info.
2444 // FIXME: Thread local data, etc
2445 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2446 *DataEnd = MMI->getContext().createTempSymbol();
2447 OS.AddComment("Record length");
2448 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2449 OS.EmitLabel(DataBegin);
David Majnemer7abd2692016-07-06 21:07:47 +00002450 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002451 if (GV->isThreadLocal()) {
2452 OS.AddComment("Record kind: S_LTHREAD32");
2453 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2454 } else {
2455 OS.AddComment("Record kind: S_LDATA32");
2456 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2457 }
David Majnemer7abd2692016-07-06 21:07:47 +00002458 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002459 if (GV->isThreadLocal()) {
2460 OS.AddComment("Record kind: S_GTHREAD32");
2461 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2462 } else {
2463 OS.AddComment("Record kind: S_GDATA32");
2464 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2465 }
David Majnemer7abd2692016-07-06 21:07:47 +00002466 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002467 OS.AddComment("Type");
2468 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2469 OS.AddComment("DataOffset");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00002470 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002471 OS.AddComment("Segment");
2472 OS.EmitCOFFSectionIndex(GVSym);
2473 OS.AddComment("Name");
2474 emitNullTerminatedSymbolName(OS, DIGV->getName());
2475 OS.EmitLabel(DataEnd);
2476}