blob: bb959e26a8e2d7410cb0e86bc595f1ad6e1d5050 [file] [log] [blame]
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001//===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- C++ -*--===//
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"
Reid Kleckner156a7232016-06-22 18:31:14 +000015#include "llvm/ADT/TinyPtrVector.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000016#include "llvm/DebugInfo/CodeView/ByteStream.h"
17#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000018#include "llvm/DebugInfo/CodeView/CodeView.h"
Reid Klecknera8d57402016-06-03 15:58:20 +000019#include "llvm/DebugInfo/CodeView/FieldListRecordBuilder.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000020#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000021#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000022#include "llvm/DebugInfo/CodeView/TypeDumper.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000023#include "llvm/DebugInfo/CodeView/TypeIndex.h"
24#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000025#include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000026#include "llvm/IR/Constants.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000027#include "llvm/MC/MCExpr.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000028#include "llvm/MC/MCSectionCOFF.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000029#include "llvm/MC/MCSymbol.h"
30#include "llvm/Support/COFF.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000031#include "llvm/Support/ScopedPrinter.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000032#include "llvm/Target/TargetFrameLowering.h"
Amjad Aboud76c9eb92016-06-18 10:25:07 +000033#include "llvm/Target/TargetRegisterInfo.h"
34#include "llvm/Target/TargetSubtargetInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000035
Reid Klecknerf9c275f2016-02-10 20:55:49 +000036using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000037using namespace llvm::codeview;
38
Reid Klecknerf9c275f2016-02-10 20:55:49 +000039CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
40 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
41 // If module doesn't have named metadata anchors or COFF debug section
42 // is not available, skip any debug info related stuff.
43 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
44 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
45 Asm = nullptr;
46 return;
47 }
48
49 // Tell MMI that we have debug info.
50 MMI->setDebugInfoAvailability(true);
51}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000052
Reid Kleckner9533af42016-01-16 00:09:09 +000053StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
54 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000055 if (!Filepath.empty())
56 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000057
Reid Kleckner9533af42016-01-16 00:09:09 +000058 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
59
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000060 // Clang emits directory and relative filename info into the IR, but CodeView
61 // operates on full paths. We could change Clang to emit full paths too, but
62 // that would increase the IR size and probably not needed for other users.
63 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000064 if (Filename.find(':') == 1)
65 Filepath = Filename;
66 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +000067 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000068
69 // Canonicalize the path. We have to do it textually because we may no longer
70 // have access the file in the filesystem.
71 // First, replace all slashes with backslashes.
72 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
73
74 // Remove all "\.\" with "\".
75 size_t Cursor = 0;
76 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
77 Filepath.erase(Cursor, 2);
78
79 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
80 // path should be well-formatted, e.g. start with a drive letter, etc.
81 Cursor = 0;
82 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
83 // Something's wrong if the path starts with "\..\", abort.
84 if (Cursor == 0)
85 break;
86
87 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
88 if (PrevSlash == std::string::npos)
89 // Something's wrong, abort.
90 break;
91
92 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
93 // The next ".." might be following the one we've just erased.
94 Cursor = PrevSlash;
95 }
96
97 // Remove all duplicate backslashes.
98 Cursor = 0;
99 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
100 Filepath.erase(Cursor, 1);
101
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000102 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000103}
104
Reid Kleckner2214ed82016-01-29 00:49:42 +0000105unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
106 unsigned NextId = FileIdMap.size() + 1;
107 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
108 if (Insertion.second) {
109 // We have to compute the full filepath and emit a .cv_file directive.
110 StringRef FullPath = getFullFilepath(F);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000111 NextId = OS.EmitCVFileDirective(NextId, FullPath);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000112 assert(NextId == FileIdMap.size() && ".cv_file directive failed");
113 }
114 return Insertion.first->second;
115}
116
Reid Kleckner876330d2016-02-12 21:48:30 +0000117CodeViewDebug::InlineSite &
118CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
119 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000120 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
121 InlineSite *Site = &SiteInsertion.first->second;
122 if (SiteInsertion.second) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000123 Site->SiteFuncId = NextFuncId++;
Reid Kleckner876330d2016-02-12 21:48:30 +0000124 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000125 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000126 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000127 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000128 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000129}
130
David Majnemer6bdc24e2016-07-01 23:12:45 +0000131static StringRef getPrettyScopeName(const DIScope *Scope) {
132 StringRef ScopeName = Scope->getName();
133 if (!ScopeName.empty())
134 return ScopeName;
135
136 switch (Scope->getTag()) {
137 case dwarf::DW_TAG_enumeration_type:
138 case dwarf::DW_TAG_class_type:
139 case dwarf::DW_TAG_structure_type:
140 case dwarf::DW_TAG_union_type:
141 return "<unnamed-tag>";
142 case dwarf::DW_TAG_namespace:
143 return "`anonymous namespace'";
144 }
145
146 return StringRef();
147}
148
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000149static const DISubprogram *getQualifiedNameComponents(
150 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
151 const DISubprogram *ClosestSubprogram = nullptr;
152 while (Scope != nullptr) {
153 if (ClosestSubprogram == nullptr)
154 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000155 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000156 if (!ScopeName.empty())
157 QualifiedNameComponents.push_back(ScopeName);
158 Scope = Scope->getScope().resolve();
159 }
160 return ClosestSubprogram;
161}
162
163static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
164 StringRef TypeName) {
165 std::string FullyQualifiedName;
166 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
167 FullyQualifiedName.append(QualifiedNameComponent);
168 FullyQualifiedName.append("::");
169 }
170 FullyQualifiedName.append(TypeName);
171 return FullyQualifiedName;
172}
173
174static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
175 SmallVector<StringRef, 5> QualifiedNameComponents;
176 getQualifiedNameComponents(Scope, QualifiedNameComponents);
177 return getQualifiedName(QualifiedNameComponents, Name);
178}
179
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000180struct CodeViewDebug::TypeLoweringScope {
181 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
182 ~TypeLoweringScope() {
183 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
184 // inner TypeLoweringScopes don't attempt to emit deferred types.
185 if (CVD.TypeEmissionLevel == 1)
186 CVD.emitDeferredCompleteTypes();
187 --CVD.TypeEmissionLevel;
188 }
189 CodeViewDebug &CVD;
190};
191
David Majnemer6bdc24e2016-07-01 23:12:45 +0000192static std::string getFullyQualifiedName(const DIScope *Ty) {
193 const DIScope *Scope = Ty->getScope().resolve();
194 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
195}
196
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000197TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
198 // No scope means global scope and that uses the zero index.
199 if (!Scope || isa<DIFile>(Scope))
200 return TypeIndex();
201
202 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
203
204 // Check if we've already translated this scope.
205 auto I = TypeIndices.find({Scope, nullptr});
206 if (I != TypeIndices.end())
207 return I->second;
208
209 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000210 std::string ScopeName = getFullyQualifiedName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000211 TypeIndex TI =
212 TypeTable.writeStringId(StringIdRecord(TypeIndex(), ScopeName));
213 return recordTypeIndexForDINode(Scope, TI);
214}
215
David Majnemer75c3ebf2016-06-02 17:13:53 +0000216TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
217 // It's possible to ask for the FuncId of a function which doesn't have a
218 // subprogram: inlining a function with debug info into a function with none.
219 if (!SP)
David Majnemerb68f32f02016-06-02 18:51:24 +0000220 return TypeIndex::None();
Reid Kleckner2280f932016-05-23 20:23:46 +0000221
David Majnemer75c3ebf2016-06-02 17:13:53 +0000222 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000223 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000224 if (I != TypeIndices.end())
225 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000226
Reid Klecknerac945e22016-06-17 16:11:20 +0000227 // The display name includes function template arguments. Drop them to match
228 // MSVC.
229 StringRef DisplayName = SP->getDisplayName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000230
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000231 const DIScope *Scope = SP->getScope().resolve();
232 TypeIndex TI;
233 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
234 // If the scope is a DICompositeType, then this must be a method. Member
235 // function types take some special handling, and require access to the
236 // subprogram.
237 TypeIndex ClassType = getTypeIndex(Class);
238 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
239 DisplayName);
240 TI = TypeTable.writeMemberFuncId(MFuncId);
241 } else {
242 // Otherwise, this must be a free function.
243 TypeIndex ParentScope = getScopeIndex(Scope);
244 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
245 TI = TypeTable.writeFuncId(FuncId);
246 }
247
248 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000249}
250
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000251TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
252 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000253 // Always use the method declaration as the key for the function type. The
254 // method declaration contains the this adjustment.
255 if (SP->getDeclaration())
256 SP = SP->getDeclaration();
257 assert(!SP->getDeclaration() && "should use declaration as key");
258
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000259 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
260 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000261 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000262 if (I != TypeIndices.end())
263 return I->second;
264
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000265 // Make sure complete type info for the class is emitted *after* the member
266 // function type, as the complete class type is likely to reference this
267 // member function type.
268 TypeLoweringScope S(*this);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000269 TypeIndex TI =
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000270 lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000271 return recordTypeIndexForDINode(SP, TI, Class);
272}
273
274TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, TypeIndex TI,
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000275 const DIType *ClassTy) {
276 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000277 (void)InsertResult;
278 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000279 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000280}
281
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000282unsigned CodeViewDebug::getPointerSizeInBytes() {
283 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
284}
285
Reid Kleckner876330d2016-02-12 21:48:30 +0000286void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
287 const DILocation *InlinedAt) {
288 if (InlinedAt) {
289 // This variable was inlined. Associate it with the InlineSite.
290 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
291 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
292 Site.InlinedLocals.emplace_back(Var);
293 } else {
294 // This variable goes in the main ProcSym.
295 CurFn->Locals.emplace_back(Var);
296 }
297}
298
Reid Kleckner829365a2016-02-11 19:41:47 +0000299static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
300 const DILocation *Loc) {
301 auto B = Locs.begin(), E = Locs.end();
302 if (std::find(B, E, Loc) == E)
303 Locs.push_back(Loc);
304}
305
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000306void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000307 const MachineFunction *MF) {
308 // Skip this instruction if it has the same location as the previous one.
309 if (DL == CurFn->LastLoc)
310 return;
311
312 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000313 if (!Scope)
314 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000315
David Majnemerc3340db2016-01-13 01:05:23 +0000316 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000317 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
318 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
319 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000320 return;
321
Reid Kleckner2214ed82016-01-29 00:49:42 +0000322 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
323 if (CI.getStartColumn() != DL.getCol())
324 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000325
Reid Kleckner2214ed82016-01-29 00:49:42 +0000326 if (!CurFn->HaveLineInfo)
327 CurFn->HaveLineInfo = true;
328 unsigned FileId = 0;
329 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
330 FileId = CurFn->LastFileId;
331 else
332 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
333 CurFn->LastLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000334
335 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000336 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000337 const DILocation *Loc = DL.get();
338
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000339 // If this location was actually inlined from somewhere else, give it the ID
340 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000341 FuncId =
342 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000343
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000344 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000345 bool FirstLoc = true;
346 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000347 InlineSite &Site =
348 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000349 if (!FirstLoc)
350 addLocIfNotPresent(Site.ChildSites, Loc);
351 FirstLoc = false;
352 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000353 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000354 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000355 }
356
Reid Klecknerdac21b42016-02-03 21:15:48 +0000357 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
358 /*PrologueEnd=*/false,
359 /*IsStmt=*/false, DL->getFilename());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000360}
361
Reid Kleckner5d122f82016-05-25 23:16:12 +0000362void CodeViewDebug::emitCodeViewMagicVersion() {
363 OS.EmitValueToAlignment(4);
364 OS.AddComment("Debug section magic");
365 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
366}
367
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000368void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000369 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000370 return;
371
372 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000373
374 // The COFF .debug$S section consists of several subsections, each starting
375 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
376 // of the payload followed by the payload itself. The subsections are 4-byte
377 // aligned.
378
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000379 // Use the generic .debug$S section, and make a subsection for all the inlined
380 // subprograms.
381 switchToDebugSectionForSymbol(nullptr);
Reid Kleckner5d122f82016-05-25 23:16:12 +0000382 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000383
Reid Kleckner2214ed82016-01-29 00:49:42 +0000384 // Emit per-function debug information.
385 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000386 if (!P.first->isDeclarationForLinker())
387 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000388
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000389 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000390 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000391 emitDebugInfoForGlobals();
392
Hans Wennborgb510b452016-06-23 16:33:53 +0000393 // Emit retained types.
394 emitDebugInfoForRetainedTypes();
395
Reid Kleckner5d122f82016-05-25 23:16:12 +0000396 // Switch back to the generic .debug$S section after potentially processing
397 // comdat symbol sections.
398 switchToDebugSectionForSymbol(nullptr);
399
David Majnemer3128b102016-06-15 18:00:01 +0000400 // Emit UDT records for any types used by global variables.
401 if (!GlobalUDTs.empty()) {
402 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
403 emitDebugInfoForUDTs(GlobalUDTs);
404 endCVSubsection(SymbolsEnd);
405 }
406
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000407 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000408 OS.AddComment("File index to string table offset subsection");
409 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000410
411 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000412 OS.AddComment("String table");
413 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000414
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000415 // Emit type information last, so that any types we translate while emitting
416 // function info are included.
417 emitTypeInformation();
418
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000419 clear();
420}
421
David Majnemerb9456a52016-03-14 05:15:09 +0000422static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
423 // Microsoft's linker seems to have trouble with symbol names longer than
424 // 0xffd8 bytes.
425 S = S.substr(0, 0xffd8);
426 SmallString<32> NullTerminatedString(S);
427 NullTerminatedString.push_back('\0');
428 OS.EmitBytes(NullTerminatedString);
429}
430
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000431void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000432 // Do nothing if we have no debug info or if no non-trivial types were emitted
433 // to TypeTable during codegen.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000434 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
Reid Klecknerfbd77872016-03-18 18:54:32 +0000435 if (!CU_Nodes)
436 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000437 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000438 return;
439
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000440 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000441 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000442 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000443
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000444 SmallString<8> CommentPrefix;
445 if (OS.isVerboseAsm()) {
446 CommentPrefix += '\t';
447 CommentPrefix += Asm->MAI->getCommentString();
448 CommentPrefix += ' ';
449 }
450
451 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
Reid Kleckner2280f932016-05-23 20:23:46 +0000452 TypeTable.ForEachRecord(
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000453 [&](TypeIndex Index, StringRef Record) {
454 if (OS.isVerboseAsm()) {
455 // Emit a block comment describing the type record for readability.
456 SmallString<512> CommentBlock;
457 raw_svector_ostream CommentOS(CommentBlock);
458 ScopedPrinter SP(CommentOS);
459 SP.setPrefix(CommentPrefix);
460 CVTD.setPrinter(&SP);
Reid Klecknerc92e9462016-07-01 18:05:56 +0000461 Error E = CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
462 if (E) {
463 logAllUnhandledErrors(std::move(E), errs(), "error: ");
464 llvm_unreachable("produced malformed type record");
465 }
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000466 // emitRawComment will insert its own tab and comment string before
467 // the first line, so strip off our first one. It also prints its own
468 // newline.
469 OS.emitRawComment(
470 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Reid Klecknerc92e9462016-07-01 18:05:56 +0000471 } else {
472#ifndef NDEBUG
473 // Assert that the type data is valid even if we aren't dumping
474 // comments. The MSVC linker doesn't do much type record validation,
475 // so the first link of an invalid type record can succeed while
476 // subsequent links will fail with LNK1285.
477 ByteStream<> Stream({Record.bytes_begin(), Record.bytes_end()});
478 CVTypeArray Types;
479 StreamReader Reader(Stream);
480 Error E = Reader.readArray(Types, Reader.getLength());
481 if (!E) {
482 TypeVisitorCallbacks C;
483 E = CVTypeVisitor(C).visitTypeStream(Types);
484 }
485 if (E) {
486 logAllUnhandledErrors(std::move(E), errs(), "error: ");
487 llvm_unreachable("produced malformed type record");
488 }
489#endif
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000490 }
491 OS.EmitBinaryData(Record);
Reid Kleckner2280f932016-05-23 20:23:46 +0000492 });
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000493}
494
Reid Kleckner5d122f82016-05-25 23:16:12 +0000495void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000496 if (InlinedSubprograms.empty())
497 return;
498
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000499 OS.AddComment("Inlinee lines subsection");
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000500 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000501
502 // We don't provide any extra file info.
503 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000504 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000505 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
506
507 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000508 assert(TypeIndices.count({SP, nullptr}));
509 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000510
David Majnemer30579ec2016-02-02 23:18:23 +0000511 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000512 unsigned FileId = maybeRecordFile(SP->getFile());
513 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
514 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000515 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000516 // The filechecksum table uses 8 byte entries for now, and file ids start at
517 // 1.
518 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000519 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000520 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000521 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000522 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000523 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000524 OS.EmitIntValue(SP->getLine(), 4);
525 }
526
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000527 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000528}
529
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000530void CodeViewDebug::collectInlineSiteChildren(
531 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
532 const InlineSite &Site) {
533 for (const DILocation *ChildSiteLoc : Site.ChildSites) {
534 auto I = FI.InlineSites.find(ChildSiteLoc);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000535 const InlineSite &ChildSite = I->second;
536 Children.push_back(ChildSite.SiteFuncId);
537 collectInlineSiteChildren(Children, FI, ChildSite);
538 }
539}
540
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000541void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
542 const DILocation *InlinedAt,
543 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000544 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
545 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000546
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000547 assert(TypeIndices.count({Site.Inlinee, nullptr}));
548 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000549
550 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000551 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000552 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000553 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000554 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000555 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000556
Reid Klecknerdac21b42016-02-03 21:15:48 +0000557 OS.AddComment("PtrParent");
558 OS.EmitIntValue(0, 4);
559 OS.AddComment("PtrEnd");
560 OS.EmitIntValue(0, 4);
561 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000562 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000563
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000564 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
565 unsigned StartLineNum = Site.Inlinee->getLine();
566 SmallVector<unsigned, 3> SecondaryFuncIds;
567 collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
568
569 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
David Majnemerc9911f22016-02-02 19:22:34 +0000570 FI.Begin, FI.End, SecondaryFuncIds);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000571
572 OS.EmitLabel(InlineEnd);
573
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000574 emitLocalVariableList(Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000575
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000576 // Recurse on child inlined call sites before closing the scope.
577 for (const DILocation *ChildSite : Site.ChildSites) {
578 auto I = FI.InlineSites.find(ChildSite);
579 assert(I != FI.InlineSites.end() &&
580 "child site not in function inline site map");
581 emitInlinedCallSite(FI, ChildSite, I->second);
582 }
583
584 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000585 OS.AddComment("Record length");
586 OS.EmitIntValue(2, 2); // RecordLength
587 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000588 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000589}
590
Reid Kleckner5d122f82016-05-25 23:16:12 +0000591void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
592 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
593 // comdat key. A section may be comdat because of -ffunction-sections or
594 // because it is comdat in the IR.
595 MCSectionCOFF *GVSec =
596 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
597 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
598
599 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
600 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
601 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
602
603 OS.SwitchSection(DebugSec);
604
605 // Emit the magic version number if this is the first time we've switched to
606 // this section.
607 if (ComdatDebugSections.insert(DebugSec).second)
608 emitCodeViewMagicVersion();
609}
610
Reid Kleckner2214ed82016-01-29 00:49:42 +0000611void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
612 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000613 // For each function there is a separate subsection
614 // which holds the PC to file:line table.
615 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000616 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000617
Reid Kleckner5d122f82016-05-25 23:16:12 +0000618 // Switch to the to a comdat section, if appropriate.
619 switchToDebugSectionForSymbol(Fn);
620
Reid Klecknerac945e22016-06-17 16:11:20 +0000621 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000622 auto *SP = GV->getSubprogram();
623 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000624
625 // If we have a display name, build the fully qualified name by walking the
626 // chain of scopes.
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000627 if (SP != nullptr && !SP->getDisplayName().empty())
628 FuncName =
629 getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000630
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000631 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000632 if (FuncName.empty())
633 FuncName = GlobalValue::getRealLinkageName(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000634
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000635 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000636 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000637 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000638 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000639 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
640 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000641 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000642 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000643 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000644
David Majnemer7abd2692016-07-06 21:07:47 +0000645 if (GV->hasLocalLinkage()) {
646 OS.AddComment("Record kind: S_LPROC32_ID");
647 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
648 } else {
Reid Klecknerdac21b42016-02-03 21:15:48 +0000649 OS.AddComment("Record kind: S_GPROC32_ID");
Zachary Turner63a28462016-05-17 23:50:21 +0000650 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
David Majnemer7abd2692016-07-06 21:07:47 +0000651 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000652
David Majnemer30579ec2016-02-02 23:18:23 +0000653 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000654 OS.AddComment("PtrParent");
655 OS.EmitIntValue(0, 4);
656 OS.AddComment("PtrEnd");
657 OS.EmitIntValue(0, 4);
658 OS.AddComment("PtrNext");
659 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000660 // This is the important bit that tells the debugger where the function
661 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000662 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000663 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000664 OS.AddComment("Offset after prologue");
665 OS.EmitIntValue(0, 4);
666 OS.AddComment("Offset before epilogue");
667 OS.EmitIntValue(0, 4);
668 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000669 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000670 OS.AddComment("Function section relative address");
671 OS.EmitCOFFSecRel32(Fn);
672 OS.AddComment("Function section index");
673 OS.EmitCOFFSectionIndex(Fn);
674 OS.AddComment("Flags");
675 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000676 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000677 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000678 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000679 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000680 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000681
Reid Kleckner10dd55c2016-06-24 17:55:40 +0000682 emitLocalVariableList(FI.Locals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000683
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000684 // Emit inlined call site information. Only emit functions inlined directly
685 // into the parent function. We'll emit the other sites recursively as part
686 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000687 for (const DILocation *InlinedAt : FI.ChildSites) {
688 auto I = FI.InlineSites.find(InlinedAt);
689 assert(I != FI.InlineSites.end() &&
690 "child site not in function inline site map");
691 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000692 }
693
David Majnemer3128b102016-06-15 18:00:01 +0000694 if (SP != nullptr)
695 emitDebugInfoForUDTs(LocalUDTs);
696
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000697 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000698 OS.AddComment("Record length");
699 OS.EmitIntValue(0x0002, 2);
700 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000701 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000702 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000703 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000704
Reid Kleckner2214ed82016-01-29 00:49:42 +0000705 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000706 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000707}
708
Reid Kleckner876330d2016-02-12 21:48:30 +0000709CodeViewDebug::LocalVarDefRange
710CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
711 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000712 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000713 DR.DataOffset = Offset;
714 assert(DR.DataOffset == Offset && "truncation");
715 DR.StructOffset = 0;
716 DR.CVRegister = CVRegister;
717 return DR;
718}
719
720CodeViewDebug::LocalVarDefRange
721CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
722 LocalVarDefRange DR;
723 DR.InMemory = 0;
724 DR.DataOffset = 0;
725 DR.StructOffset = 0;
726 DR.CVRegister = CVRegister;
727 return DR;
728}
729
730void CodeViewDebug::collectVariableInfoFromMMITable(
731 DenseSet<InlinedVariable> &Processed) {
732 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
733 const TargetFrameLowering *TFI = TSI.getFrameLowering();
734 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
735
736 for (const MachineModuleInfo::VariableDbgInfo &VI :
737 MMI->getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000738 if (!VI.Var)
739 continue;
740 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
741 "Expected inlined-at fields to agree");
742
Reid Kleckner876330d2016-02-12 21:48:30 +0000743 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000744 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
745
746 // If variable scope is not found then skip this variable.
747 if (!Scope)
748 continue;
749
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000750 // Get the frame register used and the offset.
751 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000752 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
753 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000754
755 // Calculate the label ranges.
Reid Kleckner876330d2016-02-12 21:48:30 +0000756 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000757 for (const InsnRange &Range : Scope->getRanges()) {
758 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
759 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000760 End = End ? End : Asm->getFunctionEnd();
761 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000762 }
763
Reid Kleckner876330d2016-02-12 21:48:30 +0000764 LocalVariable Var;
765 Var.DIVar = VI.Var;
766 Var.DefRanges.emplace_back(std::move(DefRange));
767 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
768 }
769}
770
771void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
772 DenseSet<InlinedVariable> Processed;
773 // Grab the variable info that was squirreled away in the MMI side-table.
774 collectVariableInfoFromMMITable(Processed);
775
776 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
777
778 for (const auto &I : DbgValues) {
779 InlinedVariable IV = I.first;
780 if (Processed.count(IV))
781 continue;
782 const DILocalVariable *DIVar = IV.first;
783 const DILocation *InlinedAt = IV.second;
784
785 // Instruction ranges, specifying where IV is accessible.
786 const auto &Ranges = I.second;
787
788 LexicalScope *Scope = nullptr;
789 if (InlinedAt)
790 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
791 else
792 Scope = LScopes.findLexicalScope(DIVar->getScope());
793 // If variable scope is not found then skip this variable.
794 if (!Scope)
795 continue;
796
797 LocalVariable Var;
798 Var.DIVar = DIVar;
799
800 // Calculate the definition ranges.
801 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
802 const InsnRange &Range = *I;
803 const MachineInstr *DVInst = Range.first;
804 assert(DVInst->isDebugValue() && "Invalid History entry");
805 const DIExpression *DIExpr = DVInst->getDebugExpression();
806
807 // Bail if there is a complex DWARF expression for now.
808 if (DIExpr && DIExpr->getNumElements() > 0)
809 continue;
810
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000811 // Bail if operand 0 is not a valid register. This means the variable is a
812 // simple constant, or is described by a complex expression.
813 // FIXME: Find a way to represent constant variables, since they are
814 // relatively common.
815 unsigned Reg =
816 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
817 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000818 continue;
819
Reid Kleckner876330d2016-02-12 21:48:30 +0000820 // Handle the two cases we can handle: indirect in memory and in register.
821 bool IsIndirect = DVInst->getOperand(1).isImm();
822 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
823 {
824 LocalVarDefRange DefRange;
825 if (IsIndirect) {
826 int64_t Offset = DVInst->getOperand(1).getImm();
827 DefRange = createDefRangeMem(CVReg, Offset);
828 } else {
829 DefRange = createDefRangeReg(CVReg);
830 }
831 if (Var.DefRanges.empty() ||
832 Var.DefRanges.back().isDifferentLocation(DefRange)) {
833 Var.DefRanges.emplace_back(std::move(DefRange));
834 }
835 }
836
837 // Compute the label range.
838 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
839 const MCSymbol *End = getLabelAfterInsn(Range.second);
840 if (!End) {
841 if (std::next(I) != E)
842 End = getLabelBeforeInsn(std::next(I)->first);
843 else
844 End = Asm->getFunctionEnd();
845 }
846
847 // If the last range end is our begin, just extend the last range.
848 // Otherwise make a new range.
849 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
850 Var.DefRanges.back().Ranges;
851 if (!Ranges.empty() && Ranges.back().second == Begin)
852 Ranges.back().second = End;
853 else
854 Ranges.emplace_back(Begin, End);
855
856 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000857 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000858
859 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000860 }
861}
862
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000863void CodeViewDebug::beginFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000864 assert(!CurFn && "Can't process two functions at once!");
865
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000866 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000867 return;
868
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000869 DebugHandlerBase::beginFunction(MF);
870
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000871 const Function *GV = MF->getFunction();
872 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000873 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +0000874 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000875 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000876
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000877 // Find the end of the function prolog. First known non-DBG_VALUE and
878 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000879 // FIXME: is there a simpler a way to do this? Can we just search
880 // for the first instruction of the function, not the last of the prolog?
881 DebugLoc PrologEndLoc;
882 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000883 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000884 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000885 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
886 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000887 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000888 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000889 } else if (!MI.isDebugValue()) {
890 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000891 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000892 }
893 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000894
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000895 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000896 if (PrologEndLoc && !EmptyPrologue) {
897 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000898 maybeRecordLocation(FnStartDL, MF);
899 }
900}
901
Hans Wennborg4b63a982016-06-23 22:57:25 +0000902void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
Reid Klecknerad56ea32016-07-01 22:24:51 +0000903 // Don't record empty UDTs.
904 if (Ty->getName().empty())
905 return;
906
Hans Wennborg4b63a982016-06-23 22:57:25 +0000907 SmallVector<StringRef, 5> QualifiedNameComponents;
908 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
909 Ty->getScope().resolve(), QualifiedNameComponents);
910
911 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +0000912 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +0000913
914 if (ClosestSubprogram == nullptr)
915 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
916 else if (ClosestSubprogram == CurrentSubprogram)
917 LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
918
919 // TODO: What if the ClosestSubprogram is neither null or the current
920 // subprogram? Currently, the UDT just gets dropped on the floor.
921 //
922 // The current behavior is not desirable. To get maximal fidelity, we would
923 // need to perform all type translation before beginning emission of .debug$S
924 // and then make LocalUDTs a member of FunctionInfo
925}
926
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000927TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000928 // Generic dispatch for lowering an unknown type.
929 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000930 case dwarf::DW_TAG_array_type:
931 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +0000932 case dwarf::DW_TAG_typedef:
933 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000934 case dwarf::DW_TAG_base_type:
935 return lowerTypeBasic(cast<DIBasicType>(Ty));
936 case dwarf::DW_TAG_pointer_type:
937 case dwarf::DW_TAG_reference_type:
938 case dwarf::DW_TAG_rvalue_reference_type:
939 return lowerTypePointer(cast<DIDerivedType>(Ty));
940 case dwarf::DW_TAG_ptr_to_member_type:
941 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
942 case dwarf::DW_TAG_const_type:
943 case dwarf::DW_TAG_volatile_type:
944 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +0000945 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000946 if (ClassTy) {
947 // The member function type of a member function pointer has no
948 // ThisAdjustment.
949 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
950 /*ThisAdjustment=*/0);
951 }
David Majnemer75c3ebf2016-06-02 17:13:53 +0000952 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +0000953 case dwarf::DW_TAG_enumeration_type:
954 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +0000955 case dwarf::DW_TAG_class_type:
956 case dwarf::DW_TAG_structure_type:
957 return lowerTypeClass(cast<DICompositeType>(Ty));
958 case dwarf::DW_TAG_union_type:
959 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000960 default:
961 // Use the null type index.
962 return TypeIndex();
963 }
964}
965
David Majnemerd065e232016-06-02 06:21:37 +0000966TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +0000967 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
968 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +0000969 StringRef TypeName = Ty->getName();
970
Hans Wennborg4b63a982016-06-23 22:57:25 +0000971 addToUDTs(Ty, UnderlyingTypeIndex);
David Majnemer3128b102016-06-15 18:00:01 +0000972
David Majnemerd065e232016-06-02 06:21:37 +0000973 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +0000974 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +0000975 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +0000976 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +0000977 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +0000978 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +0000979
David Majnemerd065e232016-06-02 06:21:37 +0000980 return UnderlyingTypeIndex;
981}
982
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000983TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
984 DITypeRef ElementTypeRef = Ty->getBaseType();
985 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
986 // IndexType is size_t, which depends on the bitness of the target.
987 TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
988 ? TypeIndex(SimpleTypeKind::UInt64Quad)
989 : TypeIndex(SimpleTypeKind::UInt32Long);
Nico Weberd8db1e12016-06-26 15:10:34 +0000990 uint64_t Size = Ty->getSizeInBits() / 8;
991 ArrayRecord Record(ElementTypeIndex, IndexType, Size, Ty->getName());
992 return TypeTable.writeArray(Record);
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000993}
994
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000995TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
996 TypeIndex Index;
997 dwarf::TypeKind Kind;
998 uint32_t ByteSize;
999
1000 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001001 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001002
1003 SimpleTypeKind STK = SimpleTypeKind::None;
1004 switch (Kind) {
1005 case dwarf::DW_ATE_address:
1006 // FIXME: Translate
1007 break;
1008 case dwarf::DW_ATE_boolean:
1009 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001010 case 1: STK = SimpleTypeKind::Boolean8; break;
1011 case 2: STK = SimpleTypeKind::Boolean16; break;
1012 case 4: STK = SimpleTypeKind::Boolean32; break;
1013 case 8: STK = SimpleTypeKind::Boolean64; break;
1014 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001015 }
1016 break;
1017 case dwarf::DW_ATE_complex_float:
1018 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001019 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001020 case 4: STK = SimpleTypeKind::Complex32; break;
1021 case 8: STK = SimpleTypeKind::Complex64; break;
1022 case 10: STK = SimpleTypeKind::Complex80; break;
1023 case 16: STK = SimpleTypeKind::Complex128; break;
1024 }
1025 break;
1026 case dwarf::DW_ATE_float:
1027 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001028 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001029 case 4: STK = SimpleTypeKind::Float32; break;
1030 case 6: STK = SimpleTypeKind::Float48; break;
1031 case 8: STK = SimpleTypeKind::Float64; break;
1032 case 10: STK = SimpleTypeKind::Float80; break;
1033 case 16: STK = SimpleTypeKind::Float128; break;
1034 }
1035 break;
1036 case dwarf::DW_ATE_signed:
1037 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001038 case 1: STK = SimpleTypeKind::SByte; break;
1039 case 2: STK = SimpleTypeKind::Int16Short; break;
1040 case 4: STK = SimpleTypeKind::Int32; break;
1041 case 8: STK = SimpleTypeKind::Int64Quad; break;
1042 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001043 }
1044 break;
1045 case dwarf::DW_ATE_unsigned:
1046 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001047 case 1: STK = SimpleTypeKind::Byte; break;
1048 case 2: STK = SimpleTypeKind::UInt16Short; break;
1049 case 4: STK = SimpleTypeKind::UInt32; break;
1050 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1051 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001052 }
1053 break;
1054 case dwarf::DW_ATE_UTF:
1055 switch (ByteSize) {
1056 case 2: STK = SimpleTypeKind::Character16; break;
1057 case 4: STK = SimpleTypeKind::Character32; break;
1058 }
1059 break;
1060 case dwarf::DW_ATE_signed_char:
1061 if (ByteSize == 1)
1062 STK = SimpleTypeKind::SignedCharacter;
1063 break;
1064 case dwarf::DW_ATE_unsigned_char:
1065 if (ByteSize == 1)
1066 STK = SimpleTypeKind::UnsignedCharacter;
1067 break;
1068 default:
1069 break;
1070 }
1071
1072 // Apply some fixups based on the source-level type name.
1073 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1074 STK = SimpleTypeKind::Int32Long;
1075 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1076 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001077 if (STK == SimpleTypeKind::UInt16Short &&
1078 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001079 STK = SimpleTypeKind::WideCharacter;
1080 if ((STK == SimpleTypeKind::SignedCharacter ||
1081 STK == SimpleTypeKind::UnsignedCharacter) &&
1082 Ty->getName() == "char")
1083 STK = SimpleTypeKind::NarrowCharacter;
1084
1085 return TypeIndex(STK);
1086}
1087
1088TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1089 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1090
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001091 // While processing the type being pointed to it is possible we already
1092 // created this pointer type. If so, we check here and return the existing
1093 // pointer type.
1094 auto I = TypeIndices.find({Ty, nullptr});
1095 if (I != TypeIndices.end())
1096 return I->second;
1097
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001098 // Pointers to simple types can use SimpleTypeMode, rather than having a
1099 // dedicated pointer type record.
1100 if (PointeeTI.isSimple() &&
1101 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1102 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1103 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1104 ? SimpleTypeMode::NearPointer64
1105 : SimpleTypeMode::NearPointer32;
1106 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1107 }
1108
1109 PointerKind PK =
1110 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1111 PointerMode PM = PointerMode::Pointer;
1112 switch (Ty->getTag()) {
1113 default: llvm_unreachable("not a pointer tag type");
1114 case dwarf::DW_TAG_pointer_type:
1115 PM = PointerMode::Pointer;
1116 break;
1117 case dwarf::DW_TAG_reference_type:
1118 PM = PointerMode::LValueReference;
1119 break;
1120 case dwarf::DW_TAG_rvalue_reference_type:
1121 PM = PointerMode::RValueReference;
1122 break;
1123 }
1124 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1125 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1126 // do.
1127 PointerOptions PO = PointerOptions::None;
1128 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1129 return TypeTable.writePointer(PR);
1130}
1131
Reid Kleckner6fa15462016-06-17 22:14:39 +00001132static PointerToMemberRepresentation
1133translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1134 // SizeInBytes being zero generally implies that the member pointer type was
1135 // incomplete, which can happen if it is part of a function prototype. In this
1136 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001137 if (IsPMF) {
1138 switch (Flags & DINode::FlagPtrToMemberRep) {
1139 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001140 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1141 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001142 case DINode::FlagSingleInheritance:
1143 return PointerToMemberRepresentation::SingleInheritanceFunction;
1144 case DINode::FlagMultipleInheritance:
1145 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1146 case DINode::FlagVirtualInheritance:
1147 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1148 }
1149 } else {
1150 switch (Flags & DINode::FlagPtrToMemberRep) {
1151 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001152 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1153 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001154 case DINode::FlagSingleInheritance:
1155 return PointerToMemberRepresentation::SingleInheritanceData;
1156 case DINode::FlagMultipleInheritance:
1157 return PointerToMemberRepresentation::MultipleInheritanceData;
1158 case DINode::FlagVirtualInheritance:
1159 return PointerToMemberRepresentation::VirtualInheritanceData;
1160 }
1161 }
1162 llvm_unreachable("invalid ptr to member representation");
1163}
1164
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001165TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1166 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1167 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001168 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001169 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
1170 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001171 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1172 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1173 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001174 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001175 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1176 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1177 MemberPointerInfo MPI(
1178 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001179 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001180 return TypeTable.writePointer(PR);
1181}
1182
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001183/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1184/// have a translation, use the NearC convention.
1185static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1186 switch (DwarfCC) {
1187 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1188 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1189 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1190 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1191 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1192 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1193 }
1194 return CallingConvention::NearC;
1195}
1196
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001197TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1198 ModifierOptions Mods = ModifierOptions::None;
1199 bool IsModifier = true;
1200 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001201 while (IsModifier && BaseTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001202 // FIXME: Need to add DWARF tag for __unaligned.
1203 switch (BaseTy->getTag()) {
1204 case dwarf::DW_TAG_const_type:
1205 Mods |= ModifierOptions::Const;
1206 break;
1207 case dwarf::DW_TAG_volatile_type:
1208 Mods |= ModifierOptions::Volatile;
1209 break;
1210 default:
1211 IsModifier = false;
1212 break;
1213 }
1214 if (IsModifier)
1215 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1216 }
1217 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001218
1219 // While processing the type being pointed to, it is possible we already
1220 // created this modifier type. If so, we check here and return the existing
1221 // modifier type.
1222 auto I = TypeIndices.find({Ty, nullptr});
1223 if (I != TypeIndices.end())
1224 return I->second;
1225
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001226 ModifierRecord MR(ModifiedTI, Mods);
1227 return TypeTable.writeModifier(MR);
1228}
1229
David Majnemer75c3ebf2016-06-02 17:13:53 +00001230TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1231 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1232 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1233 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1234
1235 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1236 ArrayRef<TypeIndex> ArgTypeIndices = None;
1237 if (!ReturnAndArgTypeIndices.empty()) {
1238 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1239 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1240 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1241 }
1242
1243 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1244 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
1245
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001246 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1247
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001248 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1249 ArgTypeIndices.size(), ArgListIndex);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001250 return TypeTable.writeProcedure(Procedure);
1251}
1252
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001253TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001254 const DIType *ClassTy,
1255 int ThisAdjustment) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001256 // Lower the containing class type.
1257 TypeIndex ClassType = getTypeIndex(ClassTy);
1258
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001259 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1260 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1261 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1262
1263 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1264 ArrayRef<TypeIndex> ArgTypeIndices = None;
1265 if (!ReturnAndArgTypeIndices.empty()) {
1266 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1267 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1268 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1269 }
1270 TypeIndex ThisTypeIndex = TypeIndex::Void();
1271 if (!ArgTypeIndices.empty()) {
1272 ThisTypeIndex = ArgTypeIndices.front();
1273 ArgTypeIndices = ArgTypeIndices.drop_front();
1274 }
1275
1276 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1277 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
1278
1279 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1280
1281 // TODO: Need to use the correct values for:
1282 // FunctionOptions
1283 // ThisPointerAdjustment.
1284 TypeIndex TI = TypeTable.writeMemberFunction(MemberFunctionRecord(
1285 ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001286 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001287
1288 return TI;
1289}
1290
1291static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1292 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001293 case DINode::FlagPrivate: return MemberAccess::Private;
1294 case DINode::FlagPublic: return MemberAccess::Public;
1295 case DINode::FlagProtected: return MemberAccess::Protected;
1296 case 0:
1297 // If there was no explicit access control, provide the default for the tag.
1298 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1299 : MemberAccess::Public;
1300 }
1301 llvm_unreachable("access flags are exclusive");
1302}
1303
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001304static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1305 if (SP->isArtificial())
1306 return MethodOptions::CompilerGenerated;
1307
1308 // FIXME: Handle other MethodOptions.
1309
1310 return MethodOptions::None;
1311}
1312
1313static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1314 bool Introduced) {
1315 switch (SP->getVirtuality()) {
1316 case dwarf::DW_VIRTUALITY_none:
1317 break;
1318 case dwarf::DW_VIRTUALITY_virtual:
1319 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1320 case dwarf::DW_VIRTUALITY_pure_virtual:
1321 return Introduced ? MethodKind::PureIntroducingVirtual
1322 : MethodKind::PureVirtual;
1323 default:
1324 llvm_unreachable("unhandled virtuality case");
1325 }
1326
1327 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1328
1329 return MethodKind::Vanilla;
1330}
1331
Reid Klecknera8d57402016-06-03 15:58:20 +00001332static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1333 switch (Ty->getTag()) {
1334 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1335 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1336 }
1337 llvm_unreachable("unexpected tag");
1338}
1339
Reid Klecknere092dad2016-07-02 00:11:07 +00001340/// Return ClassOptions that should be present on both the forward declaration
1341/// and the defintion of a tag type.
1342static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1343 ClassOptions CO = ClassOptions::None;
1344
1345 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001346 // appear to give every type a linkage name, which may be problematic for us.
1347 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001348 if (!Ty->getIdentifier().empty())
1349 CO |= ClassOptions::HasUniqueName;
1350
1351 // Put the Nested flag on a type if it appears immediately inside a tag type.
1352 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1353 // here. That flag is only set on definitions, and not forward declarations.
1354 const DIScope *ImmediateScope = Ty->getScope().resolve();
1355 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1356 CO |= ClassOptions::Nested;
1357
1358 // Put the Scoped flag on function-local types.
1359 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1360 Scope = Scope->getScope().resolve()) {
1361 if (isa<DISubprogram>(Scope)) {
1362 CO |= ClassOptions::Scoped;
1363 break;
1364 }
1365 }
1366
1367 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001368}
1369
David Majnemer979cb882016-06-16 21:32:16 +00001370TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001371 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001372 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001373 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001374
David Majnemerda9548f2016-06-17 16:13:21 +00001375 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001376 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001377 } else {
1378 FieldListRecordBuilder Fields;
1379 for (const DINode *Element : Ty->getElements()) {
1380 // We assume that the frontend provides all members in source declaration
1381 // order, which is what MSVC does.
1382 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
1383 Fields.writeEnumerator(EnumeratorRecord(
1384 MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()),
1385 Enumerator->getName()));
1386 EnumeratorCount++;
1387 }
1388 }
1389 FTI = TypeTable.writeFieldList(Fields);
1390 }
David Majnemer979cb882016-06-16 21:32:16 +00001391
David Majnemer6bdc24e2016-07-01 23:12:45 +00001392 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001393
1394 return TypeTable.writeEnum(EnumRecord(EnumeratorCount, CO, FTI, FullName,
David Majnemer979cb882016-06-16 21:32:16 +00001395 Ty->getIdentifier(),
1396 getTypeIndex(Ty->getBaseType())));
1397}
1398
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001399//===----------------------------------------------------------------------===//
1400// ClassInfo
1401//===----------------------------------------------------------------------===//
1402
1403struct llvm::ClassInfo {
1404 struct MemberInfo {
1405 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001406 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001407 };
1408 // [MemberInfo]
1409 typedef std::vector<MemberInfo> MemberList;
1410
Reid Kleckner156a7232016-06-22 18:31:14 +00001411 typedef TinyPtrVector<const DISubprogram *> MethodsList;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001412 // MethodName -> MethodsList
1413 typedef MapVector<MDString *, MethodsList> MethodsMap;
1414
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001415 /// Base classes.
1416 std::vector<const DIDerivedType *> Inheritance;
1417
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001418 /// Direct members.
1419 MemberList Members;
1420 // Direct overloaded methods gathered by name.
1421 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001422
1423 std::vector<const DICompositeType *> NestedClasses;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001424};
1425
1426void CodeViewDebug::clear() {
1427 assert(CurFn == nullptr);
1428 FileIdMap.clear();
1429 FnDebugInfo.clear();
1430 FileToFilepathMap.clear();
1431 LocalUDTs.clear();
1432 GlobalUDTs.clear();
1433 TypeIndices.clear();
1434 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001435}
1436
1437void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1438 const DIDerivedType *DDTy) {
1439 if (!DDTy->getName().empty()) {
1440 Info.Members.push_back({DDTy, 0});
1441 return;
1442 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001443 // An unnamed member must represent a nested struct or union. Add all the
1444 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001445 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00001446 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001447 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001448 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001449 ClassInfo NestedInfo = collectClassInfo(DCTy);
1450 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001451 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001452 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001453}
1454
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001455ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1456 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001457 // Add elements to structure type.
1458 DINodeArray Elements = Ty->getElements();
1459 for (auto *Element : Elements) {
1460 // We assume that the frontend provides all members in source declaration
1461 // order, which is what MSVC does.
1462 if (!Element)
1463 continue;
1464 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00001465 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001466 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001467 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001468 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001469 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1470 Info.Inheritance.push_back(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001471 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1472 // Ignore friend members. It appears that MSVC emitted info about
1473 // friends in the past, but modern versions do not.
1474 }
1475 // FIXME: Get Clang to emit function virtual table here and handle it.
Adrian McCarthy820ca542016-07-06 19:49:51 +00001476 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1477 Info.NestedClasses.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001478 }
1479 // Skip other unrecognized kinds of elements.
1480 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001481 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001482}
1483
Reid Klecknera8d57402016-06-03 15:58:20 +00001484TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1485 // First, construct the forward decl. Don't look into Ty to compute the
1486 // forward decl options, since it might not be available in all TUs.
1487 TypeRecordKind Kind = getRecordKind(Ty);
1488 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001489 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001490 std::string FullName = getFullyQualifiedName(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001491 TypeIndex FwdDeclTI = TypeTable.writeClass(ClassRecord(
1492 Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001493 TypeIndex(), TypeIndex(), 0, FullName, Ty->getIdentifier()));
Reid Kleckner643dd832016-06-22 17:15:28 +00001494 if (!Ty->isForwardDecl())
1495 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001496 return FwdDeclTI;
1497}
1498
1499TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1500 // Construct the field list and complete type record.
1501 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00001502 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001503 TypeIndex FieldTI;
1504 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001505 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001506 bool ContainsNestedClass;
1507 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1508 lowerRecordFieldList(Ty);
1509
1510 if (ContainsNestedClass)
1511 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00001512
David Majnemer6bdc24e2016-07-01 23:12:45 +00001513 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001514
Reid Klecknera8d57402016-06-03 15:58:20 +00001515 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00001516
1517 TypeIndex ClassTI = TypeTable.writeClass(ClassRecord(
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001518 Kind, FieldCount, CO, HfaKind::None, WindowsRTClassKind::None, FieldTI,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001519 TypeIndex(), VShapeTI, SizeInBytes, FullName, Ty->getIdentifier()));
Hans Wennborg9a519a02016-06-22 21:22:13 +00001520
1521 TypeTable.writeUdtSourceLine(UdtSourceLineRecord(
1522 ClassTI, TypeTable.writeStringId(StringIdRecord(
1523 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1524 Ty->getLine()));
1525
Hans Wennborg4b63a982016-06-23 22:57:25 +00001526 addToUDTs(Ty, ClassTI);
1527
Hans Wennborg9a519a02016-06-22 21:22:13 +00001528 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001529}
1530
1531TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1532 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00001533 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00001534 std::string FullName = getFullyQualifiedName(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001535 TypeIndex FwdDeclTI =
1536 TypeTable.writeUnion(UnionRecord(0, CO, HfaKind::None, TypeIndex(), 0,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001537 FullName, Ty->getIdentifier()));
Reid Kleckner643dd832016-06-22 17:15:28 +00001538 if (!Ty->isForwardDecl())
1539 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001540 return FwdDeclTI;
1541}
1542
1543TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00001544 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001545 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001546 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001547 bool ContainsNestedClass;
1548 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1549 lowerRecordFieldList(Ty);
1550
1551 if (ContainsNestedClass)
1552 CO |= ClassOptions::ContainsNestedClass;
1553
Reid Klecknera8d57402016-06-03 15:58:20 +00001554 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00001555 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00001556
1557 TypeIndex UnionTI = TypeTable.writeUnion(
1558 UnionRecord(FieldCount, CO, HfaKind::None, FieldTI, SizeInBytes, FullName,
1559 Ty->getIdentifier()));
1560
1561 TypeTable.writeUdtSourceLine(UdtSourceLineRecord(
1562 UnionTI, TypeTable.writeStringId(StringIdRecord(
1563 TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1564 Ty->getLine()));
1565
Hans Wennborg4b63a982016-06-23 22:57:25 +00001566 addToUDTs(Ty, UnionTI);
1567
Hans Wennborg9a519a02016-06-22 21:22:13 +00001568 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001569}
1570
Adrian McCarthy820ca542016-07-06 19:49:51 +00001571std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00001572CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1573 // Manually count members. MSVC appears to count everything that generates a
1574 // field list record. Each individual overload in a method overload group
1575 // contributes to this count, even though the overload group is a single field
1576 // list record.
1577 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001578 ClassInfo Info = collectClassInfo(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001579 FieldListRecordBuilder Fields;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001580
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001581 // Create base classes.
1582 for (const DIDerivedType *I : Info.Inheritance) {
1583 if (I->getFlags() & DINode::FlagVirtual) {
1584 // Virtual base.
1585 // FIXME: Emit VBPtrOffset when the frontend provides it.
1586 unsigned VBPtrOffset = 0;
1587 // FIXME: Despite the accessor name, the offset is really in bytes.
1588 unsigned VBTableIndex = I->getOffsetInBits() / 4;
1589 Fields.writeVirtualBaseClass(VirtualBaseClassRecord(
1590 translateAccessFlags(Ty->getTag(), I->getFlags()),
1591 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
1592 VBTableIndex));
1593 } else {
1594 assert(I->getOffsetInBits() % 8 == 0 &&
1595 "bases must be on byte boundaries");
1596 Fields.writeBaseClass(BaseClassRecord(
1597 translateAccessFlags(Ty->getTag(), I->getFlags()),
1598 getTypeIndex(I->getBaseType()), I->getOffsetInBits() / 8));
1599 }
1600 }
1601
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001602 // Create members.
1603 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1604 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1605 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00001606 StringRef MemberName = Member->getName();
1607 MemberAccess Access =
1608 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001609
1610 if (Member->isStaticMember()) {
David Majnemer9319cbc2016-06-30 03:00:20 +00001611 Fields.writeStaticDataMember(
1612 StaticDataMemberRecord(Access, MemberBaseType, MemberName));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001613 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001614 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001615 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001616
David Majnemer9319cbc2016-06-30 03:00:20 +00001617 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00001618 uint64_t MemberOffsetInBits =
1619 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001620 if (Member->isBitField()) {
1621 uint64_t StartBitOffset = MemberOffsetInBits;
1622 if (const auto *CI =
1623 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00001624 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00001625 }
1626 StartBitOffset -= MemberOffsetInBits;
1627 MemberBaseType = TypeTable.writeBitField(BitFieldRecord(
1628 MemberBaseType, Member->getSizeInBits(), StartBitOffset));
1629 }
1630 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
1631 Fields.writeDataMember(DataMemberRecord(Access, MemberBaseType,
1632 MemberOffsetInBytes, MemberName));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001633 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001634 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001635
1636 // Create methods
1637 for (auto &MethodItr : Info.Methods) {
1638 StringRef Name = MethodItr.first->getString();
1639
1640 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00001641 for (const DISubprogram *SP : MethodItr.second) {
1642 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1643 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001644
1645 unsigned VFTableOffset = -1;
1646 if (Introduced)
1647 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1648
1649 Methods.push_back(
1650 OneMethodRecord(MethodType, translateMethodKindFlags(SP, Introduced),
1651 translateMethodOptionFlags(SP),
1652 translateAccessFlags(Ty->getTag(), SP->getFlags()),
1653 VFTableOffset, Name));
1654 MemberCount++;
1655 }
1656 assert(Methods.size() > 0 && "Empty methods map entry");
1657 if (Methods.size() == 1)
1658 Fields.writeOneMethod(Methods[0]);
1659 else {
1660 TypeIndex MethodList =
1661 TypeTable.writeMethodOverloadList(MethodOverloadListRecord(Methods));
1662 Fields.writeOverloadedMethod(
1663 OverloadedMethodRecord(Methods.size(), MethodList, Name));
1664 }
1665 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00001666
1667 // Create nested classes.
1668 for (const DICompositeType *Nested : Info.NestedClasses) {
1669 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
1670 Fields.writeNestedType(R);
1671 MemberCount++;
1672 }
1673
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001674 TypeIndex FieldTI = TypeTable.writeFieldList(Fields);
Adrian McCarthy820ca542016-07-06 19:49:51 +00001675 return std::make_tuple(FieldTI, TypeIndex(), MemberCount,
1676 !Info.NestedClasses.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00001677}
1678
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001679TypeIndex CodeViewDebug::getVBPTypeIndex() {
1680 if (!VBPType.getIndex()) {
1681 // Make a 'const int *' type.
1682 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
1683 TypeIndex ModifiedTI = TypeTable.writeModifier(MR);
1684
1685 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1686 : PointerKind::Near32;
1687 PointerMode PM = PointerMode::Pointer;
1688 PointerOptions PO = PointerOptions::None;
1689 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1690
1691 VBPType = TypeTable.writePointer(PR);
1692 }
1693
1694 return VBPType;
1695}
1696
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001697TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001698 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001699 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001700
1701 // The null DIType is the void type. Don't try to hash it.
1702 if (!Ty)
1703 return TypeIndex::Void();
1704
Reid Klecknera8d57402016-06-03 15:58:20 +00001705 // Check if we've already translated this type. Don't try to do a
1706 // get-or-create style insertion that caches the hash lookup across the
1707 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001708 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001709 if (I != TypeIndices.end())
1710 return I->second;
1711
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001712 TypeLoweringScope S(*this);
1713 TypeIndex TI = lowerType(Ty, ClassTy);
1714 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00001715}
1716
1717TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1718 const DIType *Ty = TypeRef.resolve();
1719
1720 // The null DIType is the void type. Don't try to hash it.
1721 if (!Ty)
1722 return TypeIndex::Void();
1723
1724 // If this is a non-record type, the complete type index is the same as the
1725 // normal type index. Just call getTypeIndex.
1726 switch (Ty->getTag()) {
1727 case dwarf::DW_TAG_class_type:
1728 case dwarf::DW_TAG_structure_type:
1729 case dwarf::DW_TAG_union_type:
1730 break;
1731 default:
1732 return getTypeIndex(Ty);
1733 }
1734
1735 // Check if we've already translated the complete record type. Lowering a
1736 // complete type should never trigger lowering another complete type, so we
1737 // can reuse the hash table lookup result.
1738 const auto *CTy = cast<DICompositeType>(Ty);
1739 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1740 if (!InsertResult.second)
1741 return InsertResult.first->second;
1742
Reid Kleckner643dd832016-06-22 17:15:28 +00001743 TypeLoweringScope S(*this);
1744
Reid Klecknera8d57402016-06-03 15:58:20 +00001745 // Make sure the forward declaration is emitted first. It's unclear if this
1746 // is necessary, but MSVC does it, and we should follow suit until we can show
1747 // otherwise.
1748 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1749
1750 // Just use the forward decl if we don't have complete type info. This might
1751 // happen if the frontend is using modules and expects the complete definition
1752 // to be emitted elsewhere.
1753 if (CTy->isForwardDecl())
1754 return FwdDeclTI;
1755
1756 TypeIndex TI;
1757 switch (CTy->getTag()) {
1758 case dwarf::DW_TAG_class_type:
1759 case dwarf::DW_TAG_structure_type:
1760 TI = lowerCompleteTypeClass(CTy);
1761 break;
1762 case dwarf::DW_TAG_union_type:
1763 TI = lowerCompleteTypeUnion(CTy);
1764 break;
1765 default:
1766 llvm_unreachable("not a record");
1767 }
1768
1769 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001770 return TI;
1771}
1772
Reid Kleckner643dd832016-06-22 17:15:28 +00001773/// Emit all the deferred complete record types. Try to do this in FIFO order,
1774/// and do this until fixpoint, as each complete record type typically references
1775/// many other record types.
1776void CodeViewDebug::emitDeferredCompleteTypes() {
1777 SmallVector<const DICompositeType *, 4> TypesToEmit;
1778 while (!DeferredCompleteTypes.empty()) {
1779 std::swap(DeferredCompleteTypes, TypesToEmit);
1780 for (const DICompositeType *RecordTy : TypesToEmit)
1781 getCompleteTypeIndex(RecordTy);
1782 TypesToEmit.clear();
1783 }
1784}
1785
Reid Kleckner10dd55c2016-06-24 17:55:40 +00001786void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
1787 // Get the sorted list of parameters and emit them first.
1788 SmallVector<const LocalVariable *, 6> Params;
1789 for (const LocalVariable &L : Locals)
1790 if (L.DIVar->isParameter())
1791 Params.push_back(&L);
1792 std::sort(Params.begin(), Params.end(),
1793 [](const LocalVariable *L, const LocalVariable *R) {
1794 return L->DIVar->getArg() < R->DIVar->getArg();
1795 });
1796 for (const LocalVariable *L : Params)
1797 emitLocalVariable(*L);
1798
1799 // Next emit all non-parameters in the order that we found them.
1800 for (const LocalVariable &L : Locals)
1801 if (!L.DIVar->isParameter())
1802 emitLocalVariable(L);
1803}
1804
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001805void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
1806 // LocalSym record, see SymbolRecord.h for more info.
1807 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
1808 *LocalEnd = MMI->getContext().createTempSymbol();
1809 OS.AddComment("Record length");
1810 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
1811 OS.EmitLabel(LocalBegin);
1812
1813 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00001814 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001815
Zachary Turner63a28462016-05-17 23:50:21 +00001816 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001817 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00001818 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00001819 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00001820 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001821
1822 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00001823 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001824 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001825 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00001826 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00001827 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00001828 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001829 OS.EmitLabel(LocalEnd);
1830
Reid Kleckner876330d2016-02-12 21:48:30 +00001831 // Calculate the on disk prefix of the appropriate def range record. The
1832 // records and on disk formats are described in SymbolRecords.h. BytePrefix
1833 // should be big enough to hold all forms without memory allocation.
1834 SmallString<20> BytePrefix;
1835 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
1836 BytePrefix.clear();
1837 // FIXME: Handle bitpieces.
1838 if (DefRange.StructOffset != 0)
1839 continue;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001840
Reid Kleckner876330d2016-02-12 21:48:30 +00001841 if (DefRange.InMemory) {
Zachary Turnera78ecd12016-05-23 18:49:06 +00001842 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
1843 0, 0, ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001844 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00001845 BytePrefix +=
1846 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001847 BytePrefix +=
1848 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1849 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001850 } else {
1851 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Zachary Turnera78ecd12016-05-23 18:49:06 +00001852 // Unclear what matters here.
1853 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
1854 ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001855 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
Reid Kleckner876330d2016-02-12 21:48:30 +00001856 BytePrefix +=
1857 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001858 BytePrefix +=
1859 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1860 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001861 }
1862 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
1863 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001864}
1865
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001866void CodeViewDebug::endFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001867 if (!Asm || !CurFn) // We haven't created any debug info for this function.
1868 return;
1869
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001870 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00001871 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001872 assert(CurFn == &FnDebugInfo[GV]);
1873
Pete Cooperadebb932016-03-11 02:14:16 +00001874 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00001875
1876 DebugHandlerBase::endFunction(MF);
1877
Reid Kleckner2214ed82016-01-29 00:49:42 +00001878 // Don't emit anything if we don't have any line tables.
1879 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001880 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001881 CurFn = nullptr;
1882 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00001883 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001884
1885 CurFn->End = Asm->getFunctionEnd();
1886
Craig Topper353eda42014-04-24 06:44:33 +00001887 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001888}
1889
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001890void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001891 DebugHandlerBase::beginInstruction(MI);
1892
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001893 // Ignore DBG_VALUE locations and function prologue.
1894 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
1895 return;
1896 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001897 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001898 return;
1899 maybeRecordLocation(DL, Asm->MF);
1900}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001901
1902MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
1903 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
1904 *EndLabel = MMI->getContext().createTempSymbol();
1905 OS.EmitIntValue(unsigned(Kind), 4);
1906 OS.AddComment("Subsection size");
1907 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
1908 OS.EmitLabel(BeginLabel);
1909 return EndLabel;
1910}
1911
1912void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
1913 OS.EmitLabel(EndLabel);
1914 // Every subsection must be aligned to a 4-byte boundary.
1915 OS.EmitValueToAlignment(4);
1916}
1917
David Majnemer3128b102016-06-15 18:00:01 +00001918void CodeViewDebug::emitDebugInfoForUDTs(
1919 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
1920 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
1921 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
1922 *UDTRecordEnd = MMI->getContext().createTempSymbol();
1923 OS.AddComment("Record length");
1924 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
1925 OS.EmitLabel(UDTRecordBegin);
1926
1927 OS.AddComment("Record kind: S_UDT");
1928 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
1929
1930 OS.AddComment("Type");
1931 OS.EmitIntValue(UDT.second.getIndex(), 4);
1932
1933 emitNullTerminatedSymbolName(OS, UDT.first);
1934 OS.EmitLabel(UDTRecordEnd);
1935 }
1936}
1937
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001938void CodeViewDebug::emitDebugInfoForGlobals() {
1939 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1940 for (const MDNode *Node : CUs->operands()) {
1941 const auto *CU = cast<DICompileUnit>(Node);
1942
1943 // First, emit all globals that are not in a comdat in a single symbol
1944 // substream. MSVC doesn't like it if the substream is empty, so only open
1945 // it if we have at least one global to emit.
1946 switchToDebugSectionForSymbol(nullptr);
1947 MCSymbol *EndLabel = nullptr;
1948 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001949 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
David Majnemer577be0f2016-06-15 00:19:52 +00001950 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001951 if (!EndLabel) {
1952 OS.AddComment("Symbol subsection for globals");
1953 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1954 }
1955 emitDebugInfoForGlobal(G, Asm->getSymbol(GV));
1956 }
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001957 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001958 }
1959 if (EndLabel)
1960 endCVSubsection(EndLabel);
1961
1962 // Second, emit each global that is in a comdat into its own .debug$S
1963 // section along with its own symbol substream.
1964 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001965 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001966 if (GV->hasComdat()) {
1967 MCSymbol *GVSym = Asm->getSymbol(GV);
1968 OS.AddComment("Symbol subsection for " +
1969 Twine(GlobalValue::getRealLinkageName(GV->getName())));
1970 switchToDebugSectionForSymbol(GVSym);
1971 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1972 emitDebugInfoForGlobal(G, GVSym);
1973 endCVSubsection(EndLabel);
1974 }
1975 }
1976 }
1977 }
1978}
1979
Hans Wennborgb510b452016-06-23 16:33:53 +00001980void CodeViewDebug::emitDebugInfoForRetainedTypes() {
1981 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1982 for (const MDNode *Node : CUs->operands()) {
1983 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
1984 if (DIType *RT = dyn_cast<DIType>(Ty)) {
1985 getTypeIndex(RT);
1986 // FIXME: Add to global/local DTU list.
1987 }
1988 }
1989 }
1990}
1991
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001992void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
1993 MCSymbol *GVSym) {
1994 // DataSym record, see SymbolRecord.h for more info.
1995 // FIXME: Thread local data, etc
1996 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
1997 *DataEnd = MMI->getContext().createTempSymbol();
1998 OS.AddComment("Record length");
1999 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2000 OS.EmitLabel(DataBegin);
David Majnemera54fe1a2016-07-07 05:14:21 +00002001 const auto *GV = cast<GlobalVariable>(DIGV->getVariable());
David Majnemer7abd2692016-07-06 21:07:47 +00002002 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002003 if (GV->isThreadLocal()) {
2004 OS.AddComment("Record kind: S_LTHREAD32");
2005 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2006 } else {
2007 OS.AddComment("Record kind: S_LDATA32");
2008 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2009 }
David Majnemer7abd2692016-07-06 21:07:47 +00002010 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002011 if (GV->isThreadLocal()) {
2012 OS.AddComment("Record kind: S_GTHREAD32");
2013 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2014 } else {
2015 OS.AddComment("Record kind: S_GDATA32");
2016 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2017 }
David Majnemer7abd2692016-07-06 21:07:47 +00002018 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002019 OS.AddComment("Type");
2020 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2021 OS.AddComment("DataOffset");
2022 OS.EmitCOFFSecRel32(GVSym);
2023 OS.AddComment("Segment");
2024 OS.EmitCOFFSectionIndex(GVSym);
2025 OS.AddComment("Name");
2026 emitNullTerminatedSymbolName(OS, DIGV->getName());
2027 OS.EmitLabel(DataEnd);
2028}