1//===-- LVCodeViewVisitor.cpp ---------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements the LVCodeViewVisitor class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/DebugInfo/LogicalView/Readers/LVCodeViewVisitor.h"
14#include "llvm/BinaryFormat/Magic.h"
15#include "llvm/DebugInfo/CodeView/EnumTables.h"
16#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
17#include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"
18#include "llvm/DebugInfo/CodeView/TypeRecordHelpers.h"
19#include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h"
20#include "llvm/DebugInfo/LogicalView/Core/LVScope.h"
21#include "llvm/DebugInfo/LogicalView/Core/LVSymbol.h"
22#include "llvm/DebugInfo/LogicalView/Core/LVType.h"
23#include "llvm/DebugInfo/LogicalView/Readers/LVCodeViewReader.h"
24#include "llvm/DebugInfo/PDB/Native/InputFile.h"
25#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
26#include "llvm/DebugInfo/PDB/Native/PDBStringTable.h"
27#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
28#include "llvm/Demangle/Demangle.h"
29#include "llvm/Object/COFF.h"
30#include "llvm/Support/Error.h"
31#include "llvm/Support/FormatAdapters.h"
32#include "llvm/Support/FormatVariadic.h"
33
34using namespace llvm;
35using namespace llvm::codeview;
36using namespace llvm::object;
37using namespace llvm::pdb;
38using namespace llvm::logicalview;
39
40#define DEBUG_TYPE "CodeViewUtilities"
41
42namespace llvm {
43namespace logicalview {
44
45static TypeIndex getTrueType(TypeIndex &TI) {
46 // Dealing with a MSVC generated PDB, we encountered a type index with the
47 // value of: 0x0280xxxx where xxxx=0000.
48 //
49 // There is some documentation about type indices:
50 // https://llvm.org/docs/PDB/TpiStream.html
51 //
52 // A type index is a 32-bit integer that uniquely identifies a type inside
53 // of an object file’s .debug$T section or a PDB file’s TPI or IPI stream.
54 // The value of the type index for the first type record from the TPI stream
55 // is given by the TypeIndexBegin member of the TPI Stream Header although
56 // in practice this value is always equal to 0x1000 (4096).
57 //
58 // Any type index with a high bit set is considered to come from the IPI
59 // stream, although this appears to be more of a hack, and LLVM does not
60 // generate type indices of this nature. They can, however, be observed in
61 // Microsoft PDBs occasionally, so one should be prepared to handle them.
62 // Note that having the high bit set is not a necessary condition to
63 // determine whether a type index comes from the IPI stream, it is only
64 // sufficient.
65 LLVM_DEBUG(
66 { dbgs() << "Index before: " << HexNumber(TI.getIndex()) << "\n"; });
67 TI.setIndex(TI.getIndex() & 0x0000ffff);
68 LLVM_DEBUG(
69 { dbgs() << "Index after: " << HexNumber(TI.getIndex()) << "\n"; });
70 return TI;
71}
72
73static const EnumEntry<TypeLeafKind> LeafTypeNames[] = {
74#define CV_TYPE(enum, val) {#enum, enum},
75#include "llvm/DebugInfo/CodeView/CodeViewTypes.def"
76};
77
78// Return the type name pointed by the type index. It uses the kind to query
79// the associated name for the record type.
80static StringRef getRecordName(LazyRandomTypeCollection &Types, TypeIndex TI) {
81 if (TI.isSimple())
82 return {};
83
84 StringRef RecordName;
85 CVType CVReference = Types.getType(Index: TI);
86 auto GetName = [&](auto Record) {
87 if (Error Err = TypeDeserializer::deserializeAs(
88 const_cast<CVType &>(CVReference), Record))
89 consumeError(Err: std::move(Err));
90 else
91 RecordName = Record.getName();
92 };
93
94 TypeRecordKind RK = static_cast<TypeRecordKind>(CVReference.kind());
95 if (RK == TypeRecordKind::Class || RK == TypeRecordKind::Struct)
96 GetName(ClassRecord(RK));
97 else if (RK == TypeRecordKind::Union)
98 GetName(UnionRecord(RK));
99 else if (RK == TypeRecordKind::Enum)
100 GetName(EnumRecord(RK));
101
102 return RecordName;
103}
104
105} // namespace logicalview
106} // namespace llvm
107
108#undef DEBUG_TYPE
109#define DEBUG_TYPE "CodeViewDataVisitor"
110
111namespace llvm {
112namespace logicalview {
113
114// Keeps the type indexes with line information.
115using LVLineRecords = std::vector<TypeIndex>;
116
117namespace {
118
119class LVTypeRecords {
120 LVShared *Shared = nullptr;
121
122 // Logical elements associated to their CodeView Type Index.
123 using RecordEntry = std::pair<TypeLeafKind, LVElement *>;
124 using RecordTable = std::map<TypeIndex, RecordEntry>;
125 RecordTable RecordFromTypes;
126 RecordTable RecordFromIds;
127
128 using NameTable = std::map<StringRef, TypeIndex>;
129 NameTable NameFromTypes;
130 NameTable NameFromIds;
131
132public:
133 LVTypeRecords(LVShared *Shared) : Shared(Shared) {}
134
135 void add(uint32_t StreamIdx, TypeIndex TI, TypeLeafKind Kind,
136 LVElement *Element = nullptr);
137 void add(uint32_t StreamIdx, TypeIndex TI, StringRef Name);
138 LVElement *find(uint32_t StreamIdx, TypeIndex TI, bool Create = true);
139 TypeIndex find(uint32_t StreamIdx, StringRef Name);
140};
141
142class LVForwardReferences {
143 // Forward reference and its definitions (Name as key).
144 using ForwardEntry = std::pair<TypeIndex, TypeIndex>;
145 using ForwardTypeNames = std::map<StringRef, ForwardEntry>;
146 ForwardTypeNames ForwardTypesNames;
147
148 // Forward reference and its definition (TypeIndex as key).
149 using ForwardType = std::map<TypeIndex, TypeIndex>;
150 ForwardType ForwardTypes;
151
152 // Forward types and its references.
153 void add(TypeIndex TIForward, TypeIndex TIReference) {
154 ForwardTypes.emplace(args&: TIForward, args&: TIReference);
155 }
156
157 void add(StringRef Name, TypeIndex TIForward) {
158 auto [It, Inserted] =
159 ForwardTypesNames.try_emplace(k: Name, args&: TIForward, args: TypeIndex::None());
160 if (!Inserted) {
161 // Update a recorded definition with its reference.
162 It->second.first = TIForward;
163 add(TIForward, TIReference: It->second.second);
164 }
165 }
166
167 // Update a previously recorded forward reference with its definition.
168 void update(StringRef Name, TypeIndex TIReference) {
169 auto [It, Inserted] =
170 ForwardTypesNames.try_emplace(k: Name, args: TypeIndex::None(), args&: TIReference);
171 if (!Inserted) {
172 // Update the recorded forward reference with its definition.
173 It->second.second = TIReference;
174 add(TIForward: It->second.first, TIReference);
175 }
176 }
177
178public:
179 LVForwardReferences() = default;
180
181 void record(bool IsForwardRef, StringRef Name, TypeIndex TI) {
182 // We are expecting for the forward references to be first. But that
183 // is not always the case. A name must be recorded regardless of the
184 // order in which the forward reference appears.
185 (IsForwardRef) ? add(Name, TIForward: TI) : update(Name, TIReference: TI);
186 }
187
188 TypeIndex find(TypeIndex TIForward) {
189 auto It = ForwardTypes.find(x: TIForward);
190 return It != ForwardTypes.end() ? It->second : TypeIndex::None();
191 }
192
193 TypeIndex find(StringRef Name) {
194 auto It = ForwardTypesNames.find(x: Name);
195 return It != ForwardTypesNames.end() ? It->second.second
196 : TypeIndex::None();
197 }
198
199 // If the given TI corresponds to a reference, return the reference.
200 // Otherwise return the given TI.
201 TypeIndex remap(TypeIndex TI) {
202 TypeIndex Forward = find(TIForward: TI);
203 return Forward.isNoneType() ? TI : Forward;
204 }
205};
206
207// Namespace deduction.
208class LVNamespaceDeduction {
209 LVShared *Shared = nullptr;
210
211 using Names = std::map<StringRef, LVScope *>;
212 Names NamespaceNames;
213
214 using LookupSet = std::set<StringRef>;
215 LookupSet DeducedScopes;
216 LookupSet UnresolvedScopes;
217 LookupSet IdentifiedNamespaces;
218
219 void add(StringRef Name, LVScope *Namespace) {
220 if (NamespaceNames.find(x: Name) == NamespaceNames.end())
221 NamespaceNames.emplace(args&: Name, args&: Namespace);
222 }
223
224public:
225 LVNamespaceDeduction(LVShared *Shared) : Shared(Shared) {}
226
227 void init();
228 void add(StringRef String);
229 LVScope *get(LVStringRefs Components);
230 LVScope *get(StringRef Name, bool CheckScope = true);
231
232 // Find the logical namespace for the 'Name' component.
233 LVScope *find(StringRef Name) {
234 auto It = NamespaceNames.find(x: Name);
235 LVScope *Namespace = It != NamespaceNames.end() ? It->second : nullptr;
236 return Namespace;
237 }
238
239 // For the given lexical components, return a tuple with the first entry
240 // being the outermost namespace and the second entry being the first
241 // non-namespace.
242 LVLexicalIndex find(LVStringRefs Components) {
243 if (Components.empty())
244 return {};
245
246 LVStringRefs::size_type FirstNamespace = 0;
247 LVStringRefs::size_type FirstNonNamespace;
248 for (LVStringRefs::size_type Index = 0; Index < Components.size();
249 ++Index) {
250 FirstNonNamespace = Index;
251 LookupSet::iterator Iter = IdentifiedNamespaces.find(x: Components[Index]);
252 if (Iter == IdentifiedNamespaces.end())
253 // The component is not a namespace name.
254 break;
255 }
256 return std::make_tuple(args&: FirstNamespace, args&: FirstNonNamespace);
257 }
258};
259
260// Strings.
261class LVStringRecords {
262 using StringEntry = std::tuple<uint32_t, std::string, LVScopeCompileUnit *>;
263 using StringIds = std::map<TypeIndex, StringEntry>;
264 StringIds Strings;
265
266public:
267 LVStringRecords() = default;
268
269 void add(TypeIndex TI, StringRef String) {
270 static uint32_t Index = 0;
271 auto [It, Inserted] = Strings.try_emplace(k: TI);
272 if (Inserted)
273 It->second = std::make_tuple(args&: ++Index, args: std::string(String), args: nullptr);
274 }
275
276 StringRef find(TypeIndex TI) {
277 StringIds::iterator Iter = Strings.find(x: TI);
278 return Iter != Strings.end() ? std::get<1>(t&: Iter->second) : StringRef{};
279 }
280
281 uint32_t findIndex(TypeIndex TI) {
282 StringIds::iterator Iter = Strings.find(x: TI);
283 return Iter != Strings.end() ? std::get<0>(t&: Iter->second) : 0;
284 }
285
286 // Move strings representing the filenames to the compile unit.
287 void addFilenames();
288 void addFilenames(LVScopeCompileUnit *Scope);
289};
290} // namespace
291
292using LVTypeKinds = std::set<TypeLeafKind>;
293using LVSymbolKinds = std::set<SymbolKind>;
294
295// The following data keeps forward information, type records, names for
296// namespace deduction, strings records, line records.
297// It is shared by the type visitor, symbol visitor and logical visitor and
298// it is independent from the CodeViewReader.
299struct LVShared {
300 LVCodeViewReader *Reader;
301 LVLogicalVisitor *Visitor;
302 LVForwardReferences ForwardReferences;
303 LVLineRecords LineRecords;
304 LVNamespaceDeduction NamespaceDeduction;
305 LVStringRecords StringRecords;
306 LVTypeRecords TypeRecords;
307
308 // In order to determine which types and/or symbols records should be handled
309 // by the reader, we record record kinds seen by the type and symbol visitors.
310 // At the end of the scopes creation, the '--internal=tag' option will allow
311 // to print the unique record ids collected.
312 LVTypeKinds TypeKinds;
313 LVSymbolKinds SymbolKinds;
314
315 LVShared(LVCodeViewReader *Reader, LVLogicalVisitor *Visitor)
316 : Reader(Reader), Visitor(Visitor), NamespaceDeduction(this),
317 TypeRecords(this) {}
318 ~LVShared() = default;
319};
320} // namespace logicalview
321} // namespace llvm
322
323void LVTypeRecords::add(uint32_t StreamIdx, TypeIndex TI, TypeLeafKind Kind,
324 LVElement *Element) {
325 RecordTable &Target =
326 (StreamIdx == StreamTPI) ? RecordFromTypes : RecordFromIds;
327 Target.emplace(args: std::piecewise_construct, args: std::forward_as_tuple(args&: TI),
328 args: std::forward_as_tuple(args&: Kind, args&: Element));
329}
330
331void LVTypeRecords::add(uint32_t StreamIdx, TypeIndex TI, StringRef Name) {
332 NameTable &Target = (StreamIdx == StreamTPI) ? NameFromTypes : NameFromIds;
333 Target.emplace(args&: Name, args&: TI);
334}
335
336LVElement *LVTypeRecords::find(uint32_t StreamIdx, TypeIndex TI, bool Create) {
337 RecordTable &Target =
338 (StreamIdx == StreamTPI) ? RecordFromTypes : RecordFromIds;
339
340 LVElement *Element = nullptr;
341 RecordTable::iterator Iter = Target.find(x: TI);
342 if (Iter != Target.end()) {
343 Element = Iter->second.second;
344 if (Element || !Create)
345 return Element;
346
347 // Create the logical element if not found.
348 Element = Shared->Visitor->createElement(Kind: Iter->second.first);
349 if (Element) {
350 Element->setOffset(TI.getIndex());
351 Element->setOffsetFromTypeIndex();
352 Target[TI].second = Element;
353 }
354 }
355 return Element;
356}
357
358TypeIndex LVTypeRecords::find(uint32_t StreamIdx, StringRef Name) {
359 NameTable &Target = (StreamIdx == StreamTPI) ? NameFromTypes : NameFromIds;
360 NameTable::iterator Iter = Target.find(x: Name);
361 return Iter != Target.end() ? Iter->second : TypeIndex::None();
362}
363
364void LVStringRecords::addFilenames() {
365 for (StringIds::const_reference Entry : Strings) {
366 StringRef Name = std::get<1>(t: Entry.second);
367 LVScopeCompileUnit *Scope = std::get<2>(t: Entry.second);
368 Scope->addFilename(Name: transformPath(Path: Name));
369 }
370 Strings.clear();
371}
372
373void LVStringRecords::addFilenames(LVScopeCompileUnit *Scope) {
374 for (StringIds::reference Entry : Strings)
375 if (!std::get<2>(t&: Entry.second))
376 std::get<2>(t&: Entry.second) = Scope;
377}
378
379void LVNamespaceDeduction::add(StringRef String) {
380 StringRef InnerComponent;
381 StringRef OuterComponent;
382 std::tie(args&: OuterComponent, args&: InnerComponent) = getInnerComponent(Name: String);
383 DeducedScopes.insert(x: InnerComponent);
384 if (OuterComponent.size())
385 UnresolvedScopes.insert(x: OuterComponent);
386}
387
388void LVNamespaceDeduction::init() {
389 // We have 2 sets of names:
390 // - deduced scopes (class, structure, union and enum) and
391 // - unresolved scopes, that can represent namespaces or any deduced.
392 // Before creating the namespaces, we have to traverse the unresolved
393 // and remove any references to already deduced scopes.
394 LVStringRefs Components;
395 for (const StringRef &Unresolved : UnresolvedScopes) {
396 Components = getAllLexicalComponents(Name: Unresolved);
397 for (const StringRef &Component : Components) {
398 LookupSet::iterator Iter = DeducedScopes.find(x: Component);
399 if (Iter == DeducedScopes.end())
400 IdentifiedNamespaces.insert(x: Component);
401 }
402 }
403
404 LLVM_DEBUG({
405 auto Print = [&](LookupSet &Container, const char *Title) {
406 auto Header = [&]() {
407 dbgs() << formatv("\n{0}\n", fmt_repeat('=', 72));
408 dbgs() << formatv("{0}\n", Title);
409 dbgs() << formatv("{0}\n", fmt_repeat('=', 72));
410 };
411 Header();
412 for (const StringRef &Item : Container)
413 dbgs() << formatv("'{0}'\n", Item.str().c_str());
414 };
415
416 Print(DeducedScopes, "Deducted Scopes");
417 Print(UnresolvedScopes, "Unresolved Scopes");
418 Print(IdentifiedNamespaces, "Namespaces");
419 });
420}
421
422LVScope *LVNamespaceDeduction::get(LVStringRefs Components) {
423 LLVM_DEBUG({
424 for (const StringRef &Component : Components)
425 dbgs() << formatv("'{0}'\n", Component.str().c_str());
426 });
427
428 if (Components.empty())
429 return nullptr;
430
431 // Update the namespaces relationship.
432 LVScope *Namespace = nullptr;
433 LVScope *Parent = Shared->Reader->getCompileUnit();
434 for (const StringRef &Component : Components) {
435 // Check if we have seen the namespace.
436 Namespace = find(Name: Component);
437 if (!Namespace) {
438 // We have identified namespaces that are generated by MSVC. Mark them
439 // as 'system' so they will be excluded from the logical view.
440 Namespace = Shared->Reader->createScopeNamespace();
441 Namespace->setTag(dwarf::DW_TAG_namespace);
442 Namespace->setName(Component);
443 Parent->addElement(Scope: Namespace);
444 getReader().isSystemEntry(Element: Namespace);
445 add(Name: Component, Namespace);
446 }
447 Parent = Namespace;
448 }
449 return Parent;
450}
451
452LVScope *LVNamespaceDeduction::get(StringRef ScopedName, bool CheckScope) {
453 LVStringRefs Components = getAllLexicalComponents(Name: ScopedName);
454 if (CheckScope)
455 llvm::erase_if(C&: Components, P: [&](StringRef Component) {
456 LookupSet::iterator Iter = IdentifiedNamespaces.find(x: Component);
457 return Iter == IdentifiedNamespaces.end();
458 });
459
460 LLVM_DEBUG(
461 { dbgs() << formatv("ScopedName: '{0}'\n", ScopedName.str().c_str()); });
462
463 return get(Components);
464}
465
466#undef DEBUG_TYPE
467#define DEBUG_TYPE "CodeViewTypeVisitor"
468
469//===----------------------------------------------------------------------===//
470// TypeRecord traversal.
471//===----------------------------------------------------------------------===//
472void LVTypeVisitor::printTypeIndex(StringRef FieldName, TypeIndex TI,
473 uint32_t StreamIdx) const {
474 codeview::printTypeIndex(Printer&: W, FieldName, TI,
475 Types&: StreamIdx == StreamTPI ? Types : Ids);
476}
477
478Error LVTypeVisitor::visitTypeBegin(CVType &Record) {
479 return visitTypeBegin(Record, TI: TypeIndex::fromArrayIndex(Index: Types.size()));
480}
481
482Error LVTypeVisitor::visitTypeBegin(CVType &Record, TypeIndex TI) {
483 LLVM_DEBUG({
484 W.getOStream() << formatTypeLeafKind(Record.kind());
485 W.getOStream() << " (" << HexNumber(TI.getIndex()) << ")\n";
486 });
487
488 if (options().getInternalTag())
489 Shared->TypeKinds.insert(x: Record.kind());
490
491 // The collected type records, will be use to create the logical elements
492 // during the symbols traversal when a type is referenced.
493 CurrentTypeIndex = TI;
494 Shared->TypeRecords.add(StreamIdx, TI, Kind: Record.kind());
495 return Error::success();
496}
497
498Error LVTypeVisitor::visitUnknownType(CVType &Record) {
499 LLVM_DEBUG({ W.printNumber("Length", uint32_t(Record.content().size())); });
500 return Error::success();
501}
502
503Error LVTypeVisitor::visitMemberBegin(CVMemberRecord &Record) {
504 LLVM_DEBUG({
505 W.startLine() << formatTypeLeafKind(Record.Kind);
506 W.getOStream() << " {\n";
507 W.indent();
508 });
509 return Error::success();
510}
511
512Error LVTypeVisitor::visitMemberEnd(CVMemberRecord &Record) {
513 LLVM_DEBUG({
514 W.unindent();
515 W.startLine() << "}\n";
516 });
517 return Error::success();
518}
519
520Error LVTypeVisitor::visitUnknownMember(CVMemberRecord &Record) {
521 LLVM_DEBUG({ W.printHex("UnknownMember", unsigned(Record.Kind)); });
522 return Error::success();
523}
524
525// LF_BUILDINFO (TPI)/(IPI)
526Error LVTypeVisitor::visitKnownRecord(CVType &Record, BuildInfoRecord &Args) {
527 // All the args are references into the TPI/IPI stream.
528 LLVM_DEBUG({
529 W.printNumber("NumArgs", static_cast<uint32_t>(Args.getArgs().size()));
530 ListScope Arguments(W, "Arguments");
531 for (TypeIndex Arg : Args.getArgs())
532 printTypeIndex("ArgType", Arg, StreamIPI);
533 });
534
535 // Only add the strings that hold information about filenames. They will be
536 // used to complete the line/file information for the logical elements.
537 // There are other strings holding information about namespaces.
538 TypeIndex TI;
539 StringRef String;
540
541 // Absolute CWD path
542 TI = Args.getArgs()[BuildInfoRecord::BuildInfoArg::CurrentDirectory];
543 String = Ids.getTypeName(Index: TI);
544 if (!String.empty())
545 Shared->StringRecords.add(TI, String);
546
547 // Get the compile unit name.
548 TI = Args.getArgs()[BuildInfoRecord::BuildInfoArg::SourceFile];
549 String = Ids.getTypeName(Index: TI);
550 if (!String.empty())
551 Shared->StringRecords.add(TI, String);
552 LogicalVisitor->setCompileUnitName(std::string(String));
553
554 return Error::success();
555}
556
557// LF_CLASS, LF_STRUCTURE, LF_INTERFACE (TPI)
558Error LVTypeVisitor::visitKnownRecord(CVType &Record, ClassRecord &Class) {
559 LLVM_DEBUG({
560 printTypeIndex("TypeIndex", CurrentTypeIndex, StreamTPI);
561 printTypeIndex("FieldListType", Class.getFieldList(), StreamTPI);
562 W.printString("Name", Class.getName());
563 });
564
565 // Collect class name for scope deduction.
566 Shared->NamespaceDeduction.add(String: Class.getName());
567 Shared->ForwardReferences.record(IsForwardRef: Class.isForwardRef(), Name: Class.getName(),
568 TI: CurrentTypeIndex);
569
570 // Collect class name for contained scopes deduction.
571 Shared->TypeRecords.add(StreamIdx, TI: CurrentTypeIndex, Name: Class.getName());
572 return Error::success();
573}
574
575// LF_ENUM (TPI)
576Error LVTypeVisitor::visitKnownRecord(CVType &Record, EnumRecord &Enum) {
577 LLVM_DEBUG({
578 printTypeIndex("TypeIndex", CurrentTypeIndex, StreamTPI);
579 printTypeIndex("FieldListType", Enum.getFieldList(), StreamTPI);
580 W.printString("Name", Enum.getName());
581 });
582
583 // Collect enum name for scope deduction.
584 Shared->NamespaceDeduction.add(String: Enum.getName());
585 return Error::success();
586}
587
588// LF_FUNC_ID (TPI)/(IPI)
589Error LVTypeVisitor::visitKnownRecord(CVType &Record, FuncIdRecord &Func) {
590 LLVM_DEBUG({
591 printTypeIndex("TypeIndex", CurrentTypeIndex, StreamTPI);
592 printTypeIndex("Type", Func.getFunctionType(), StreamTPI);
593 printTypeIndex("Parent", Func.getParentScope(), StreamTPI);
594 W.printString("Name", Func.getName());
595 });
596
597 // Collect function name for scope deduction.
598 Shared->NamespaceDeduction.add(String: Func.getName());
599 return Error::success();
600}
601
602// LF_PROCEDURE (TPI)
603Error LVTypeVisitor::visitKnownRecord(CVType &Record, ProcedureRecord &Proc) {
604 LLVM_DEBUG({
605 printTypeIndex("TypeIndex", CurrentTypeIndex, StreamTPI);
606 printTypeIndex("ReturnType", Proc.getReturnType(), StreamTPI);
607 W.printNumber("NumParameters", Proc.getParameterCount());
608 printTypeIndex("ArgListType", Proc.getArgumentList(), StreamTPI);
609 });
610
611 // Collect procedure information as they can be referenced by typedefs.
612 Shared->TypeRecords.add(StreamIdx: StreamTPI, TI: CurrentTypeIndex, Kind: {});
613 return Error::success();
614}
615
616// LF_STRING_ID (TPI)/(IPI)
617Error LVTypeVisitor::visitKnownRecord(CVType &Record, StringIdRecord &String) {
618 // No additional references are needed.
619 LLVM_DEBUG({
620 printTypeIndex("Id", String.getId(), StreamIPI);
621 W.printString("StringData", String.getString());
622 });
623 return Error::success();
624}
625
626// LF_UDT_SRC_LINE (TPI)/(IPI)
627Error LVTypeVisitor::visitKnownRecord(CVType &Record,
628 UdtSourceLineRecord &Line) {
629 // UDT and SourceFile are references into the TPI/IPI stream.
630 LLVM_DEBUG({
631 printTypeIndex("UDT", Line.getUDT(), StreamIPI);
632 printTypeIndex("SourceFile", Line.getSourceFile(), StreamIPI);
633 W.printNumber("LineNumber", Line.getLineNumber());
634 });
635
636 Shared->LineRecords.push_back(x: CurrentTypeIndex);
637 return Error::success();
638}
639
640// LF_UNION (TPI)
641Error LVTypeVisitor::visitKnownRecord(CVType &Record, UnionRecord &Union) {
642 LLVM_DEBUG({
643 W.printNumber("MemberCount", Union.getMemberCount());
644 printTypeIndex("FieldList", Union.getFieldList(), StreamTPI);
645 W.printNumber("SizeOf", Union.getSize());
646 W.printString("Name", Union.getName());
647 if (Union.hasUniqueName())
648 W.printString("UniqueName", Union.getUniqueName());
649 });
650
651 // Collect union name for scope deduction.
652 Shared->NamespaceDeduction.add(String: Union.getName());
653 Shared->ForwardReferences.record(IsForwardRef: Union.isForwardRef(), Name: Union.getName(),
654 TI: CurrentTypeIndex);
655
656 // Collect class name for contained scopes deduction.
657 Shared->TypeRecords.add(StreamIdx, TI: CurrentTypeIndex, Name: Union.getName());
658 return Error::success();
659}
660
661#undef DEBUG_TYPE
662#define DEBUG_TYPE "CodeViewSymbolVisitor"
663
664//===----------------------------------------------------------------------===//
665// SymbolRecord traversal.
666//===----------------------------------------------------------------------===//
667void LVSymbolVisitorDelegate::printRelocatedField(StringRef Label,
668 uint32_t RelocOffset,
669 uint32_t Offset,
670 StringRef *RelocSym) {
671 Reader->printRelocatedField(Label, CoffSection, RelocOffset, Offset,
672 RelocSym);
673}
674
675void LVSymbolVisitorDelegate::getLinkageName(uint32_t RelocOffset,
676 uint32_t Offset,
677 StringRef *RelocSym) {
678 Reader->getLinkageName(CoffSection, RelocOffset, Offset, RelocSym);
679}
680
681StringRef
682LVSymbolVisitorDelegate::getFileNameForFileOffset(uint32_t FileOffset) {
683 Expected<StringRef> Name = Reader->getFileNameForFileOffset(FileOffset);
684 if (!Name) {
685 consumeError(Err: Name.takeError());
686 return {};
687 }
688 return *Name;
689}
690
691DebugStringTableSubsectionRef LVSymbolVisitorDelegate::getStringTable() {
692 return Reader->CVStringTable;
693}
694
695void LVSymbolVisitor::printLocalVariableAddrRange(
696 const LocalVariableAddrRange &Range, uint32_t RelocationOffset) {
697 DictScope S(W, "LocalVariableAddrRange");
698 if (ObjDelegate)
699 ObjDelegate->printRelocatedField(Label: "OffsetStart", RelocOffset: RelocationOffset,
700 Offset: Range.OffsetStart);
701 W.printHex(Label: "ISectStart", Value: Range.ISectStart);
702 W.printHex(Label: "Range", Value: Range.Range);
703}
704
705void LVSymbolVisitor::printLocalVariableAddrGap(
706 ArrayRef<LocalVariableAddrGap> Gaps) {
707 for (const LocalVariableAddrGap &Gap : Gaps) {
708 ListScope S(W, "LocalVariableAddrGap");
709 W.printHex(Label: "GapStartOffset", Value: Gap.GapStartOffset);
710 W.printHex(Label: "Range", Value: Gap.Range);
711 }
712}
713
714void LVSymbolVisitor::printTypeIndex(StringRef FieldName, TypeIndex TI) const {
715 codeview::printTypeIndex(Printer&: W, FieldName, TI, Types);
716}
717
718Error LVSymbolVisitor::visitSymbolBegin(CVSymbol &Record) {
719 return visitSymbolBegin(Record, Offset: 0);
720}
721
722Error LVSymbolVisitor::visitSymbolBegin(CVSymbol &Record, uint32_t Offset) {
723 SymbolKind Kind = Record.kind();
724 LLVM_DEBUG({
725 W.printNumber("Offset", Offset);
726 W.printEnum("Begin Kind", unsigned(Kind), getSymbolTypeNames());
727 });
728
729 if (options().getInternalTag())
730 Shared->SymbolKinds.insert(x: Kind);
731
732 LogicalVisitor->CurrentElement = LogicalVisitor->createElement(Kind);
733 if (!LogicalVisitor->CurrentElement) {
734 LLVM_DEBUG({
735 // We have an unsupported Symbol or Type Record.
736 // W.printEnum("Kind ignored", unsigned(Kind), getSymbolTypeNames());
737 });
738 return Error::success();
739 }
740
741 // Offset carried by the traversal routines when dealing with streams.
742 CurrentOffset = Offset;
743 IsCompileUnit = false;
744 if (!LogicalVisitor->CurrentElement->getOffsetFromTypeIndex())
745 LogicalVisitor->CurrentElement->setOffset(Offset);
746 if (symbolOpensScope(Kind) || (IsCompileUnit = symbolIsCompileUnit(Kind))) {
747 assert(LogicalVisitor->CurrentScope && "Invalid scope!");
748 LogicalVisitor->addElement(Scope: LogicalVisitor->CurrentScope, IsCompileUnit);
749 } else {
750 if (LogicalVisitor->CurrentSymbol)
751 LogicalVisitor->addElement(Symbol: LogicalVisitor->CurrentSymbol);
752 if (LogicalVisitor->CurrentType)
753 LogicalVisitor->addElement(Type: LogicalVisitor->CurrentType);
754 }
755
756 return Error::success();
757}
758
759Error LVSymbolVisitor::visitSymbolEnd(CVSymbol &Record) {
760 SymbolKind Kind = Record.kind();
761 LLVM_DEBUG(
762 { W.printEnum("End Kind", unsigned(Kind), getSymbolTypeNames()); });
763
764 if (symbolEndsScope(Kind)) {
765 LogicalVisitor->popScope();
766 }
767
768 return Error::success();
769}
770
771Error LVSymbolVisitor::visitUnknownSymbol(CVSymbol &Record) {
772 LLVM_DEBUG({ W.printNumber("Length", Record.length()); });
773 return Error::success();
774}
775
776// S_BLOCK32
777Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record, BlockSym &Block) {
778 LLVM_DEBUG({
779 W.printHex("CodeSize", Block.CodeSize);
780 W.printHex("Segment", Block.Segment);
781 W.printString("BlockName", Block.Name);
782 });
783
784 if (LVScope *Scope = LogicalVisitor->CurrentScope) {
785 StringRef LinkageName;
786 if (ObjDelegate)
787 ObjDelegate->getLinkageName(RelocOffset: Block.getRelocationOffset(), Offset: Block.CodeOffset,
788 RelocSym: &LinkageName);
789 Scope->setLinkageName(LinkageName);
790
791 if (options().getGeneralCollectRanges()) {
792 // Record converted segment::offset addressing for this scope.
793 LVAddress Addendum = Reader->getSymbolTableAddress(Name: LinkageName);
794 LVAddress LowPC =
795 Reader->linearAddress(Segment: Block.Segment, Offset: Block.CodeOffset, Addendum);
796 LVAddress HighPC = LowPC + Block.CodeSize - 1;
797 Scope->addObject(LowerAddress: LowPC, UpperAddress: HighPC);
798 }
799 }
800
801 return Error::success();
802}
803
804// S_BPREL32
805Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
806 BPRelativeSym &Local) {
807 LLVM_DEBUG({
808 printTypeIndex("Type", Local.Type);
809 W.printNumber("Offset", Local.Offset);
810 W.printString("VarName", Local.Name);
811 });
812
813 if (LVSymbol *Symbol = LogicalVisitor->CurrentSymbol) {
814 Symbol->setName(Local.Name);
815 // From the MS_Symbol_Type.pdf documentation (S_BPREL32):
816 // This symbol specifies symbols that are allocated on the stack for a
817 // procedure. For C and C++, these include the actual function parameters
818 // and the local non-static variables of functions.
819 // However, the offset for 'this' comes as a negative value.
820
821 // Symbol was created as 'variable'; determine its real kind.
822 Symbol->resetIsVariable();
823
824 if (Local.Name == "this") {
825 Symbol->setIsParameter();
826 Symbol->setIsArtificial();
827 } else {
828 // Determine symbol kind.
829 bool(Local.Offset > 0) ? Symbol->setIsParameter()
830 : Symbol->setIsVariable();
831 }
832
833 // Update correct debug information tag.
834 if (Symbol->getIsParameter())
835 Symbol->setTag(dwarf::DW_TAG_formal_parameter);
836
837 setLocalVariableType(Symbol, TI: Local.Type);
838 }
839
840 return Error::success();
841}
842
843// S_REGREL32
844Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
845 RegRelativeSym &Local) {
846 LLVM_DEBUG({
847 printTypeIndex("Type", Local.Type);
848 W.printNumber("Offset", Local.Offset);
849 W.printString("VarName", Local.Name);
850 });
851
852 if (LVSymbol *Symbol = LogicalVisitor->CurrentSymbol) {
853 Symbol->setName(Local.Name);
854
855 // Symbol was created as 'variable'; determine its real kind.
856 Symbol->resetIsVariable();
857
858 // Check for the 'this' symbol.
859 if (Local.Name == "this") {
860 Symbol->setIsArtificial();
861 Symbol->setIsParameter();
862 } else {
863 // Determine symbol kind.
864 determineSymbolKind(Symbol, Register: Local.Register);
865 }
866
867 // Update correct debug information tag.
868 if (Symbol->getIsParameter())
869 Symbol->setTag(dwarf::DW_TAG_formal_parameter);
870
871 setLocalVariableType(Symbol, TI: Local.Type);
872 }
873
874 return Error::success();
875}
876
877// S_REGREL32_INDIR
878Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
879 RegRelativeIndirSym &Local) {
880 LLVM_DEBUG({
881 printTypeIndex("Type", Local.Type);
882 W.printNumber("Offset", Local.Offset);
883 W.printNumber("OffsetInUdt", Local.OffsetInUdt);
884 W.printString("VarName", Local.Name);
885 });
886
887 if (LVSymbol *Symbol = LogicalVisitor->CurrentSymbol) {
888 Symbol->setName(Local.Name);
889
890 // Symbol was created as 'variable'; determine its real kind.
891 Symbol->resetIsVariable();
892
893 // Check for the 'this' symbol.
894 if (Local.Name == "this") {
895 Symbol->setIsArtificial();
896 Symbol->setIsParameter();
897 } else {
898 // Determine symbol kind.
899 determineSymbolKind(Symbol, Register: Local.Register);
900 }
901
902 // Update correct debug information tag.
903 if (Symbol->getIsParameter())
904 Symbol->setTag(dwarf::DW_TAG_formal_parameter);
905
906 setLocalVariableType(Symbol, TI: Local.Type);
907 }
908
909 return Error::success();
910}
911
912// S_BUILDINFO
913Error LVSymbolVisitor::visitKnownRecord(CVSymbol &CVR,
914 BuildInfoSym &BuildInfo) {
915 LLVM_DEBUG({ printTypeIndex("BuildId", BuildInfo.BuildId); });
916
917 CVType CVBuildType = Ids.getType(Index: BuildInfo.BuildId);
918 if (Error Err = LogicalVisitor->finishVisitation(
919 Record&: CVBuildType, TI: BuildInfo.BuildId, Element: Reader->getCompileUnit()))
920 return Err;
921
922 return Error::success();
923}
924
925// S_COMPILE2
926Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
927 Compile2Sym &Compile2) {
928 LLVM_DEBUG({
929 W.printEnum("Language", uint8_t(Compile2.getLanguage()),
930 getSourceLanguageNames());
931 W.printFlags("Flags", uint32_t(Compile2.getFlags()),
932 getCompileSym3FlagNames());
933 W.printEnum("Machine", unsigned(Compile2.Machine), getCPUTypeNames());
934 W.printString("VersionName", Compile2.Version);
935 });
936
937 // MSVC generates the following sequence for a CodeView module:
938 // S_OBJNAME --> Set 'CurrentObjectName'.
939 // S_COMPILE2 --> Set the compile unit name using 'CurrentObjectName'.
940 // ...
941 // S_BUILDINFO --> Extract the source name.
942 //
943 // Clang generates the following sequence for a CodeView module:
944 // S_COMPILE2 --> Set the compile unit name to empty string.
945 // ...
946 // S_BUILDINFO --> Extract the source name.
947 //
948 // For both toolchains, update the compile unit name from S_BUILDINFO.
949 if (LVScope *Scope = LogicalVisitor->CurrentScope) {
950 // The name of the CU, was extracted from the 'BuildInfo' subsection.
951 Reader->setCompileUnitCPUType(Compile2.Machine);
952 Scope->setName(CurrentObjectName);
953 if (options().getAttributeProducer())
954 Scope->setProducer(Compile2.Version);
955 if (options().getAttributeLanguage())
956 Scope->setSourceLanguage(LVSourceLanguage{
957 static_cast<llvm::codeview::SourceLanguage>(Compile2.getLanguage())});
958 getReader().isSystemEntry(Element: Scope, Name: CurrentObjectName);
959
960 // The line records in CodeView are recorded per Module ID. Update
961 // the relationship between the current CU and the Module ID.
962 Reader->addModule(Scope);
963
964 // Updated the collected strings with their associated compile unit.
965 Shared->StringRecords.addFilenames(Scope: Reader->getCompileUnit());
966 }
967
968 // Clear any previous ObjectName.
969 CurrentObjectName = "";
970 return Error::success();
971}
972
973// S_COMPILE3
974Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
975 Compile3Sym &Compile3) {
976 LLVM_DEBUG({
977 W.printEnum("Language", uint8_t(Compile3.getLanguage()),
978 getSourceLanguageNames());
979 W.printFlags("Flags", uint32_t(Compile3.getFlags()),
980 getCompileSym3FlagNames());
981 W.printEnum("Machine", unsigned(Compile3.Machine), getCPUTypeNames());
982 W.printString("VersionName", Compile3.Version);
983 });
984
985 // MSVC generates the following sequence for a CodeView module:
986 // S_OBJNAME --> Set 'CurrentObjectName'.
987 // S_COMPILE3 --> Set the compile unit name using 'CurrentObjectName'.
988 // ...
989 // S_BUILDINFO --> Extract the source name.
990 //
991 // Clang generates the following sequence for a CodeView module:
992 // S_COMPILE3 --> Set the compile unit name to empty string.
993 // ...
994 // S_BUILDINFO --> Extract the source name.
995 //
996 // For both toolchains, update the compile unit name from S_BUILDINFO.
997 if (LVScope *Scope = LogicalVisitor->CurrentScope) {
998 // The name of the CU, was extracted from the 'BuildInfo' subsection.
999 Reader->setCompileUnitCPUType(Compile3.Machine);
1000 Scope->setName(CurrentObjectName);
1001 if (options().getAttributeProducer())
1002 Scope->setProducer(Compile3.Version);
1003 if (options().getAttributeLanguage())
1004 Scope->setSourceLanguage(LVSourceLanguage{
1005 static_cast<llvm::codeview::SourceLanguage>(Compile3.getLanguage())});
1006 getReader().isSystemEntry(Element: Scope, Name: CurrentObjectName);
1007
1008 // The line records in CodeView are recorded per Module ID. Update
1009 // the relationship between the current CU and the Module ID.
1010 Reader->addModule(Scope);
1011
1012 // Updated the collected strings with their associated compile unit.
1013 Shared->StringRecords.addFilenames(Scope: Reader->getCompileUnit());
1014 }
1015
1016 // Clear any previous ObjectName.
1017 CurrentObjectName = "";
1018 return Error::success();
1019}
1020
1021// S_CONSTANT, S_MANCONSTANT
1022Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
1023 ConstantSym &Constant) {
1024 LLVM_DEBUG({
1025 printTypeIndex("Type", Constant.Type);
1026 W.printNumber("Value", Constant.Value);
1027 W.printString("Name", Constant.Name);
1028 });
1029
1030 if (LVSymbol *Symbol = LogicalVisitor->CurrentSymbol) {
1031 Symbol->setName(Constant.Name);
1032 Symbol->setType(LogicalVisitor->getElement(StreamIdx: StreamTPI, TI: Constant.Type));
1033 Symbol->resetIncludeInPrint();
1034 }
1035
1036 return Error::success();
1037}
1038
1039// S_DEFRANGE_FRAMEPOINTER_REL_FULL_SCOPE
1040Error LVSymbolVisitor::visitKnownRecord(
1041 CVSymbol &Record,
1042 DefRangeFramePointerRelFullScopeSym &DefRangeFramePointerRelFullScope) {
1043 // DefRanges don't have types, just registers and code offsets.
1044 LLVM_DEBUG({
1045 if (LocalSymbol)
1046 W.getOStream() << formatv("Symbol: {0}, ", LocalSymbol->getName());
1047
1048 W.printNumber("Offset", DefRangeFramePointerRelFullScope.Offset);
1049 });
1050
1051 if (LVSymbol *Symbol = LocalSymbol) {
1052 Symbol->setHasCodeViewLocation();
1053 LocalSymbol = nullptr;
1054
1055 // Add location debug location. Operands: [Offset, 0].
1056 dwarf::Attribute Attr =
1057 dwarf::Attribute(SymbolKind::S_DEFRANGE_FRAMEPOINTER_REL_FULL_SCOPE);
1058
1059 uint64_t Operand1 = DefRangeFramePointerRelFullScope.Offset;
1060 Symbol->addLocation(Attr, LowPC: 0, HighPC: 0, SectionOffset: 0, LocDescOffset: 0);
1061 Symbol->addLocationOperands(Opcode: LVSmall(Attr), Operands: {Operand1});
1062 }
1063
1064 return Error::success();
1065}
1066
1067// S_DEFRANGE_FRAMEPOINTER_REL
1068Error LVSymbolVisitor::visitKnownRecord(
1069 CVSymbol &Record, DefRangeFramePointerRelSym &DefRangeFramePointerRel) {
1070 // DefRanges don't have types, just registers and code offsets.
1071 LLVM_DEBUG({
1072 if (LocalSymbol)
1073 W.getOStream() << formatv("Symbol: {0}, ", LocalSymbol->getName());
1074
1075 W.printNumber("Offset", DefRangeFramePointerRel.Hdr.Offset);
1076 printLocalVariableAddrRange(DefRangeFramePointerRel.Range,
1077 DefRangeFramePointerRel.getRelocationOffset());
1078 printLocalVariableAddrGap(DefRangeFramePointerRel.Gaps);
1079 });
1080
1081 // We are expecting the following sequence:
1082 // 128 | S_LOCAL [size = 20] `ParamBar`
1083 // ...
1084 // 148 | S_DEFRANGE_FRAMEPOINTER_REL [size = 16]
1085 if (LVSymbol *Symbol = LocalSymbol) {
1086 Symbol->setHasCodeViewLocation();
1087 LocalSymbol = nullptr;
1088
1089 // Add location debug location. Operands: [Offset, 0].
1090 dwarf::Attribute Attr =
1091 dwarf::Attribute(SymbolKind::S_DEFRANGE_FRAMEPOINTER_REL);
1092 uint64_t Operand1 = DefRangeFramePointerRel.Hdr.Offset;
1093
1094 LocalVariableAddrRange Range = DefRangeFramePointerRel.Range;
1095 LVAddress Address =
1096 Reader->linearAddress(Segment: Range.ISectStart, Offset: Range.OffsetStart);
1097
1098 Symbol->addLocation(Attr, LowPC: Address, HighPC: Address + Range.Range, SectionOffset: 0, LocDescOffset: 0);
1099 Symbol->addLocationOperands(Opcode: LVSmall(Attr), Operands: {Operand1});
1100 }
1101
1102 return Error::success();
1103}
1104
1105// S_DEFRANGE_REGISTER_REL
1106Error LVSymbolVisitor::visitKnownRecord(
1107 CVSymbol &Record, DefRangeRegisterRelSym &DefRangeRegisterRel) {
1108 // DefRanges don't have types, just registers and code offsets.
1109 LLVM_DEBUG({
1110 if (LocalSymbol)
1111 W.getOStream() << formatv("Symbol: {0}, ", LocalSymbol->getName());
1112
1113 W.printBoolean("HasSpilledUDTMember",
1114 DefRangeRegisterRel.hasSpilledUDTMember());
1115 W.printNumber("OffsetInParent", DefRangeRegisterRel.offsetInParent());
1116 W.printNumber("BasePointerOffset",
1117 DefRangeRegisterRel.Hdr.BasePointerOffset);
1118 printLocalVariableAddrRange(DefRangeRegisterRel.Range,
1119 DefRangeRegisterRel.getRelocationOffset());
1120 printLocalVariableAddrGap(DefRangeRegisterRel.Gaps);
1121 });
1122
1123 if (LVSymbol *Symbol = LocalSymbol) {
1124 Symbol->setHasCodeViewLocation();
1125 LocalSymbol = nullptr;
1126
1127 // Add location debug location. Operands: [Register, Offset].
1128 dwarf::Attribute Attr =
1129 dwarf::Attribute(SymbolKind::S_DEFRANGE_REGISTER_REL);
1130 uint64_t Operand1 = DefRangeRegisterRel.Hdr.Register;
1131 uint64_t Operand2 = DefRangeRegisterRel.Hdr.BasePointerOffset;
1132
1133 LocalVariableAddrRange Range = DefRangeRegisterRel.Range;
1134 LVAddress Address =
1135 Reader->linearAddress(Segment: Range.ISectStart, Offset: Range.OffsetStart);
1136
1137 Symbol->addLocation(Attr, LowPC: Address, HighPC: Address + Range.Range, SectionOffset: 0, LocDescOffset: 0);
1138 Symbol->addLocationOperands(Opcode: LVSmall(Attr), Operands: {Operand1, Operand2});
1139 }
1140
1141 return Error::success();
1142}
1143
1144// S_DEFRANGE_REGISTER
1145Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
1146 DefRangeRegisterSym &DefRangeRegister) {
1147 // DefRanges don't have types, just registers and code offsets.
1148 LLVM_DEBUG({
1149 if (LocalSymbol)
1150 W.getOStream() << formatv("Symbol: {0}, ", LocalSymbol->getName());
1151
1152 W.printEnum("Register", uint16_t(DefRangeRegister.Hdr.Register),
1153 getRegisterNames(Reader->getCompileUnitCPUType()));
1154 W.printNumber("MayHaveNoName", DefRangeRegister.Hdr.MayHaveNoName);
1155 printLocalVariableAddrRange(DefRangeRegister.Range,
1156 DefRangeRegister.getRelocationOffset());
1157 printLocalVariableAddrGap(DefRangeRegister.Gaps);
1158 });
1159
1160 if (LVSymbol *Symbol = LocalSymbol) {
1161 Symbol->setHasCodeViewLocation();
1162 LocalSymbol = nullptr;
1163
1164 // Add location debug location. Operands: [Register, 0].
1165 dwarf::Attribute Attr = dwarf::Attribute(SymbolKind::S_DEFRANGE_REGISTER);
1166 uint64_t Operand1 = DefRangeRegister.Hdr.Register;
1167
1168 LocalVariableAddrRange Range = DefRangeRegister.Range;
1169 LVAddress Address =
1170 Reader->linearAddress(Segment: Range.ISectStart, Offset: Range.OffsetStart);
1171
1172 Symbol->addLocation(Attr, LowPC: Address, HighPC: Address + Range.Range, SectionOffset: 0, LocDescOffset: 0);
1173 Symbol->addLocationOperands(Opcode: LVSmall(Attr), Operands: {Operand1});
1174 }
1175
1176 return Error::success();
1177}
1178
1179// S_DEFRANGE_SUBFIELD_REGISTER
1180Error LVSymbolVisitor::visitKnownRecord(
1181 CVSymbol &Record, DefRangeSubfieldRegisterSym &DefRangeSubfieldRegister) {
1182 // DefRanges don't have types, just registers and code offsets.
1183 LLVM_DEBUG({
1184 if (LocalSymbol)
1185 W.getOStream() << formatv("Symbol: {0}, ", LocalSymbol->getName());
1186
1187 W.printEnum("Register", uint16_t(DefRangeSubfieldRegister.Hdr.Register),
1188 getRegisterNames(Reader->getCompileUnitCPUType()));
1189 W.printNumber("MayHaveNoName", DefRangeSubfieldRegister.Hdr.MayHaveNoName);
1190 W.printNumber("OffsetInParent",
1191 DefRangeSubfieldRegister.Hdr.OffsetInParent);
1192 printLocalVariableAddrRange(DefRangeSubfieldRegister.Range,
1193 DefRangeSubfieldRegister.getRelocationOffset());
1194 printLocalVariableAddrGap(DefRangeSubfieldRegister.Gaps);
1195 });
1196
1197 if (LVSymbol *Symbol = LocalSymbol) {
1198 Symbol->setHasCodeViewLocation();
1199 LocalSymbol = nullptr;
1200
1201 // Add location debug location. Operands: [Register, 0].
1202 dwarf::Attribute Attr =
1203 dwarf::Attribute(SymbolKind::S_DEFRANGE_SUBFIELD_REGISTER);
1204 uint64_t Operand1 = DefRangeSubfieldRegister.Hdr.Register;
1205
1206 LocalVariableAddrRange Range = DefRangeSubfieldRegister.Range;
1207 LVAddress Address =
1208 Reader->linearAddress(Segment: Range.ISectStart, Offset: Range.OffsetStart);
1209
1210 Symbol->addLocation(Attr, LowPC: Address, HighPC: Address + Range.Range, SectionOffset: 0, LocDescOffset: 0);
1211 Symbol->addLocationOperands(Opcode: LVSmall(Attr), Operands: {Operand1});
1212 }
1213
1214 return Error::success();
1215}
1216
1217// S_DEFRANGE_SUBFIELD
1218Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
1219 DefRangeSubfieldSym &DefRangeSubfield) {
1220 // DefRanges don't have types, just registers and code offsets.
1221 LLVM_DEBUG({
1222 if (LocalSymbol)
1223 W.getOStream() << formatv("Symbol: {0}, ", LocalSymbol->getName());
1224
1225 if (ObjDelegate) {
1226 DebugStringTableSubsectionRef Strings = ObjDelegate->getStringTable();
1227 auto ExpectedProgram = Strings.getString(DefRangeSubfield.Program);
1228 if (!ExpectedProgram) {
1229 consumeError(ExpectedProgram.takeError());
1230 return llvm::make_error<CodeViewError>(
1231 "String table offset outside of bounds of String Table!");
1232 }
1233 W.printString("Program", *ExpectedProgram);
1234 }
1235 W.printNumber("OffsetInParent", DefRangeSubfield.OffsetInParent);
1236 printLocalVariableAddrRange(DefRangeSubfield.Range,
1237 DefRangeSubfield.getRelocationOffset());
1238 printLocalVariableAddrGap(DefRangeSubfield.Gaps);
1239 });
1240
1241 if (LVSymbol *Symbol = LocalSymbol) {
1242 Symbol->setHasCodeViewLocation();
1243 LocalSymbol = nullptr;
1244
1245 // Add location debug location. Operands: [Program, 0].
1246 dwarf::Attribute Attr = dwarf::Attribute(SymbolKind::S_DEFRANGE_SUBFIELD);
1247 uint64_t Operand1 = DefRangeSubfield.Program;
1248
1249 LocalVariableAddrRange Range = DefRangeSubfield.Range;
1250 LVAddress Address =
1251 Reader->linearAddress(Segment: Range.ISectStart, Offset: Range.OffsetStart);
1252
1253 Symbol->addLocation(Attr, LowPC: Address, HighPC: Address + Range.Range, SectionOffset: 0, LocDescOffset: 0);
1254 Symbol->addLocationOperands(Opcode: LVSmall(Attr), Operands: {Operand1, /*Operand2=*/0});
1255 }
1256
1257 return Error::success();
1258}
1259
1260// S_DEFRANGE
1261Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
1262 DefRangeSym &DefRange) {
1263 // DefRanges don't have types, just registers and code offsets.
1264 LLVM_DEBUG({
1265 if (LocalSymbol)
1266 W.getOStream() << formatv("Symbol: {0}, ", LocalSymbol->getName());
1267
1268 if (ObjDelegate) {
1269 DebugStringTableSubsectionRef Strings = ObjDelegate->getStringTable();
1270 auto ExpectedProgram = Strings.getString(DefRange.Program);
1271 if (!ExpectedProgram) {
1272 consumeError(ExpectedProgram.takeError());
1273 return llvm::make_error<CodeViewError>(
1274 "String table offset outside of bounds of String Table!");
1275 }
1276 W.printString("Program", *ExpectedProgram);
1277 }
1278 printLocalVariableAddrRange(DefRange.Range, DefRange.getRelocationOffset());
1279 printLocalVariableAddrGap(DefRange.Gaps);
1280 });
1281
1282 if (LVSymbol *Symbol = LocalSymbol) {
1283 Symbol->setHasCodeViewLocation();
1284 LocalSymbol = nullptr;
1285
1286 // Add location debug location. Operands: [Program, 0].
1287 dwarf::Attribute Attr = dwarf::Attribute(SymbolKind::S_DEFRANGE);
1288 uint64_t Operand1 = DefRange.Program;
1289
1290 LocalVariableAddrRange Range = DefRange.Range;
1291 LVAddress Address =
1292 Reader->linearAddress(Segment: Range.ISectStart, Offset: Range.OffsetStart);
1293
1294 Symbol->addLocation(Attr, LowPC: Address, HighPC: Address + Range.Range, SectionOffset: 0, LocDescOffset: 0);
1295 Symbol->addLocationOperands(Opcode: LVSmall(Attr), Operands: {Operand1, /*Operand2=*/0});
1296 }
1297
1298 return Error::success();
1299}
1300
1301// S_FRAMEPROC
1302Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
1303 FrameProcSym &FrameProc) {
1304 if (LVScope *Function = LogicalVisitor->getReaderScope()) {
1305 // S_FRAMEPROC contains extra information for the function described
1306 // by any of the previous generated records:
1307 // S_GPROC32, S_LPROC32, S_LPROC32_ID, S_GPROC32_ID.
1308
1309 // The generated sequence is:
1310 // S_GPROC32_ID ...
1311 // S_FRAMEPROC ...
1312
1313 // Collect additional inline flags for the current scope function.
1314 FrameProcedureOptions Flags = FrameProc.Flags;
1315 if (FrameProcedureOptions::MarkedInline ==
1316 (Flags & FrameProcedureOptions::MarkedInline))
1317 Function->setInlineCode(dwarf::DW_INL_declared_inlined);
1318 if (FrameProcedureOptions::Inlined ==
1319 (Flags & FrameProcedureOptions::Inlined))
1320 Function->setInlineCode(dwarf::DW_INL_inlined);
1321
1322 // To determine the symbol kind for any symbol declared in that function,
1323 // we can access the S_FRAMEPROC for the parent scope function. It contains
1324 // information about the local fp and param fp registers and compare with
1325 // the register in the S_REGREL32 to get a match.
1326 codeview::CPUType CPU = Reader->getCompileUnitCPUType();
1327 LocalFrameRegister = FrameProc.getLocalFramePtrReg(CPU);
1328 ParamFrameRegister = FrameProc.getParamFramePtrReg(CPU);
1329 }
1330
1331 return Error::success();
1332}
1333
1334// S_GDATA32, S_LDATA32, S_LMANDATA, S_GMANDATA
1335Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record, DataSym &Data) {
1336 LLVM_DEBUG({
1337 printTypeIndex("Type", Data.Type);
1338 W.printString("DisplayName", Data.Name);
1339 });
1340
1341 if (LVSymbol *Symbol = LogicalVisitor->CurrentSymbol) {
1342 StringRef LinkageName;
1343 if (ObjDelegate)
1344 ObjDelegate->getLinkageName(RelocOffset: Data.getRelocationOffset(), Offset: Data.DataOffset,
1345 RelocSym: &LinkageName);
1346
1347 Symbol->setName(Data.Name);
1348 Symbol->setLinkageName(LinkageName);
1349
1350 // The MSVC generates local data as initialization for aggregates. It
1351 // contains the address for an initialization function.
1352 // The symbols contains the '$initializer$' pattern. Allow them only if
1353 // the '--internal=system' option is given.
1354 // 0 | S_LDATA32 `Struct$initializer$`
1355 // type = 0x1040 (void ()*)
1356 if (getReader().isSystemEntry(Element: Symbol) && !options().getAttributeSystem()) {
1357 Symbol->resetIncludeInPrint();
1358 return Error::success();
1359 }
1360
1361 if (LVScope *Namespace = Shared->NamespaceDeduction.get(ScopedName: Data.Name)) {
1362 // The variable is already at different scope. In order to reflect
1363 // the correct parent, move it to the namespace.
1364 if (Symbol->getParentScope()->removeElement(Element: Symbol))
1365 Namespace->addElement(Symbol);
1366 }
1367
1368 Symbol->setType(LogicalVisitor->getElement(StreamIdx: StreamTPI, TI: Data.Type));
1369 if (Record.kind() == SymbolKind::S_GDATA32)
1370 Symbol->setIsExternal();
1371 }
1372
1373 return Error::success();
1374}
1375
1376// S_INLINESITE
1377Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
1378 InlineSiteSym &InlineSite) {
1379 LLVM_DEBUG({ printTypeIndex("Inlinee", InlineSite.Inlinee); });
1380
1381 if (LVScope *InlinedFunction = LogicalVisitor->CurrentScope) {
1382 LVScope *AbstractFunction = Reader->createScopeFunction();
1383 AbstractFunction->setIsSubprogram();
1384 AbstractFunction->setTag(dwarf::DW_TAG_subprogram);
1385 AbstractFunction->setInlineCode(dwarf::DW_INL_inlined);
1386 AbstractFunction->setIsInlinedAbstract();
1387 InlinedFunction->setReference(AbstractFunction);
1388
1389 LogicalVisitor->startProcessArgumentList();
1390 // 'Inlinee' is a Type ID.
1391 CVType CVFunctionType = Ids.getType(Index: InlineSite.Inlinee);
1392 if (Error Err = LogicalVisitor->finishVisitation(
1393 Record&: CVFunctionType, TI: InlineSite.Inlinee, Element: AbstractFunction))
1394 return Err;
1395 LogicalVisitor->stopProcessArgumentList();
1396
1397 // For inlined functions set the linkage name to be the same as
1398 // the name. It used to find their lines and ranges.
1399 StringRef Name = AbstractFunction->getName();
1400 InlinedFunction->setName(Name);
1401 InlinedFunction->setLinkageName(Name);
1402
1403 // Process annotation bytes to calculate code and line offsets.
1404 if (Error Err = LogicalVisitor->inlineSiteAnnotation(
1405 AbstractFunction, InlinedFunction, InlineSite))
1406 return Err;
1407 }
1408
1409 return Error::success();
1410}
1411
1412// S_LOCAL
1413Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record, LocalSym &Local) {
1414 LLVM_DEBUG({
1415 printTypeIndex("Type", Local.Type);
1416 W.printFlags("Flags", uint16_t(Local.Flags), getLocalFlagNames());
1417 W.printString("VarName", Local.Name);
1418 });
1419
1420 if (LVSymbol *Symbol = LogicalVisitor->CurrentSymbol) {
1421 Symbol->setName(Local.Name);
1422
1423 // Symbol was created as 'variable'; determine its real kind.
1424 Symbol->resetIsVariable();
1425
1426 // Be sure the 'this' symbol is marked as 'compiler generated'.
1427 if (bool(Local.Flags & LocalSymFlags::IsCompilerGenerated) ||
1428 Local.Name == "this") {
1429 Symbol->setIsArtificial();
1430 Symbol->setIsParameter();
1431 } else {
1432 bool(Local.Flags & LocalSymFlags::IsParameter) ? Symbol->setIsParameter()
1433 : Symbol->setIsVariable();
1434 }
1435
1436 // Update correct debug information tag.
1437 if (Symbol->getIsParameter())
1438 Symbol->setTag(dwarf::DW_TAG_formal_parameter);
1439
1440 setLocalVariableType(Symbol, TI: Local.Type);
1441
1442 // The CodeView records (S_DEFFRAME_*) describing debug location for
1443 // this symbol, do not have any direct reference to it. Those records
1444 // are emitted after this symbol. Record the current symbol.
1445 LocalSymbol = Symbol;
1446 }
1447
1448 return Error::success();
1449}
1450
1451// S_OBJNAME
1452Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record, ObjNameSym &ObjName) {
1453 LLVM_DEBUG({
1454 W.printHex("Signature", ObjName.Signature);
1455 W.printString("ObjectName", ObjName.Name);
1456 });
1457
1458 CurrentObjectName = ObjName.Name;
1459 return Error::success();
1460}
1461
1462// S_GPROC32, S_LPROC32, S_LPROC32_ID, S_GPROC32_ID
1463Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record, ProcSym &Proc) {
1464 if (InFunctionScope)
1465 return llvm::make_error<CodeViewError>(Args: "Visiting a ProcSym while inside "
1466 "function scope!");
1467
1468 InFunctionScope = true;
1469
1470 LLVM_DEBUG({
1471 printTypeIndex("FunctionType", Proc.FunctionType);
1472 W.printHex("Segment", Proc.Segment);
1473 W.printFlags("Flags", static_cast<uint8_t>(Proc.Flags),
1474 getProcSymFlagNames());
1475 W.printString("DisplayName", Proc.Name);
1476 });
1477
1478 // Clang and Microsoft generated different debug information records:
1479 // For functions definitions:
1480 // Clang: S_GPROC32 -> LF_FUNC_ID -> LF_PROCEDURE
1481 // Microsoft: S_GPROC32 -> LF_PROCEDURE
1482
1483 // For member function definition:
1484 // Clang: S_GPROC32 -> LF_MFUNC_ID -> LF_MFUNCTION
1485 // Microsoft: S_GPROC32 -> LF_MFUNCTION
1486 // In order to support both sequences, if we found LF_FUNCTION_ID, just
1487 // get the TypeIndex for LF_PROCEDURE.
1488
1489 // For the given test case, we have the sequence:
1490 // namespace NSP_local {
1491 // void foo_local() {
1492 // }
1493 // }
1494 //
1495 // 0x1000 | LF_STRING_ID String: NSP_local
1496 // 0x1002 | LF_PROCEDURE
1497 // return type = 0x0003 (void), # args = 0, param list = 0x1001
1498 // calling conv = cdecl, options = None
1499 // 0x1003 | LF_FUNC_ID
1500 // name = foo_local, type = 0x1002, parent scope = 0x1000
1501 // 0 | S_GPROC32_ID `NSP_local::foo_local`
1502 // type = `0x1003 (foo_local)`
1503 // 0x1004 | LF_STRING_ID String: suite
1504 // 0x1005 | LF_STRING_ID String: suite_local.cpp
1505 //
1506 // The LF_STRING_ID can hold different information:
1507 // 0x1000 - The enclosing namespace.
1508 // 0x1004 - The compile unit directory name.
1509 // 0x1005 - The compile unit name.
1510 //
1511 // Before deducting its scope, we need to evaluate its type and create any
1512 // associated namespaces.
1513 if (LVScope *Function = LogicalVisitor->CurrentScope) {
1514 StringRef LinkageName;
1515 if (ObjDelegate)
1516 ObjDelegate->getLinkageName(RelocOffset: Proc.getRelocationOffset(), Offset: Proc.CodeOffset,
1517 RelocSym: &LinkageName);
1518
1519 // The line table can be accessed using the linkage name.
1520 Reader->addToSymbolTable(Name: LinkageName, Function);
1521 Function->setName(Proc.Name);
1522 Function->setLinkageName(LinkageName);
1523
1524 if (options().getGeneralCollectRanges()) {
1525 // Record converted segment::offset addressing for this scope.
1526 LVAddress Addendum = Reader->getSymbolTableAddress(Name: LinkageName);
1527 LVAddress LowPC =
1528 Reader->linearAddress(Segment: Proc.Segment, Offset: Proc.CodeOffset, Addendum);
1529 LVAddress HighPC = LowPC + Proc.CodeSize - 1;
1530 Function->addObject(LowerAddress: LowPC, UpperAddress: HighPC);
1531
1532 // If the scope is a function, add it to the public names.
1533 if ((options().getAttributePublics() || options().getPrintAnyLine()) &&
1534 !Function->getIsInlinedFunction())
1535 Reader->getCompileUnit()->addPublicName(Scope: Function, LowPC, HighPC);
1536 }
1537
1538 if (Function->getIsSystem() && !options().getAttributeSystem()) {
1539 Function->resetIncludeInPrint();
1540 return Error::success();
1541 }
1542
1543 TypeIndex TIFunctionType = Proc.FunctionType;
1544 if (TIFunctionType.isSimple())
1545 Function->setType(LogicalVisitor->getElement(StreamIdx: StreamTPI, TI: TIFunctionType));
1546 else {
1547 // We have to detect the correct stream, using the lexical parent
1548 // name, as there is not other obvious way to get the stream.
1549 // Normal function: LF_FUNC_ID (TPI)/(IPI)
1550 // LF_PROCEDURE (TPI)
1551 // Lambda function: LF_MFUNCTION (TPI)
1552 // Member function: LF_MFUNC_ID (TPI)/(IPI)
1553
1554 StringRef OuterComponent;
1555 std::tie(args&: OuterComponent, args: std::ignore) = getInnerComponent(Name: Proc.Name);
1556 TypeIndex TI = Shared->ForwardReferences.find(Name: OuterComponent);
1557
1558 std::optional<CVType> CVFunctionType;
1559 auto GetRecordType = [&]() -> bool {
1560 CVFunctionType = Ids.tryGetType(Index: TIFunctionType);
1561 if (!CVFunctionType)
1562 return false;
1563
1564 if (TI.isNoneType())
1565 // Normal function.
1566 if (CVFunctionType->kind() == LF_FUNC_ID)
1567 return true;
1568
1569 // Member function.
1570 return (CVFunctionType->kind() == LF_MFUNC_ID);
1571 };
1572
1573 // We can have a LF_FUNC_ID, LF_PROCEDURE or LF_MFUNCTION.
1574 if (!GetRecordType()) {
1575 CVFunctionType = Types.tryGetType(Index: TIFunctionType);
1576 if (!CVFunctionType)
1577 return llvm::make_error<CodeViewError>(Args: "Invalid type index");
1578 }
1579
1580 if (Error Err = LogicalVisitor->finishVisitation(
1581 Record&: *CVFunctionType, TI: TIFunctionType, Element: Function))
1582 return Err;
1583 }
1584
1585 if (Record.kind() == SymbolKind::S_GPROC32 ||
1586 Record.kind() == SymbolKind::S_GPROC32_ID)
1587 Function->setIsExternal();
1588
1589 // We don't have a way to see if the symbol is compiler generated. Use
1590 // the linkage name, to detect `scalar deleting destructor' functions.
1591 std::string DemangledSymbol = demangle(MangledName: LinkageName);
1592 if (DemangledSymbol.find(s: "scalar deleting dtor") != std::string::npos) {
1593 Function->setIsArtificial();
1594 } else {
1595 // Clang generates global ctor and dtor names containing the substrings:
1596 // 'dynamic initializer for' and 'dynamic atexit destructor for'.
1597 if (DemangledSymbol.find(s: "dynamic atexit destructor for") !=
1598 std::string::npos)
1599 Function->setIsArtificial();
1600 }
1601 }
1602
1603 return Error::success();
1604}
1605
1606// S_END
1607Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
1608 ScopeEndSym &ScopeEnd) {
1609 InFunctionScope = false;
1610 return Error::success();
1611}
1612
1613// S_THUNK32
1614Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record, Thunk32Sym &Thunk) {
1615 if (InFunctionScope)
1616 return llvm::make_error<CodeViewError>(Args: "Visiting a Thunk32Sym while inside "
1617 "function scope!");
1618
1619 InFunctionScope = true;
1620
1621 LLVM_DEBUG({
1622 W.printHex("Segment", Thunk.Segment);
1623 W.printString("Name", Thunk.Name);
1624 });
1625
1626 if (LVScope *Function = LogicalVisitor->CurrentScope)
1627 Function->setName(Thunk.Name);
1628
1629 return Error::success();
1630}
1631
1632// S_UDT, S_COBOLUDT
1633Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record, UDTSym &UDT) {
1634 LLVM_DEBUG({
1635 printTypeIndex("Type", UDT.Type);
1636 W.printString("UDTName", UDT.Name);
1637 });
1638
1639 if (LVType *Type = LogicalVisitor->CurrentType) {
1640 if (LVScope *Namespace = Shared->NamespaceDeduction.get(ScopedName: UDT.Name)) {
1641 if (Type->getParentScope()->removeElement(Element: Type))
1642 Namespace->addElement(Type);
1643 }
1644
1645 Type->setName(UDT.Name);
1646
1647 // We have to determine if the typedef is a real C/C++ definition or is
1648 // the S_UDT record that describe all the user defined types.
1649 // 0 | S_UDT `Name` original type = 0x1009
1650 // 0x1009 | LF_STRUCTURE `Name`
1651 // Ignore type definitions for RTTI types:
1652 // _s__RTTIBaseClassArray, _s__RTTIBaseClassDescriptor,
1653 // _s__RTTICompleteObjectLocator, _s__RTTIClassHierarchyDescriptor.
1654 if (getReader().isSystemEntry(Element: Type))
1655 Type->resetIncludeInPrint();
1656 else {
1657 StringRef RecordName = getRecordName(Types, TI: UDT.Type);
1658 if (UDT.Name == RecordName)
1659 Type->resetIncludeInPrint();
1660 Type->setType(LogicalVisitor->getElement(StreamIdx: StreamTPI, TI: UDT.Type));
1661 }
1662 }
1663
1664 return Error::success();
1665}
1666
1667// S_UNAMESPACE
1668Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
1669 UsingNamespaceSym &UN) {
1670 LLVM_DEBUG({ W.printString("Namespace", UN.Name); });
1671 return Error::success();
1672}
1673
1674// S_ARMSWITCHTABLE
1675Error LVSymbolVisitor::visitKnownRecord(CVSymbol &CVR,
1676 JumpTableSym &JumpTable) {
1677 LLVM_DEBUG({
1678 W.printHex("BaseOffset", JumpTable.BaseOffset);
1679 W.printNumber("BaseSegment", JumpTable.BaseSegment);
1680 W.printFlags("SwitchType", static_cast<uint16_t>(JumpTable.SwitchType),
1681 getJumpTableEntrySizeNames());
1682 W.printHex("BranchOffset", JumpTable.BranchOffset);
1683 W.printHex("TableOffset", JumpTable.TableOffset);
1684 W.printNumber("BranchSegment", JumpTable.BranchSegment);
1685 W.printNumber("TableSegment", JumpTable.TableSegment);
1686 W.printNumber("EntriesCount", JumpTable.EntriesCount);
1687 });
1688 return Error::success();
1689}
1690
1691// S_CALLERS, S_CALLEES, S_INLINEES
1692Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record, CallerSym &Caller) {
1693 LLVM_DEBUG({
1694 llvm::StringRef FieldName;
1695 switch (Caller.getKind()) {
1696 case SymbolRecordKind::CallerSym:
1697 FieldName = "Callee";
1698 break;
1699 case SymbolRecordKind::CalleeSym:
1700 FieldName = "Caller";
1701 break;
1702 case SymbolRecordKind::InlineesSym:
1703 FieldName = "Inlinee";
1704 break;
1705 default:
1706 return llvm::make_error<CodeViewError>(
1707 "Unknown CV Record type for a CallerSym object!");
1708 }
1709 for (auto FuncID : Caller.Indices) {
1710 printTypeIndex(FieldName, FuncID);
1711 }
1712 });
1713 return Error::success();
1714}
1715
1716void LVSymbolVisitor::setLocalVariableType(LVSymbol *Symbol, TypeIndex TI) {
1717 LVElement *Element = LogicalVisitor->getElement(StreamIdx: StreamTPI, TI);
1718 if (Element && Element->getIsScoped()) {
1719 // We have a local type. Find its parent function.
1720 LVScope *Parent = Symbol->getFunctionParent();
1721 // The element representing the type has been already finalized. If
1722 // the type is an aggregate type, its members have been already added.
1723 // As the type is local, its level will be changed.
1724
1725 // FIXME: Currently the algorithm used to scope lambda functions is
1726 // incorrect. Before we allocate the type at this scope, check if is
1727 // already allocated in other scope.
1728 if (!Element->getParentScope()) {
1729 Parent->addElement(Element);
1730 Element->updateLevel(Parent);
1731 }
1732 }
1733 Symbol->setType(Element);
1734}
1735
1736#undef DEBUG_TYPE
1737#define DEBUG_TYPE "CodeViewLogicalVisitor"
1738
1739//===----------------------------------------------------------------------===//
1740// Logical visitor.
1741//===----------------------------------------------------------------------===//
1742LVLogicalVisitor::LVLogicalVisitor(LVCodeViewReader *Reader, ScopedPrinter &W,
1743 InputFile &Input)
1744 : Reader(Reader), W(W), Input(Input) {
1745 // The LogicalVisitor connects the CodeViewReader with the visitors that
1746 // traverse the types, symbols, etc. Do any initialization that is needed.
1747 Shared = std::make_shared<LVShared>(args&: Reader, args: this);
1748}
1749
1750void LVLogicalVisitor::printTypeIndex(StringRef FieldName, TypeIndex TI,
1751 uint32_t StreamIdx) {
1752 codeview::printTypeIndex(Printer&: W, FieldName, TI,
1753 Types&: StreamIdx == StreamTPI ? types() : ids());
1754}
1755
1756void LVLogicalVisitor::printTypeBegin(CVType &Record, TypeIndex TI,
1757 LVElement *Element, uint32_t StreamIdx) {
1758 W.getOStream() << "\n";
1759 W.startLine() << formatTypeLeafKind(K: Record.kind());
1760 W.getOStream() << " (" << HexNumber(TI.getIndex()) << ")";
1761 W.getOStream() << " {\n";
1762 W.indent();
1763 W.printEnum(Label: "TypeLeafKind", Value: unsigned(Record.kind()), EnumValues: ArrayRef(LeafTypeNames));
1764 printTypeIndex(FieldName: "TI", TI, StreamIdx);
1765 W.startLine() << "Element: " << HexNumber(Element->getOffset()) << " "
1766 << Element->getName() << "\n";
1767}
1768
1769void LVLogicalVisitor::printTypeEnd(CVType &Record) {
1770 W.unindent();
1771 W.startLine() << "}\n";
1772}
1773
1774void LVLogicalVisitor::printMemberBegin(CVMemberRecord &Record, TypeIndex TI,
1775 LVElement *Element,
1776 uint32_t StreamIdx) {
1777 W.getOStream() << "\n";
1778 W.startLine() << formatTypeLeafKind(K: Record.Kind);
1779 W.getOStream() << " (" << HexNumber(TI.getIndex()) << ")";
1780 W.getOStream() << " {\n";
1781 W.indent();
1782 W.printEnum(Label: "TypeLeafKind", Value: unsigned(Record.Kind), EnumValues: ArrayRef(LeafTypeNames));
1783 printTypeIndex(FieldName: "TI", TI, StreamIdx);
1784 W.startLine() << "Element: " << HexNumber(Element->getOffset()) << " "
1785 << Element->getName() << "\n";
1786}
1787
1788void LVLogicalVisitor::printMemberEnd(CVMemberRecord &Record) {
1789 W.unindent();
1790 W.startLine() << "}\n";
1791}
1792
1793Error LVLogicalVisitor::visitUnknownType(CVType &Record, TypeIndex TI) {
1794 LLVM_DEBUG({
1795 printTypeIndex("\nTI", TI, StreamTPI);
1796 W.printNumber("Length", uint32_t(Record.content().size()));
1797 });
1798 return Error::success();
1799}
1800
1801// LF_ARGLIST (TPI)
1802Error LVLogicalVisitor::visitKnownRecord(CVType &Record, ArgListRecord &Args,
1803 TypeIndex TI, LVElement *Element) {
1804 ArrayRef<TypeIndex> Indices = Args.getIndices();
1805 uint32_t Size = Indices.size();
1806 LLVM_DEBUG({
1807 printTypeBegin(Record, TI, Element, StreamTPI);
1808 W.printNumber("NumArgs", Size);
1809 ListScope Arguments(W, "Arguments");
1810 for (uint32_t I = 0; I < Size; ++I)
1811 printTypeIndex("ArgType", Indices[I], StreamTPI);
1812 printTypeEnd(Record);
1813 });
1814
1815 LVScope *Function = static_cast<LVScope *>(Element);
1816 for (uint32_t Index = 0; Index < Size; ++Index) {
1817 TypeIndex ParameterType = Indices[Index];
1818 createParameter(TI: ParameterType, Name: StringRef(), Parent: Function);
1819 }
1820
1821 return Error::success();
1822}
1823
1824// LF_ARRAY (TPI)
1825Error LVLogicalVisitor::visitKnownRecord(CVType &Record, ArrayRecord &AT,
1826 TypeIndex TI, LVElement *Element) {
1827 LLVM_DEBUG({
1828 printTypeBegin(Record, TI, Element, StreamTPI);
1829 printTypeIndex("ElementType", AT.getElementType(), StreamTPI);
1830 printTypeIndex("IndexType", AT.getIndexType(), StreamTPI);
1831 W.printNumber("SizeOf", AT.getSize());
1832 W.printString("Name", AT.getName());
1833 printTypeEnd(Record);
1834 });
1835
1836 if (Element->getIsFinalized())
1837 return Error::success();
1838 Element->setIsFinalized();
1839
1840 LVScopeArray *Array = static_cast<LVScopeArray *>(Element);
1841 if (!Array)
1842 return Error::success();
1843
1844 Reader->getCompileUnit()->addElement(Scope: Array);
1845 TypeIndex TIElementType = AT.getElementType();
1846
1847 LVType *PrevSubrange = nullptr;
1848 LazyRandomTypeCollection &Types = types();
1849
1850 // As the logical view is modeled on DWARF, for each dimension we have to
1851 // create a DW_TAG_subrange_type, with dimension size.
1852 // The subrange type can be: unsigned __int32 or unsigned __int64.
1853 auto AddSubrangeType = [&](ArrayRecord &AR) {
1854 LVType *Subrange = Reader->createTypeSubrange();
1855 Subrange->setTag(dwarf::DW_TAG_subrange_type);
1856 Subrange->setType(getElement(StreamIdx: StreamTPI, TI: AR.getIndexType()));
1857 Subrange->setCount(AR.getSize());
1858 Subrange->setOffset(
1859 TIElementType.isSimple()
1860 ? (uint32_t)(TypeLeafKind)TIElementType.getSimpleKind()
1861 : TIElementType.getIndex());
1862 Array->addElement(Type: Subrange);
1863
1864 if (PrevSubrange)
1865 if (int64_t Count = Subrange->getCount())
1866 PrevSubrange->setCount(PrevSubrange->getCount() / Count);
1867 PrevSubrange = Subrange;
1868 };
1869
1870 // Preserve the original TypeIndex; it would be updated in the case of:
1871 // - The array type contains qualifiers.
1872 // - In multidimensional arrays, the last LF_ARRAY entry contains the type.
1873 TypeIndex TIArrayType;
1874
1875 // For each dimension in the array, there is a LF_ARRAY entry. The last
1876 // entry contains the array type, which can be a LF_MODIFIER in the case
1877 // of the type being modified by a qualifier (const, etc).
1878 ArrayRecord AR(AT);
1879 CVType CVEntry = Record;
1880 while (CVEntry.kind() == LF_ARRAY) {
1881 // Create the subrange information, required by the logical view. Once
1882 // the array has been processed, the dimension sizes will updated, as
1883 // the sizes are a progression. For instance:
1884 // sizeof(int) = 4
1885 // int Array[2]; Sizes: 8 Dim: 8 / 4 -> [2]
1886 // int Array[2][3]; Sizes: 24, 12 Dim: 24 / 12 -> [2]
1887 // Dim: 12 / 4 -> [3]
1888 // int Array[2][3][4]; sizes: 96, 48, 16 Dim: 96 / 48 -> [2]
1889 // Dim: 48 / 16 -> [3]
1890 // Dim: 16 / 4 -> [4]
1891 AddSubrangeType(AR);
1892 TIArrayType = TIElementType;
1893
1894 // The current ElementType can be a modifier, in which case we need to
1895 // get the type being modified.
1896 // If TypeIndex is not a simple type, check if we have a qualified type.
1897 if (!TIElementType.isSimple()) {
1898 CVType CVElementType = Types.getType(Index: TIElementType);
1899 if (CVElementType.kind() == LF_MODIFIER) {
1900 LVElement *QualifiedType =
1901 Shared->TypeRecords.find(StreamIdx: StreamTPI, TI: TIElementType);
1902 if (Error Err =
1903 finishVisitation(Record&: CVElementType, TI: TIElementType, Element: QualifiedType))
1904 return Err;
1905 // Get the TypeIndex of the type that the LF_MODIFIER modifies.
1906 TIElementType = getModifiedType(CVT: CVElementType);
1907 }
1908 }
1909 // Ends the traversal, as we have reached a simple type (int, char, etc).
1910 if (TIElementType.isSimple())
1911 break;
1912
1913 // Read next dimension linked entry, if any.
1914 CVEntry = Types.getType(Index: TIElementType);
1915 if (Error Err = TypeDeserializer::deserializeAs(
1916 CVT&: const_cast<CVType &>(CVEntry), Record&: AR)) {
1917 consumeError(Err: std::move(Err));
1918 break;
1919 }
1920 TIElementType = AR.getElementType();
1921 // NOTE: The typeindex has a value of: 0x0280.0000
1922 getTrueType(TI&: TIElementType);
1923 }
1924
1925 Array->setName(AT.getName());
1926 TIArrayType = Shared->ForwardReferences.remap(TI: TIArrayType);
1927 Array->setType(getElement(StreamIdx: StreamTPI, TI: TIArrayType));
1928
1929 if (PrevSubrange)
1930 // In the case of an aggregate type (class, struct, union, interface),
1931 // get the aggregate size. As the original record is pointing to its
1932 // reference, we have to update it.
1933 if (uint64_t Size =
1934 isAggregate(CVT: CVEntry)
1935 ? getSizeInBytesForTypeRecord(CVT: Types.getType(Index: TIArrayType))
1936 : getSizeInBytesForTypeIndex(TI: TIElementType))
1937 PrevSubrange->setCount(PrevSubrange->getCount() / Size);
1938
1939 return Error::success();
1940}
1941
1942// LF_BITFIELD (TPI)
1943Error LVLogicalVisitor::visitKnownRecord(CVType &Record, BitFieldRecord &BF,
1944 TypeIndex TI, LVElement *Element) {
1945 LLVM_DEBUG({
1946 printTypeBegin(Record, TI, Element, StreamTPI);
1947 printTypeIndex("Type", TI, StreamTPI);
1948 W.printNumber("BitSize", BF.getBitSize());
1949 W.printNumber("BitOffset", BF.getBitOffset());
1950 printTypeEnd(Record);
1951 });
1952
1953 Element->setType(getElement(StreamIdx: StreamTPI, TI: BF.getType()));
1954 Element->setBitSize(BF.getBitSize());
1955 return Error::success();
1956}
1957
1958// LF_BUILDINFO (TPI)/(IPI)
1959Error LVLogicalVisitor::visitKnownRecord(CVType &Record, BuildInfoRecord &BI,
1960 TypeIndex TI, LVElement *Element) {
1961 LLVM_DEBUG({
1962 printTypeBegin(Record, TI, Element, StreamIPI);
1963 W.printNumber("NumArgs", static_cast<uint32_t>(BI.getArgs().size()));
1964 ListScope Arguments(W, "Arguments");
1965 for (TypeIndex Arg : BI.getArgs())
1966 printTypeIndex("ArgType", Arg, StreamIPI);
1967 printTypeEnd(Record);
1968 });
1969
1970 // The given 'Element' refers to the current compilation unit.
1971 // All the args are references into the TPI/IPI stream.
1972 TypeIndex TIName = BI.getArgs()[BuildInfoRecord::BuildInfoArg::SourceFile];
1973 std::string Name = std::string(ids().getTypeName(Index: TIName));
1974
1975 // There are cases where LF_BUILDINFO fields are empty.
1976 if (!Name.empty())
1977 Element->setName(Name);
1978
1979 return Error::success();
1980}
1981
1982// LF_CLASS, LF_STRUCTURE, LF_INTERFACE (TPI)
1983Error LVLogicalVisitor::visitKnownRecord(CVType &Record, ClassRecord &Class,
1984 TypeIndex TI, LVElement *Element) {
1985 LLVM_DEBUG({
1986 printTypeBegin(Record, TI, Element, StreamTPI);
1987 W.printNumber("MemberCount", Class.getMemberCount());
1988 printTypeIndex("FieldList", Class.getFieldList(), StreamTPI);
1989 printTypeIndex("DerivedFrom", Class.getDerivationList(), StreamTPI);
1990 printTypeIndex("VShape", Class.getVTableShape(), StreamTPI);
1991 W.printNumber("SizeOf", Class.getSize());
1992 W.printString("Name", Class.getName());
1993 if (Class.hasUniqueName())
1994 W.printString("UniqueName", Class.getUniqueName());
1995 printTypeEnd(Record);
1996 });
1997
1998 if (Element->getIsFinalized())
1999 return Error::success();
2000 Element->setIsFinalized();
2001
2002 LVScopeAggregate *Scope = static_cast<LVScopeAggregate *>(Element);
2003 if (!Scope)
2004 return Error::success();
2005
2006 Scope->setName(Class.getName());
2007 if (Class.hasUniqueName())
2008 Scope->setLinkageName(Class.getUniqueName());
2009 Scope->setBitSize(Class.getSize() * DWARF_CHAR_BIT);
2010
2011 if (Class.isNested()) {
2012 Scope->setIsNested();
2013 createParents(ScopedName: Class.getName(), Element: Scope);
2014 }
2015
2016 if (Class.isScoped())
2017 Scope->setIsScoped();
2018
2019 // Nested types will be added to their parents at creation. The forward
2020 // references are only processed to finish the referenced element creation.
2021 if (!(Class.isNested() || Class.isScoped())) {
2022 if (LVScope *Namespace = Shared->NamespaceDeduction.get(ScopedName: Class.getName()))
2023 Namespace->addElement(Scope);
2024 else
2025 Reader->getCompileUnit()->addElement(Scope);
2026 }
2027
2028 LazyRandomTypeCollection &Types = types();
2029 TypeIndex TIFieldList = Class.getFieldList();
2030 if (TIFieldList.isNoneType()) {
2031 TypeIndex ForwardType = Shared->ForwardReferences.find(Name: Class.getName());
2032 if (!ForwardType.isNoneType()) {
2033 CVType CVReference = Types.getType(Index: ForwardType);
2034 TypeRecordKind RK = static_cast<TypeRecordKind>(CVReference.kind());
2035 ClassRecord ReferenceRecord(RK);
2036 if (Error Err = TypeDeserializer::deserializeAs(
2037 CVT&: const_cast<CVType &>(CVReference), Record&: ReferenceRecord))
2038 return Err;
2039 TIFieldList = ReferenceRecord.getFieldList();
2040 }
2041 }
2042
2043 if (!TIFieldList.isNoneType()) {
2044 // Pass down the TypeIndex 'TI' for the aggregate containing the field list.
2045 CVType CVFieldList = Types.getType(Index: TIFieldList);
2046 if (Error Err = finishVisitation(Record&: CVFieldList, TI, Element: Scope))
2047 return Err;
2048 }
2049
2050 return Error::success();
2051}
2052
2053// LF_ENUM (TPI)
2054Error LVLogicalVisitor::visitKnownRecord(CVType &Record, EnumRecord &Enum,
2055 TypeIndex TI, LVElement *Element) {
2056 LLVM_DEBUG({
2057 printTypeBegin(Record, TI, Element, StreamTPI);
2058 W.printNumber("NumEnumerators", Enum.getMemberCount());
2059 printTypeIndex("UnderlyingType", Enum.getUnderlyingType(), StreamTPI);
2060 printTypeIndex("FieldListType", Enum.getFieldList(), StreamTPI);
2061 W.printString("Name", Enum.getName());
2062 printTypeEnd(Record);
2063 });
2064
2065 LVScopeEnumeration *Scope = static_cast<LVScopeEnumeration *>(Element);
2066 if (!Scope)
2067 return Error::success();
2068
2069 if (Scope->getIsFinalized())
2070 return Error::success();
2071 Scope->setIsFinalized();
2072
2073 // Set the name, as in the case of nested, it would determine the relation
2074 // to any potential parent, via the LF_NESTTYPE record.
2075 Scope->setName(Enum.getName());
2076 if (Enum.hasUniqueName())
2077 Scope->setLinkageName(Enum.getUniqueName());
2078
2079 Scope->setType(getElement(StreamIdx: StreamTPI, TI: Enum.getUnderlyingType()));
2080
2081 if (Enum.isNested()) {
2082 Scope->setIsNested();
2083 createParents(ScopedName: Enum.getName(), Element: Scope);
2084 }
2085
2086 if (Enum.isScoped()) {
2087 Scope->setIsScoped();
2088 Scope->setIsEnumClass();
2089 }
2090
2091 // Nested types will be added to their parents at creation.
2092 if (!(Enum.isNested() || Enum.isScoped())) {
2093 if (LVScope *Namespace = Shared->NamespaceDeduction.get(ScopedName: Enum.getName()))
2094 Namespace->addElement(Scope);
2095 else
2096 Reader->getCompileUnit()->addElement(Scope);
2097 }
2098
2099 TypeIndex TIFieldList = Enum.getFieldList();
2100 if (!TIFieldList.isNoneType()) {
2101 LazyRandomTypeCollection &Types = types();
2102 CVType CVFieldList = Types.getType(Index: TIFieldList);
2103 if (Error Err = finishVisitation(Record&: CVFieldList, TI: TIFieldList, Element: Scope))
2104 return Err;
2105 }
2106
2107 return Error::success();
2108}
2109
2110// LF_FIELDLIST (TPI)
2111Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2112 FieldListRecord &FieldList,
2113 TypeIndex TI, LVElement *Element) {
2114 LLVM_DEBUG({
2115 printTypeBegin(Record, TI, Element, StreamTPI);
2116 printTypeEnd(Record);
2117 });
2118
2119 if (Error Err = visitFieldListMemberStream(TI, Element, FieldList: FieldList.Data))
2120 return Err;
2121
2122 return Error::success();
2123}
2124
2125// LF_FUNC_ID (TPI)/(IPI)
2126Error LVLogicalVisitor::visitKnownRecord(CVType &Record, FuncIdRecord &Func,
2127 TypeIndex TI, LVElement *Element) {
2128 // ParentScope and FunctionType are references into the TPI stream.
2129 LLVM_DEBUG({
2130 printTypeBegin(Record, TI, Element, StreamIPI);
2131 printTypeIndex("ParentScope", Func.getParentScope(), StreamTPI);
2132 printTypeIndex("FunctionType", Func.getFunctionType(), StreamTPI);
2133 W.printString("Name", Func.getName());
2134 printTypeEnd(Record);
2135 });
2136
2137 // The TypeIndex (LF_PROCEDURE) returned by 'getFunctionType' is the
2138 // function propotype, we need to use the function definition.
2139 if (LVScope *FunctionDcl = static_cast<LVScope *>(Element)) {
2140 // For inlined functions, the inlined instance has been already processed
2141 // (all its information is contained in the Symbols section).
2142 // 'Element' points to the created 'abstract' (out-of-line) function.
2143 // Use the parent scope information to allocate it to the correct scope.
2144 LazyRandomTypeCollection &Types = types();
2145 TypeIndex TIParent = Func.getParentScope();
2146 if (FunctionDcl->getIsInlinedAbstract()) {
2147 FunctionDcl->setName(Func.getName());
2148 if (TIParent.isNoneType())
2149 Reader->getCompileUnit()->addElement(Scope: FunctionDcl);
2150 }
2151
2152 if (!TIParent.isNoneType()) {
2153 CVType CVParentScope = ids().getType(Index: TIParent);
2154 if (Error Err = finishVisitation(Record&: CVParentScope, TI: TIParent, Element: FunctionDcl))
2155 return Err;
2156 }
2157
2158 TypeIndex TIFunctionType = Func.getFunctionType();
2159 CVType CVFunctionType = Types.getType(Index: TIFunctionType);
2160 if (Error Err =
2161 finishVisitation(Record&: CVFunctionType, TI: TIFunctionType, Element: FunctionDcl))
2162 return Err;
2163
2164 FunctionDcl->setIsFinalized();
2165 }
2166
2167 return Error::success();
2168}
2169
2170// LF_LABEL (TPI)
2171Error LVLogicalVisitor::visitKnownRecord(CVType &Record, LabelRecord &LR,
2172 TypeIndex TI, LVElement *Element) {
2173 LLVM_DEBUG({
2174 printTypeBegin(Record, TI, Element, StreamTPI);
2175 printTypeEnd(Record);
2176 });
2177 return Error::success();
2178}
2179
2180// LF_MFUNC_ID (TPI)/(IPI)
2181Error LVLogicalVisitor::visitKnownRecord(CVType &Record, MemberFuncIdRecord &Id,
2182 TypeIndex TI, LVElement *Element) {
2183 // ClassType and FunctionType are references into the TPI stream.
2184 LLVM_DEBUG({
2185 printTypeBegin(Record, TI, Element, StreamIPI);
2186 printTypeIndex("ClassType", Id.getClassType(), StreamTPI);
2187 printTypeIndex("FunctionType", Id.getFunctionType(), StreamTPI);
2188 W.printString("Name", Id.getName());
2189 printTypeEnd(Record);
2190 });
2191
2192 LVScope *FunctionDcl = static_cast<LVScope *>(Element);
2193 if (FunctionDcl->getIsInlinedAbstract()) {
2194 // For inlined functions, the inlined instance has been already processed
2195 // (all its information is contained in the Symbols section).
2196 // 'Element' points to the created 'abstract' (out-of-line) function.
2197 // Use the parent scope information to allocate it to the correct scope.
2198 if (LVScope *Class = static_cast<LVScope *>(
2199 Shared->TypeRecords.find(StreamIdx: StreamTPI, TI: Id.getClassType())))
2200 Class->addElement(Scope: FunctionDcl);
2201 }
2202
2203 TypeIndex TIFunctionType = Id.getFunctionType();
2204 CVType CVFunction = types().getType(Index: TIFunctionType);
2205 if (Error Err = finishVisitation(Record&: CVFunction, TI: TIFunctionType, Element))
2206 return Err;
2207
2208 return Error::success();
2209}
2210
2211// LF_MFUNCTION (TPI)
2212Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2213 MemberFunctionRecord &MF, TypeIndex TI,
2214 LVElement *Element) {
2215 LLVM_DEBUG({
2216 printTypeBegin(Record, TI, Element, StreamTPI);
2217 printTypeIndex("ReturnType", MF.getReturnType(), StreamTPI);
2218 printTypeIndex("ClassType", MF.getClassType(), StreamTPI);
2219 printTypeIndex("ThisType", MF.getThisType(), StreamTPI);
2220 W.printNumber("NumParameters", MF.getParameterCount());
2221 printTypeIndex("ArgListType", MF.getArgumentList(), StreamTPI);
2222 W.printNumber("ThisAdjustment", MF.getThisPointerAdjustment());
2223 printTypeEnd(Record);
2224 });
2225
2226 if (LVScope *MemberFunction = static_cast<LVScope *>(Element)) {
2227 LVElement *Class = getElement(StreamIdx: StreamTPI, TI: MF.getClassType());
2228
2229 MemberFunction->setIsFinalized();
2230 MemberFunction->setType(getElement(StreamIdx: StreamTPI, TI: MF.getReturnType()));
2231 MemberFunction->setOffset(TI.getIndex());
2232 MemberFunction->setOffsetFromTypeIndex();
2233
2234 if (ProcessArgumentList) {
2235 ProcessArgumentList = false;
2236
2237 if (!MemberFunction->getIsStatic()) {
2238 LVElement *ThisPointer = getElement(StreamIdx: StreamTPI, TI: MF.getThisType());
2239 // When creating the 'this' pointer, check if it points to a reference.
2240 ThisPointer->setType(Class);
2241 LVSymbol *This =
2242 createParameter(Element: ThisPointer, Name: StringRef(), Parent: MemberFunction);
2243 This->setIsArtificial();
2244 }
2245
2246 // Create formal parameters.
2247 LazyRandomTypeCollection &Types = types();
2248 CVType CVArguments = Types.getType(Index: MF.getArgumentList());
2249 if (Error Err = finishVisitation(Record&: CVArguments, TI: MF.getArgumentList(),
2250 Element: MemberFunction))
2251 return Err;
2252 }
2253 }
2254
2255 return Error::success();
2256}
2257
2258// LF_METHODLIST (TPI)
2259Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2260 MethodOverloadListRecord &Overloads,
2261 TypeIndex TI, LVElement *Element) {
2262 LLVM_DEBUG({
2263 printTypeBegin(Record, TI, Element, StreamTPI);
2264 printTypeEnd(Record);
2265 });
2266
2267 for (OneMethodRecord &Method : Overloads.Methods) {
2268 CVMemberRecord Record;
2269 Record.Kind = LF_METHOD;
2270 Method.Name = OverloadedMethodName;
2271 if (Error Err = visitKnownMember(Record, Method, TI, Element))
2272 return Err;
2273 }
2274
2275 return Error::success();
2276}
2277
2278// LF_MODIFIER (TPI)
2279Error LVLogicalVisitor::visitKnownRecord(CVType &Record, ModifierRecord &Mod,
2280 TypeIndex TI, LVElement *Element) {
2281 LLVM_DEBUG({
2282 printTypeBegin(Record, TI, Element, StreamTPI);
2283 printTypeIndex("ModifiedType", Mod.getModifiedType(), StreamTPI);
2284 printTypeEnd(Record);
2285 });
2286
2287 // Create the modified type, which will be attached to the type(s) that
2288 // contains the modifiers.
2289 LVElement *ModifiedType = getElement(StreamIdx: StreamTPI, TI: Mod.getModifiedType());
2290
2291 // At this point the types recording the qualifiers do not have a
2292 // scope parent. They must be assigned to the current compile unit.
2293 LVScopeCompileUnit *CompileUnit = Reader->getCompileUnit();
2294
2295 // The incoming element does not have a defined kind. Use the given
2296 // modifiers to complete its type. A type can have more than one modifier;
2297 // in that case, we have to create an extra type to have the other modifier.
2298 LVType *LastLink = static_cast<LVType *>(Element);
2299 if (!LastLink->getParentScope())
2300 CompileUnit->addElement(Type: LastLink);
2301
2302 bool SeenModifier = false;
2303 uint16_t Mods = static_cast<uint16_t>(Mod.getModifiers());
2304 if (Mods & uint16_t(ModifierOptions::Const)) {
2305 SeenModifier = true;
2306 LastLink->setTag(dwarf::DW_TAG_const_type);
2307 LastLink->setIsConst();
2308 LastLink->setName("const");
2309 }
2310 if (Mods & uint16_t(ModifierOptions::Volatile)) {
2311 if (SeenModifier) {
2312 LVType *Volatile = Reader->createType();
2313 Volatile->setIsModifier();
2314 LastLink->setType(Volatile);
2315 LastLink = Volatile;
2316 CompileUnit->addElement(Type: LastLink);
2317 }
2318 LastLink->setTag(dwarf::DW_TAG_volatile_type);
2319 LastLink->setIsVolatile();
2320 LastLink->setName("volatile");
2321 }
2322 if (Mods & uint16_t(ModifierOptions::Unaligned)) {
2323 if (SeenModifier) {
2324 LVType *Unaligned = Reader->createType();
2325 Unaligned->setIsModifier();
2326 LastLink->setType(Unaligned);
2327 LastLink = Unaligned;
2328 CompileUnit->addElement(Type: LastLink);
2329 }
2330 LastLink->setTag(dwarf::DW_TAG_unaligned);
2331 LastLink->setIsUnaligned();
2332 LastLink->setName("unaligned");
2333 }
2334
2335 LastLink->setType(ModifiedType);
2336 return Error::success();
2337}
2338
2339// LF_POINTER (TPI)
2340Error LVLogicalVisitor::visitKnownRecord(CVType &Record, PointerRecord &Ptr,
2341 TypeIndex TI, LVElement *Element) {
2342 LLVM_DEBUG({
2343 printTypeBegin(Record, TI, Element, StreamTPI);
2344 printTypeIndex("PointeeType", Ptr.getReferentType(), StreamTPI);
2345 W.printNumber("IsFlat", Ptr.isFlat());
2346 W.printNumber("IsConst", Ptr.isConst());
2347 W.printNumber("IsVolatile", Ptr.isVolatile());
2348 W.printNumber("IsUnaligned", Ptr.isUnaligned());
2349 W.printNumber("IsRestrict", Ptr.isRestrict());
2350 W.printNumber("IsThisPtr&", Ptr.isLValueReferenceThisPtr());
2351 W.printNumber("IsThisPtr&&", Ptr.isRValueReferenceThisPtr());
2352 W.printNumber("SizeOf", Ptr.getSize());
2353
2354 if (Ptr.isPointerToMember()) {
2355 const MemberPointerInfo &MI = Ptr.getMemberInfo();
2356 printTypeIndex("ClassType", MI.getContainingType(), StreamTPI);
2357 }
2358 printTypeEnd(Record);
2359 });
2360
2361 // Find the pointed-to type.
2362 LVType *Pointer = static_cast<LVType *>(Element);
2363 LVElement *Pointee = nullptr;
2364
2365 PointerMode Mode = Ptr.getMode();
2366 Pointee = Ptr.isPointerToMember()
2367 ? Shared->TypeRecords.find(StreamIdx: StreamTPI, TI: Ptr.getReferentType())
2368 : getElement(StreamIdx: StreamTPI, TI: Ptr.getReferentType());
2369
2370 // At this point the types recording the qualifiers do not have a
2371 // scope parent. They must be assigned to the current compile unit.
2372 LVScopeCompileUnit *CompileUnit = Reader->getCompileUnit();
2373
2374 // Order for the different modifiers:
2375 // <restrict> <pointer, Reference, ValueReference> <const, volatile>
2376 // Const and volatile already processed.
2377 bool SeenModifier = false;
2378 LVType *LastLink = Pointer;
2379 if (!LastLink->getParentScope())
2380 CompileUnit->addElement(Type: LastLink);
2381
2382 if (Ptr.isRestrict()) {
2383 SeenModifier = true;
2384 LVType *Restrict = Reader->createType();
2385 Restrict->setTag(dwarf::DW_TAG_restrict_type);
2386 Restrict->setIsRestrict();
2387 Restrict->setName("restrict");
2388 LastLink->setType(Restrict);
2389 LastLink = Restrict;
2390 CompileUnit->addElement(Type: LastLink);
2391 }
2392 if (Mode == PointerMode::LValueReference) {
2393 if (SeenModifier) {
2394 LVType *LReference = Reader->createType();
2395 LReference->setIsModifier();
2396 LastLink->setType(LReference);
2397 LastLink = LReference;
2398 CompileUnit->addElement(Type: LastLink);
2399 }
2400 LastLink->setTag(dwarf::DW_TAG_reference_type);
2401 LastLink->setIsReference();
2402 LastLink->setName("&");
2403 }
2404 if (Mode == PointerMode::RValueReference) {
2405 if (SeenModifier) {
2406 LVType *RReference = Reader->createType();
2407 RReference->setIsModifier();
2408 LastLink->setType(RReference);
2409 LastLink = RReference;
2410 CompileUnit->addElement(Type: LastLink);
2411 }
2412 LastLink->setTag(dwarf::DW_TAG_rvalue_reference_type);
2413 LastLink->setIsRvalueReference();
2414 LastLink->setName("&&");
2415 }
2416
2417 // When creating the pointer, check if it points to a reference.
2418 LastLink->setType(Pointee);
2419 return Error::success();
2420}
2421
2422// LF_PROCEDURE (TPI)
2423Error LVLogicalVisitor::visitKnownRecord(CVType &Record, ProcedureRecord &Proc,
2424 TypeIndex TI, LVElement *Element) {
2425 LLVM_DEBUG({
2426 printTypeBegin(Record, TI, Element, StreamTPI);
2427 printTypeIndex("ReturnType", Proc.getReturnType(), StreamTPI);
2428 W.printNumber("NumParameters", Proc.getParameterCount());
2429 printTypeIndex("ArgListType", Proc.getArgumentList(), StreamTPI);
2430 printTypeEnd(Record);
2431 });
2432
2433 // There is no need to traverse the argument list, as the CodeView format
2434 // declares the parameters as a 'S_LOCAL' symbol tagged as parameter.
2435 // Only process parameters when dealing with inline functions.
2436 if (LVScope *FunctionDcl = static_cast<LVScope *>(Element)) {
2437 FunctionDcl->setType(getElement(StreamIdx: StreamTPI, TI: Proc.getReturnType()));
2438
2439 if (ProcessArgumentList) {
2440 ProcessArgumentList = false;
2441 // Create formal parameters.
2442 LazyRandomTypeCollection &Types = types();
2443 CVType CVArguments = Types.getType(Index: Proc.getArgumentList());
2444 if (Error Err = finishVisitation(Record&: CVArguments, TI: Proc.getArgumentList(),
2445 Element: FunctionDcl))
2446 return Err;
2447 }
2448 }
2449
2450 return Error::success();
2451}
2452
2453// LF_UNION (TPI)
2454Error LVLogicalVisitor::visitKnownRecord(CVType &Record, UnionRecord &Union,
2455 TypeIndex TI, LVElement *Element) {
2456 LLVM_DEBUG({
2457 printTypeBegin(Record, TI, Element, StreamTPI);
2458 W.printNumber("MemberCount", Union.getMemberCount());
2459 printTypeIndex("FieldList", Union.getFieldList(), StreamTPI);
2460 W.printNumber("SizeOf", Union.getSize());
2461 W.printString("Name", Union.getName());
2462 if (Union.hasUniqueName())
2463 W.printString("UniqueName", Union.getUniqueName());
2464 printTypeEnd(Record);
2465 });
2466
2467 LVScopeAggregate *Scope = static_cast<LVScopeAggregate *>(Element);
2468 if (!Scope)
2469 return Error::success();
2470
2471 if (Scope->getIsFinalized())
2472 return Error::success();
2473 Scope->setIsFinalized();
2474
2475 Scope->setName(Union.getName());
2476 if (Union.hasUniqueName())
2477 Scope->setLinkageName(Union.getUniqueName());
2478 Scope->setBitSize(Union.getSize() * DWARF_CHAR_BIT);
2479
2480 if (Union.isNested()) {
2481 Scope->setIsNested();
2482 createParents(ScopedName: Union.getName(), Element: Scope);
2483 } else {
2484 if (LVScope *Namespace = Shared->NamespaceDeduction.get(ScopedName: Union.getName()))
2485 Namespace->addElement(Scope);
2486 else
2487 Reader->getCompileUnit()->addElement(Scope);
2488 }
2489
2490 if (!Union.getFieldList().isNoneType()) {
2491 LazyRandomTypeCollection &Types = types();
2492 // Pass down the TypeIndex 'TI' for the aggregate containing the field list.
2493 CVType CVFieldList = Types.getType(Index: Union.getFieldList());
2494 if (Error Err = finishVisitation(Record&: CVFieldList, TI, Element: Scope))
2495 return Err;
2496 }
2497
2498 return Error::success();
2499}
2500
2501// LF_TYPESERVER2 (TPI)
2502Error LVLogicalVisitor::visitKnownRecord(CVType &Record, TypeServer2Record &TS,
2503 TypeIndex TI, LVElement *Element) {
2504 LLVM_DEBUG({
2505 printTypeBegin(Record, TI, Element, StreamTPI);
2506 W.printString("Guid", formatv("{0}", TS.getGuid()).str());
2507 W.printNumber("Age", TS.getAge());
2508 W.printString("Name", TS.getName());
2509 printTypeEnd(Record);
2510 });
2511 return Error::success();
2512}
2513
2514// LF_VFTABLE (TPI)
2515Error LVLogicalVisitor::visitKnownRecord(CVType &Record, VFTableRecord &VFT,
2516 TypeIndex TI, LVElement *Element) {
2517 LLVM_DEBUG({
2518 printTypeBegin(Record, TI, Element, StreamTPI);
2519 printTypeIndex("CompleteClass", VFT.getCompleteClass(), StreamTPI);
2520 printTypeIndex("OverriddenVFTable", VFT.getOverriddenVTable(), StreamTPI);
2521 W.printHex("VFPtrOffset", VFT.getVFPtrOffset());
2522 W.printString("VFTableName", VFT.getName());
2523 for (const StringRef &N : VFT.getMethodNames())
2524 W.printString("MethodName", N);
2525 printTypeEnd(Record);
2526 });
2527 return Error::success();
2528}
2529
2530// LF_VTSHAPE (TPI)
2531Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2532 VFTableShapeRecord &Shape,
2533 TypeIndex TI, LVElement *Element) {
2534 LLVM_DEBUG({
2535 printTypeBegin(Record, TI, Element, StreamTPI);
2536 W.printNumber("VFEntryCount", Shape.getEntryCount());
2537 printTypeEnd(Record);
2538 });
2539 return Error::success();
2540}
2541
2542// LF_SUBSTR_LIST (TPI)/(IPI)
2543Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2544 StringListRecord &Strings,
2545 TypeIndex TI, LVElement *Element) {
2546 // All the indices are references into the TPI/IPI stream.
2547 LLVM_DEBUG({
2548 printTypeBegin(Record, TI, Element, StreamIPI);
2549 ArrayRef<TypeIndex> Indices = Strings.getIndices();
2550 uint32_t Size = Indices.size();
2551 W.printNumber("NumStrings", Size);
2552 ListScope Arguments(W, "Strings");
2553 for (uint32_t I = 0; I < Size; ++I)
2554 printTypeIndex("String", Indices[I], StreamIPI);
2555 printTypeEnd(Record);
2556 });
2557 return Error::success();
2558}
2559
2560// LF_STRING_ID (TPI)/(IPI)
2561Error LVLogicalVisitor::visitKnownRecord(CVType &Record, StringIdRecord &String,
2562 TypeIndex TI, LVElement *Element) {
2563 // All args are references into the TPI/IPI stream.
2564 LLVM_DEBUG({
2565 printTypeIndex("\nTI", TI, StreamIPI);
2566 printTypeIndex("Id", String.getId(), StreamIPI);
2567 W.printString("StringData", String.getString());
2568 });
2569
2570 if (LVScope *Namespace = Shared->NamespaceDeduction.get(
2571 ScopedName: String.getString(), /*CheckScope=*/false)) {
2572 // The function is already at different scope. In order to reflect
2573 // the correct parent, move it to the namespace.
2574 if (LVScope *Scope = Element->getParentScope())
2575 Scope->removeElement(Element);
2576 Namespace->addElement(Element);
2577 }
2578
2579 return Error::success();
2580}
2581
2582// LF_UDT_SRC_LINE (TPI)/(IPI)
2583Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2584 UdtSourceLineRecord &SourceLine,
2585 TypeIndex TI, LVElement *Element) {
2586 // All args are references into the TPI/IPI stream.
2587 LLVM_DEBUG({
2588 printTypeIndex("\nTI", TI, StreamIPI);
2589 printTypeIndex("UDT", SourceLine.getUDT(), StreamIPI);
2590 printTypeIndex("SourceFile", SourceLine.getSourceFile(), StreamIPI);
2591 W.printNumber("LineNumber", SourceLine.getLineNumber());
2592 });
2593 return Error::success();
2594}
2595
2596// LF_UDT_MOD_SRC_LINE (TPI)/(IPI)
2597Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2598 UdtModSourceLineRecord &ModSourceLine,
2599 TypeIndex TI, LVElement *Element) {
2600 // All args are references into the TPI/IPI stream.
2601 LLVM_DEBUG({
2602 printTypeBegin(Record, TI, Element, StreamIPI);
2603 printTypeIndex("\nTI", TI, StreamIPI);
2604 printTypeIndex("UDT", ModSourceLine.getUDT(), StreamIPI);
2605 printTypeIndex("SourceFile", ModSourceLine.getSourceFile(), StreamIPI);
2606 W.printNumber("LineNumber", ModSourceLine.getLineNumber());
2607 W.printNumber("Module", ModSourceLine.getModule());
2608 printTypeEnd(Record);
2609 });
2610 return Error::success();
2611}
2612
2613// LF_PRECOMP (TPI)
2614Error LVLogicalVisitor::visitKnownRecord(CVType &Record, PrecompRecord &Precomp,
2615 TypeIndex TI, LVElement *Element) {
2616 LLVM_DEBUG({
2617 printTypeBegin(Record, TI, Element, StreamTPI);
2618 W.printHex("StartIndex", Precomp.getStartTypeIndex());
2619 W.printHex("Count", Precomp.getTypesCount());
2620 W.printHex("Signature", Precomp.getSignature());
2621 W.printString("PrecompFile", Precomp.getPrecompFilePath());
2622 printTypeEnd(Record);
2623 });
2624 return Error::success();
2625}
2626
2627// LF_ENDPRECOMP (TPI)
2628Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2629 EndPrecompRecord &EndPrecomp,
2630 TypeIndex TI, LVElement *Element) {
2631 LLVM_DEBUG({
2632 printTypeBegin(Record, TI, Element, StreamTPI);
2633 W.printHex("Signature", EndPrecomp.getSignature());
2634 printTypeEnd(Record);
2635 });
2636 return Error::success();
2637}
2638
2639Error LVLogicalVisitor::visitUnknownMember(CVMemberRecord &Record,
2640 TypeIndex TI) {
2641 LLVM_DEBUG({ W.printHex("UnknownMember", unsigned(Record.Kind)); });
2642 return Error::success();
2643}
2644
2645// LF_BCLASS, LF_BINTERFACE
2646Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2647 BaseClassRecord &Base, TypeIndex TI,
2648 LVElement *Element) {
2649 LLVM_DEBUG({
2650 printMemberBegin(Record, TI, Element, StreamTPI);
2651 printTypeIndex("BaseType", Base.getBaseType(), StreamTPI);
2652 W.printHex("BaseOffset", Base.getBaseOffset());
2653 printMemberEnd(Record);
2654 });
2655
2656 createElement(Kind: Record.Kind);
2657 if (LVSymbol *Symbol = CurrentSymbol) {
2658 LVElement *BaseClass = getElement(StreamIdx: StreamTPI, TI: Base.getBaseType());
2659 Symbol->setName(BaseClass->getName());
2660 Symbol->setType(BaseClass);
2661 Symbol->setAccessibilityCode(Base.getAccess());
2662 static_cast<LVScope *>(Element)->addElement(Symbol);
2663 }
2664
2665 return Error::success();
2666}
2667
2668// LF_MEMBER
2669Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2670 DataMemberRecord &Field, TypeIndex TI,
2671 LVElement *Element) {
2672 LLVM_DEBUG({
2673 printMemberBegin(Record, TI, Element, StreamTPI);
2674 printTypeIndex("Type", Field.getType(), StreamTPI);
2675 W.printHex("FieldOffset", Field.getFieldOffset());
2676 W.printString("Name", Field.getName());
2677 printMemberEnd(Record);
2678 });
2679
2680 // Create the data member.
2681 createDataMember(Record, Parent: static_cast<LVScope *>(Element), Name: Field.getName(),
2682 Type: Field.getType(), Access: Field.getAccess());
2683 return Error::success();
2684}
2685
2686// LF_ENUMERATE
2687Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2688 EnumeratorRecord &Enum, TypeIndex TI,
2689 LVElement *Element) {
2690 LLVM_DEBUG({
2691 printMemberBegin(Record, TI, Element, StreamTPI);
2692 W.printNumber("EnumValue", Enum.getValue());
2693 W.printString("Name", Enum.getName());
2694 printMemberEnd(Record);
2695 });
2696
2697 createElement(Kind: Record.Kind);
2698 if (LVType *Type = CurrentType) {
2699 Type->setName(Enum.getName());
2700 SmallString<16> Value;
2701 Enum.getValue().toString(Str&: Value, Radix: 16, Signed: true, formatAsCLiteral: true);
2702 Type->setValue(Value);
2703 static_cast<LVScope *>(Element)->addElement(Type: CurrentType);
2704 }
2705
2706 return Error::success();
2707}
2708
2709// LF_INDEX
2710Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2711 ListContinuationRecord &Cont,
2712 TypeIndex TI, LVElement *Element) {
2713 LLVM_DEBUG({
2714 printMemberBegin(Record, TI, Element, StreamTPI);
2715 printTypeIndex("ContinuationIndex", Cont.getContinuationIndex(), StreamTPI);
2716 printMemberEnd(Record);
2717 });
2718 return Error::success();
2719}
2720
2721// LF_NESTTYPE
2722Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2723 NestedTypeRecord &Nested, TypeIndex TI,
2724 LVElement *Element) {
2725 LLVM_DEBUG({
2726 printMemberBegin(Record, TI, Element, StreamTPI);
2727 printTypeIndex("Type", Nested.getNestedType(), StreamTPI);
2728 W.printString("Name", Nested.getName());
2729 printMemberEnd(Record);
2730 });
2731
2732 if (LVElement *Typedef = createElement(Kind: SymbolKind::S_UDT)) {
2733 Typedef->setName(Nested.getName());
2734 LVElement *NestedType = getElement(StreamIdx: StreamTPI, TI: Nested.getNestedType());
2735 Typedef->setType(NestedType);
2736 LVScope *Scope = static_cast<LVScope *>(Element);
2737 Scope->addElement(Element: Typedef);
2738
2739 if (NestedType && NestedType->getIsNested()) {
2740 // 'Element' is an aggregate type that may contains this nested type
2741 // definition. Used their scoped names, to decide on their relationship.
2742 StringRef RecordName = getRecordName(Types&: types(), TI);
2743
2744 StringRef NestedTypeName = NestedType->getName();
2745 if (NestedTypeName.size() && RecordName.size()) {
2746 StringRef OuterComponent;
2747 std::tie(args&: OuterComponent, args: std::ignore) =
2748 getInnerComponent(Name: NestedTypeName);
2749 // We have an already created nested type. Add it to the current scope
2750 // and update all its children if any.
2751 if (OuterComponent.size() && OuterComponent == RecordName) {
2752 if (!NestedType->getIsScopedAlready()) {
2753 Scope->addElement(Element: NestedType);
2754 NestedType->setIsScopedAlready();
2755 NestedType->updateLevel(Parent: Scope);
2756 }
2757 Typedef->resetIncludeInPrint();
2758 }
2759 }
2760 }
2761 }
2762
2763 return Error::success();
2764}
2765
2766// LF_ONEMETHOD
2767Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2768 OneMethodRecord &Method, TypeIndex TI,
2769 LVElement *Element) {
2770 LLVM_DEBUG({
2771 printMemberBegin(Record, TI, Element, StreamTPI);
2772 printTypeIndex("Type", Method.getType(), StreamTPI);
2773 // If virtual, then read the vftable offset.
2774 if (Method.isIntroducingVirtual())
2775 W.printHex("VFTableOffset", Method.getVFTableOffset());
2776 W.printString("Name", Method.getName());
2777 printMemberEnd(Record);
2778 });
2779
2780 // All the LF_ONEMETHOD objects share the same type description.
2781 // We have to create a scope object for each one and get the required
2782 // information from the LF_MFUNCTION object.
2783 ProcessArgumentList = true;
2784 if (LVElement *MemberFunction = createElement(Kind: TypeLeafKind::LF_ONEMETHOD)) {
2785 MemberFunction->setIsFinalized();
2786 static_cast<LVScope *>(Element)->addElement(Element: MemberFunction);
2787
2788 MemberFunction->setName(Method.getName());
2789 MemberFunction->setAccessibilityCode(Method.getAccess());
2790
2791 MethodKind Kind = Method.getMethodKind();
2792 if (Kind == MethodKind::Static)
2793 MemberFunction->setIsStatic();
2794 MemberFunction->setVirtualityCode(Kind);
2795
2796 MethodOptions Flags = Method.Attrs.getFlags();
2797 if (MethodOptions::CompilerGenerated ==
2798 (Flags & MethodOptions::CompilerGenerated))
2799 MemberFunction->setIsArtificial();
2800
2801 LazyRandomTypeCollection &Types = types();
2802 CVType CVMethodType = Types.getType(Index: Method.getType());
2803 if (Error Err =
2804 finishVisitation(Record&: CVMethodType, TI: Method.getType(), Element: MemberFunction))
2805 return Err;
2806 }
2807 ProcessArgumentList = false;
2808
2809 return Error::success();
2810}
2811
2812// LF_METHOD
2813Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2814 OverloadedMethodRecord &Method,
2815 TypeIndex TI, LVElement *Element) {
2816 LLVM_DEBUG({
2817 printMemberBegin(Record, TI, Element, StreamTPI);
2818 W.printHex("MethodCount", Method.getNumOverloads());
2819 printTypeIndex("MethodListIndex", Method.getMethodList(), StreamTPI);
2820 W.printString("Name", Method.getName());
2821 printMemberEnd(Record);
2822 });
2823
2824 // Record the overloaded method name, which will be used during the
2825 // traversal of the method list.
2826 LazyRandomTypeCollection &Types = types();
2827 OverloadedMethodName = Method.getName();
2828 CVType CVMethods = Types.getType(Index: Method.getMethodList());
2829 if (Error Err = finishVisitation(Record&: CVMethods, TI: Method.getMethodList(), Element))
2830 return Err;
2831
2832 return Error::success();
2833}
2834
2835// LF_STMEMBER
2836Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2837 StaticDataMemberRecord &Field,
2838 TypeIndex TI, LVElement *Element) {
2839 LLVM_DEBUG({
2840 printMemberBegin(Record, TI, Element, StreamTPI);
2841 printTypeIndex("Type", Field.getType(), StreamTPI);
2842 W.printString("Name", Field.getName());
2843 printMemberEnd(Record);
2844 });
2845
2846 // Create the data member.
2847 createDataMember(Record, Parent: static_cast<LVScope *>(Element), Name: Field.getName(),
2848 Type: Field.getType(), Access: Field.getAccess());
2849 return Error::success();
2850}
2851
2852// LF_VFUNCTAB
2853Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2854 VFPtrRecord &VFTable, TypeIndex TI,
2855 LVElement *Element) {
2856 LLVM_DEBUG({
2857 printMemberBegin(Record, TI, Element, StreamTPI);
2858 printTypeIndex("Type", VFTable.getType(), StreamTPI);
2859 printMemberEnd(Record);
2860 });
2861 return Error::success();
2862}
2863
2864// LF_VBCLASS, LF_IVBCLASS
2865Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2866 VirtualBaseClassRecord &Base,
2867 TypeIndex TI, LVElement *Element) {
2868 LLVM_DEBUG({
2869 printMemberBegin(Record, TI, Element, StreamTPI);
2870 printTypeIndex("BaseType", Base.getBaseType(), StreamTPI);
2871 printTypeIndex("VBPtrType", Base.getVBPtrType(), StreamTPI);
2872 W.printHex("VBPtrOffset", Base.getVBPtrOffset());
2873 W.printHex("VBTableIndex", Base.getVTableIndex());
2874 printMemberEnd(Record);
2875 });
2876
2877 createElement(Kind: Record.Kind);
2878 if (LVSymbol *Symbol = CurrentSymbol) {
2879 LVElement *BaseClass = getElement(StreamIdx: StreamTPI, TI: Base.getBaseType());
2880 Symbol->setName(BaseClass->getName());
2881 Symbol->setType(BaseClass);
2882 Symbol->setAccessibilityCode(Base.getAccess());
2883 Symbol->setVirtualityCode(MethodKind::Virtual);
2884 static_cast<LVScope *>(Element)->addElement(Symbol);
2885 }
2886
2887 return Error::success();
2888}
2889
2890Error LVLogicalVisitor::visitMemberRecord(CVMemberRecord &Record,
2891 TypeVisitorCallbacks &Callbacks,
2892 TypeIndex TI, LVElement *Element) {
2893 if (Error Err = Callbacks.visitMemberBegin(Record))
2894 return Err;
2895
2896 switch (Record.Kind) {
2897 default:
2898 if (Error Err = Callbacks.visitUnknownMember(Record))
2899 return Err;
2900 break;
2901#define MEMBER_RECORD(EnumName, EnumVal, Name) \
2902 case EnumName: { \
2903 if (Error Err = \
2904 visitKnownMember<Name##Record>(Record, Callbacks, TI, Element)) \
2905 return Err; \
2906 break; \
2907 }
2908#define MEMBER_RECORD_ALIAS(EnumName, EnumVal, Name, AliasName) \
2909 MEMBER_RECORD(EnumVal, EnumVal, AliasName)
2910#define TYPE_RECORD(EnumName, EnumVal, Name)
2911#define TYPE_RECORD_ALIAS(EnumName, EnumVal, Name, AliasName)
2912#include "llvm/DebugInfo/CodeView/CodeViewTypes.def"
2913 }
2914
2915 if (Error Err = Callbacks.visitMemberEnd(Record))
2916 return Err;
2917
2918 return Error::success();
2919}
2920
2921Error LVLogicalVisitor::finishVisitation(CVType &Record, TypeIndex TI,
2922 LVElement *Element) {
2923 switch (Record.kind()) {
2924 default:
2925 if (Error Err = visitUnknownType(Record, TI))
2926 return Err;
2927 break;
2928#define TYPE_RECORD(EnumName, EnumVal, Name) \
2929 case EnumName: { \
2930 if (Error Err = visitKnownRecord<Name##Record>(Record, TI, Element)) \
2931 return Err; \
2932 break; \
2933 }
2934#define TYPE_RECORD_ALIAS(EnumName, EnumVal, Name, AliasName) \
2935 TYPE_RECORD(EnumVal, EnumVal, AliasName)
2936#define MEMBER_RECORD(EnumName, EnumVal, Name)
2937#define MEMBER_RECORD_ALIAS(EnumName, EnumVal, Name, AliasName)
2938#include "llvm/DebugInfo/CodeView/CodeViewTypes.def"
2939 }
2940
2941 return Error::success();
2942}
2943
2944// Customized version of 'FieldListVisitHelper'.
2945Error LVLogicalVisitor::visitFieldListMemberStream(
2946 TypeIndex TI, LVElement *Element, ArrayRef<uint8_t> FieldList) {
2947 BinaryByteStream Stream(FieldList, llvm::endianness::little);
2948 BinaryStreamReader Reader(Stream);
2949 FieldListDeserializer Deserializer(Reader);
2950 TypeVisitorCallbackPipeline Pipeline;
2951 Pipeline.addCallbackToPipeline(Callbacks&: Deserializer);
2952
2953 TypeLeafKind Leaf;
2954 while (!Reader.empty()) {
2955 if (Error Err = Reader.readEnum(Dest&: Leaf))
2956 return Err;
2957
2958 CVMemberRecord Record;
2959 Record.Kind = Leaf;
2960 if (Error Err = visitMemberRecord(Record, Callbacks&: Pipeline, TI, Element))
2961 return Err;
2962 }
2963
2964 return Error::success();
2965}
2966
2967void LVLogicalVisitor::addElement(LVScope *Scope, bool IsCompileUnit) {
2968 // The CodeView specifications does not treat S_COMPILE2 and S_COMPILE3
2969 // as symbols that open a scope. The CodeView reader, treat them in a
2970 // similar way as DWARF. As there is no a symbole S_END to close the
2971 // compile unit, we need to check for the next compile unit.
2972 if (IsCompileUnit) {
2973 if (!ScopeStack.empty())
2974 popScope();
2975 InCompileUnitScope = true;
2976 }
2977
2978 pushScope(Scope);
2979 ReaderParent->addElement(Scope);
2980}
2981
2982void LVLogicalVisitor::addElement(LVSymbol *Symbol) {
2983 ReaderScope->addElement(Symbol);
2984}
2985
2986void LVLogicalVisitor::addElement(LVType *Type) {
2987 ReaderScope->addElement(Type);
2988}
2989
2990LVElement *LVLogicalVisitor::createElement(TypeLeafKind Kind) {
2991 CurrentScope = nullptr;
2992 CurrentSymbol = nullptr;
2993 CurrentType = nullptr;
2994
2995 if (Kind < TypeIndex::FirstNonSimpleIndex) {
2996 CurrentType = Reader->createType();
2997 CurrentType->setIsBase();
2998 CurrentType->setTag(dwarf::DW_TAG_base_type);
2999 if (options().getAttributeBase())
3000 CurrentType->setIncludeInPrint();
3001 return CurrentType;
3002 }
3003
3004 switch (Kind) {
3005 // Types.
3006 case TypeLeafKind::LF_ENUMERATE:
3007 CurrentType = Reader->createTypeEnumerator();
3008 CurrentType->setTag(dwarf::DW_TAG_enumerator);
3009 return CurrentType;
3010 case TypeLeafKind::LF_MODIFIER:
3011 CurrentType = Reader->createType();
3012 CurrentType->setIsModifier();
3013 return CurrentType;
3014 case TypeLeafKind::LF_POINTER:
3015 CurrentType = Reader->createType();
3016 CurrentType->setIsPointer();
3017 CurrentType->setName("*");
3018 CurrentType->setTag(dwarf::DW_TAG_pointer_type);
3019 return CurrentType;
3020
3021 // Symbols.
3022 case TypeLeafKind::LF_BCLASS:
3023 case TypeLeafKind::LF_IVBCLASS:
3024 case TypeLeafKind::LF_VBCLASS:
3025 CurrentSymbol = Reader->createSymbol();
3026 CurrentSymbol->setTag(dwarf::DW_TAG_inheritance);
3027 CurrentSymbol->setIsInheritance();
3028 return CurrentSymbol;
3029 case TypeLeafKind::LF_MEMBER:
3030 case TypeLeafKind::LF_STMEMBER:
3031 CurrentSymbol = Reader->createSymbol();
3032 CurrentSymbol->setIsMember();
3033 CurrentSymbol->setTag(dwarf::DW_TAG_member);
3034 return CurrentSymbol;
3035
3036 // Scopes.
3037 case TypeLeafKind::LF_ARRAY:
3038 CurrentScope = Reader->createScopeArray();
3039 CurrentScope->setTag(dwarf::DW_TAG_array_type);
3040 return CurrentScope;
3041 case TypeLeafKind::LF_CLASS:
3042 CurrentScope = Reader->createScopeAggregate();
3043 CurrentScope->setTag(dwarf::DW_TAG_class_type);
3044 CurrentScope->setIsClass();
3045 return CurrentScope;
3046 case TypeLeafKind::LF_ENUM:
3047 CurrentScope = Reader->createScopeEnumeration();
3048 CurrentScope->setTag(dwarf::DW_TAG_enumeration_type);
3049 return CurrentScope;
3050 case TypeLeafKind::LF_METHOD:
3051 case TypeLeafKind::LF_ONEMETHOD:
3052 case TypeLeafKind::LF_PROCEDURE:
3053 CurrentScope = Reader->createScopeFunction();
3054 CurrentScope->setIsSubprogram();
3055 CurrentScope->setTag(dwarf::DW_TAG_subprogram);
3056 return CurrentScope;
3057 case TypeLeafKind::LF_STRUCTURE:
3058 CurrentScope = Reader->createScopeAggregate();
3059 CurrentScope->setIsStructure();
3060 CurrentScope->setTag(dwarf::DW_TAG_structure_type);
3061 return CurrentScope;
3062 case TypeLeafKind::LF_UNION:
3063 CurrentScope = Reader->createScopeAggregate();
3064 CurrentScope->setIsUnion();
3065 CurrentScope->setTag(dwarf::DW_TAG_union_type);
3066 return CurrentScope;
3067 default:
3068 // If '--internal=tag' and '--print=warning' are specified in the command
3069 // line, we record and print each seen 'TypeLeafKind'.
3070 break;
3071 }
3072 return nullptr;
3073}
3074
3075LVElement *LVLogicalVisitor::createElement(SymbolKind Kind) {
3076 CurrentScope = nullptr;
3077 CurrentSymbol = nullptr;
3078 CurrentType = nullptr;
3079 switch (Kind) {
3080 // Types.
3081 case SymbolKind::S_UDT:
3082 CurrentType = Reader->createTypeDefinition();
3083 CurrentType->setTag(dwarf::DW_TAG_typedef);
3084 return CurrentType;
3085
3086 // Symbols.
3087 case SymbolKind::S_CONSTANT:
3088 CurrentSymbol = Reader->createSymbol();
3089 CurrentSymbol->setIsConstant();
3090 CurrentSymbol->setTag(dwarf::DW_TAG_constant);
3091 return CurrentSymbol;
3092
3093 case SymbolKind::S_BPREL32:
3094 case SymbolKind::S_REGREL32:
3095 case SymbolKind::S_REGREL32_INDIR:
3096 case SymbolKind::S_GDATA32:
3097 case SymbolKind::S_LDATA32:
3098 case SymbolKind::S_LOCAL:
3099 // During the symbol traversal more information is available to
3100 // determine if the symbol is a parameter or a variable. At this
3101 // stage mark it as variable.
3102 CurrentSymbol = Reader->createSymbol();
3103 CurrentSymbol->setIsVariable();
3104 CurrentSymbol->setTag(dwarf::DW_TAG_variable);
3105 return CurrentSymbol;
3106
3107 // Scopes.
3108 case SymbolKind::S_BLOCK32:
3109 CurrentScope = Reader->createScope();
3110 CurrentScope->setIsLexicalBlock();
3111 CurrentScope->setTag(dwarf::DW_TAG_lexical_block);
3112 return CurrentScope;
3113 case SymbolKind::S_COMPILE2:
3114 case SymbolKind::S_COMPILE3:
3115 CurrentScope = Reader->createScopeCompileUnit();
3116 CurrentScope->setTag(dwarf::DW_TAG_compile_unit);
3117 Reader->setCompileUnit(static_cast<LVScopeCompileUnit *>(CurrentScope));
3118 return CurrentScope;
3119 case SymbolKind::S_INLINESITE:
3120 case SymbolKind::S_INLINESITE2:
3121 CurrentScope = Reader->createScopeFunctionInlined();
3122 CurrentScope->setIsInlinedFunction();
3123 CurrentScope->setTag(dwarf::DW_TAG_inlined_subroutine);
3124 return CurrentScope;
3125 case SymbolKind::S_LPROC32:
3126 case SymbolKind::S_GPROC32:
3127 case SymbolKind::S_LPROC32_ID:
3128 case SymbolKind::S_GPROC32_ID:
3129 case SymbolKind::S_SEPCODE:
3130 case SymbolKind::S_THUNK32:
3131 CurrentScope = Reader->createScopeFunction();
3132 CurrentScope->setIsSubprogram();
3133 CurrentScope->setTag(dwarf::DW_TAG_subprogram);
3134 return CurrentScope;
3135 default:
3136 // If '--internal=tag' and '--print=warning' are specified in the command
3137 // line, we record and print each seen 'SymbolKind'.
3138 break;
3139 }
3140 return nullptr;
3141}
3142
3143LVElement *LVLogicalVisitor::createElement(TypeIndex TI, TypeLeafKind Kind) {
3144 LVElement *Element = Shared->TypeRecords.find(StreamIdx: StreamTPI, TI);
3145 if (!Element) {
3146 // We are dealing with a base type or pointer to a base type, which are
3147 // not included explicitly in the CodeView format.
3148 if (Kind < TypeIndex::FirstNonSimpleIndex) {
3149 Element = createElement(Kind);
3150 Element->setIsFinalized();
3151 Shared->TypeRecords.add(StreamIdx: StreamTPI, TI: (TypeIndex)Kind, Kind, Element);
3152 Element->setOffset(Kind);
3153 return Element;
3154 }
3155 // We are dealing with a pointer to a base type.
3156 if (TI.getIndex() < TypeIndex::FirstNonSimpleIndex) {
3157 Element = createElement(Kind);
3158 Shared->TypeRecords.add(StreamIdx: StreamTPI, TI, Kind, Element);
3159 Element->setOffset(TI.getIndex());
3160 Element->setOffsetFromTypeIndex();
3161 return Element;
3162 }
3163
3164 W.printString(Value: "** Not implemented. **");
3165 printTypeIndex(FieldName: "TypeIndex", TI, StreamIdx: StreamTPI);
3166 W.printString(Label: "TypeLeafKind", Value: formatTypeLeafKind(K: Kind));
3167 return nullptr;
3168 }
3169
3170 Element->setOffset(TI.getIndex());
3171 Element->setOffsetFromTypeIndex();
3172 return Element;
3173}
3174
3175void LVLogicalVisitor::createDataMember(CVMemberRecord &Record, LVScope *Parent,
3176 StringRef Name, TypeIndex TI,
3177 MemberAccess Access) {
3178 LLVM_DEBUG({
3179 printTypeIndex("TypeIndex", TI, StreamTPI);
3180 W.printString("TypeName", Name);
3181 });
3182
3183 createElement(Kind: Record.Kind);
3184 if (LVSymbol *Symbol = CurrentSymbol) {
3185 Symbol->setName(Name);
3186 if (TI.isNoneType() || TI.isSimple())
3187 Symbol->setType(getElement(StreamIdx: StreamTPI, TI));
3188 else {
3189 LazyRandomTypeCollection &Types = types();
3190 CVType CVMemberType = Types.getType(Index: TI);
3191 if (CVMemberType.kind() == LF_BITFIELD) {
3192 if (Error Err = finishVisitation(Record&: CVMemberType, TI, Element: Symbol)) {
3193 consumeError(Err: std::move(Err));
3194 return;
3195 }
3196 } else
3197 Symbol->setType(getElement(StreamIdx: StreamTPI, TI));
3198 }
3199 Symbol->setAccessibilityCode(Access);
3200 Parent->addElement(Symbol);
3201 }
3202}
3203
3204LVSymbol *LVLogicalVisitor::createParameter(LVElement *Element, StringRef Name,
3205 LVScope *Parent) {
3206 LVSymbol *Parameter = Reader->createSymbol();
3207 Parent->addElement(Symbol: Parameter);
3208 Parameter->setIsParameter();
3209 Parameter->setTag(dwarf::DW_TAG_formal_parameter);
3210 Parameter->setName(Name);
3211 Parameter->setType(Element);
3212 return Parameter;
3213}
3214
3215LVSymbol *LVLogicalVisitor::createParameter(TypeIndex TI, StringRef Name,
3216 LVScope *Parent) {
3217 return createParameter(Element: getElement(StreamIdx: StreamTPI, TI), Name, Parent);
3218}
3219
3220LVType *LVLogicalVisitor::createBaseType(TypeIndex TI, StringRef TypeName) {
3221 TypeLeafKind SimpleKind = (TypeLeafKind)TI.getSimpleKind();
3222 TypeIndex TIR = (TypeIndex)SimpleKind;
3223 LLVM_DEBUG({
3224 printTypeIndex("TypeIndex", TIR, StreamTPI);
3225 W.printString("TypeName", TypeName);
3226 });
3227
3228 if (LVElement *Element = Shared->TypeRecords.find(StreamIdx: StreamTPI, TI: TIR))
3229 return static_cast<LVType *>(Element);
3230
3231 if (createElement(TI: TIR, Kind: SimpleKind)) {
3232 CurrentType->setName(TypeName);
3233 CurrentType->setBitSize(getSizeInBytesForTypeIndex(TI: TIR) * DWARF_CHAR_BIT);
3234 Reader->getCompileUnit()->addElement(Type: CurrentType);
3235 }
3236 return CurrentType;
3237}
3238
3239LVType *LVLogicalVisitor::createPointerType(TypeIndex TI, StringRef TypeName) {
3240 LLVM_DEBUG({
3241 printTypeIndex("TypeIndex", TI, StreamTPI);
3242 W.printString("TypeName", TypeName);
3243 });
3244
3245 if (LVElement *Element = Shared->TypeRecords.find(StreamIdx: StreamTPI, TI))
3246 return static_cast<LVType *>(Element);
3247
3248 LVType *Pointee = createBaseType(TI, TypeName: TypeName.drop_back(N: 1));
3249 if (createElement(TI, Kind: TypeLeafKind::LF_POINTER)) {
3250 CurrentType->setIsFinalized();
3251 CurrentType->setType(Pointee);
3252 Reader->getCompileUnit()->addElement(Type: CurrentType);
3253 }
3254 return CurrentType;
3255}
3256
3257void LVLogicalVisitor::createParents(StringRef ScopedName, LVElement *Element) {
3258 // For the given test case:
3259 //
3260 // struct S { enum E { ... }; };
3261 // S::E V;
3262 //
3263 // 0 | S_LOCAL `V`
3264 // type=0x1004 (S::E), flags = none
3265 // 0x1004 | LF_ENUM `S::E`
3266 // options: has unique name | is nested
3267 // 0x1009 | LF_STRUCTURE `S`
3268 // options: contains nested class
3269 //
3270 // When the local 'V' is processed, its type 'E' is created. But There is
3271 // no direct reference to its parent 'S'. We use the scoped name for 'E',
3272 // to create its parents.
3273
3274 // The input scoped name must have at least parent and nested names.
3275 // Drop the last element name, as it corresponds to the nested type.
3276 LVStringRefs Components = getAllLexicalComponents(Name: ScopedName);
3277 if (Components.size() < 2)
3278 return;
3279 Components.pop_back();
3280
3281 LVStringRefs::size_type FirstNamespace;
3282 LVStringRefs::size_type FirstAggregate;
3283 std::tie(args&: FirstNamespace, args&: FirstAggregate) =
3284 Shared->NamespaceDeduction.find(Components);
3285
3286 LLVM_DEBUG({
3287 W.printString("First Namespace", Components[FirstNamespace]);
3288 W.printString("First NonNamespace", Components[FirstAggregate]);
3289 });
3290
3291 // Create any referenced namespaces.
3292 if (FirstNamespace < FirstAggregate) {
3293 Shared->NamespaceDeduction.get(
3294 Components: LVStringRefs(Components.begin() + FirstNamespace,
3295 Components.begin() + FirstAggregate));
3296 }
3297
3298 // Traverse the enclosing scopes (aggregates) and create them. In the
3299 // case of nested empty aggregates, MSVC does not emit a full record
3300 // description. It emits only the reference record.
3301 LVScope *Aggregate = nullptr;
3302 TypeIndex TIAggregate;
3303 std::string AggregateName = getScopedName(
3304 Components: LVStringRefs(Components.begin(), Components.begin() + FirstAggregate));
3305
3306 // This traversal is executed at least once.
3307 for (LVStringRefs::size_type Index = FirstAggregate;
3308 Index < Components.size(); ++Index) {
3309 AggregateName = getScopedName(Components: LVStringRefs(Components.begin() + Index,
3310 Components.begin() + Index + 1),
3311 BaseName: AggregateName);
3312 TIAggregate = Shared->ForwardReferences.remap(
3313 TI: Shared->TypeRecords.find(StreamIdx: StreamTPI, Name: AggregateName));
3314 Aggregate =
3315 TIAggregate.isNoneType()
3316 ? nullptr
3317 : static_cast<LVScope *>(getElement(StreamIdx: StreamTPI, TI: TIAggregate));
3318 }
3319
3320 // Workaround for cases where LF_NESTTYPE is missing for nested templates.
3321 // If we manage to get parent information from the scoped name, we can add
3322 // the nested type without relying on the LF_NESTTYPE.
3323 if (Aggregate && !Element->getIsScopedAlready()) {
3324 Aggregate->addElement(Element);
3325 Element->setIsScopedAlready();
3326 }
3327}
3328
3329LVElement *LVLogicalVisitor::getElement(uint32_t StreamIdx, TypeIndex TI,
3330 LVScope *Parent) {
3331 LLVM_DEBUG({ printTypeIndex("TypeIndex", TI, StreamTPI); });
3332 TI = Shared->ForwardReferences.remap(TI);
3333 LLVM_DEBUG({ printTypeIndex("TypeIndex Remap", TI, StreamTPI); });
3334
3335 LVElement *Element = Shared->TypeRecords.find(StreamIdx, TI);
3336 if (!Element) {
3337 if (TI.isNoneType() || TI.isSimple()) {
3338 StringRef TypeName = TypeIndex::simpleTypeName(TI);
3339 // If the name ends with "*", create 2 logical types: a pointer and a
3340 // pointee type. TypeIndex is composed of a SympleTypeMode byte followed
3341 // by a SimpleTypeKind byte. The logical pointer will be identified by
3342 // the full TypeIndex value and the pointee by the SimpleTypeKind.
3343 return (TypeName.back() == '*') ? createPointerType(TI, TypeName)
3344 : createBaseType(TI, TypeName);
3345 }
3346
3347 LLVM_DEBUG({ W.printHex("TypeIndex not implemented: ", TI.getIndex()); });
3348 return nullptr;
3349 }
3350
3351 // The element has been finalized.
3352 if (Element->getIsFinalized())
3353 return Element;
3354
3355 // Add the element in case of a given parent.
3356 if (Parent)
3357 Parent->addElement(Element);
3358
3359 // Check for a composite type.
3360 LazyRandomTypeCollection &Types = types();
3361 CVType CVRecord = Types.getType(Index: TI);
3362 if (Error Err = finishVisitation(Record&: CVRecord, TI, Element)) {
3363 consumeError(Err: std::move(Err));
3364 return nullptr;
3365 }
3366 Element->setIsFinalized();
3367 return Element;
3368}
3369
3370void LVLogicalVisitor::processLines() {
3371 // Traverse the collected LF_UDT_SRC_LINE records and add the source line
3372 // information to the logical elements.
3373 for (const TypeIndex &Entry : Shared->LineRecords) {
3374 CVType CVRecord = ids().getType(Index: Entry);
3375 UdtSourceLineRecord Line;
3376 if (Error Err = TypeDeserializer::deserializeAs(
3377 CVT&: const_cast<CVType &>(CVRecord), Record&: Line))
3378 consumeError(Err: std::move(Err));
3379 else {
3380 LLVM_DEBUG({
3381 printTypeIndex("UDT", Line.getUDT(), StreamIPI);
3382 printTypeIndex("SourceFile", Line.getSourceFile(), StreamIPI);
3383 W.printNumber("LineNumber", Line.getLineNumber());
3384 });
3385
3386 // The TypeIndex returned by 'getUDT()' must point to an already
3387 // created logical element. If no logical element is found, it means
3388 // the LF_UDT_SRC_LINE is associated with a system TypeIndex.
3389 if (LVElement *Element = Shared->TypeRecords.find(
3390 StreamIdx: StreamTPI, TI: Line.getUDT(), /*Create=*/false)) {
3391 Element->setLineNumber(Line.getLineNumber());
3392 Element->setFilenameIndex(
3393 Shared->StringRecords.findIndex(TI: Line.getSourceFile()));
3394 }
3395 }
3396 }
3397}
3398
3399void LVLogicalVisitor::processNamespaces() {
3400 // Create namespaces.
3401 Shared->NamespaceDeduction.init();
3402}
3403
3404void LVLogicalVisitor::processFiles() { Shared->StringRecords.addFilenames(); }
3405
3406void LVLogicalVisitor::printRecords(raw_ostream &OS) const {
3407 if (!options().getInternalTag())
3408 return;
3409
3410 unsigned Count = 0;
3411 auto PrintItem = [&](StringRef Name) {
3412 auto NewLine = [&]() {
3413 if (++Count == 4) {
3414 Count = 0;
3415 OS << "\n";
3416 }
3417 };
3418 OS << format(Fmt: "%20s", Vals: Name.str().c_str());
3419 NewLine();
3420 };
3421
3422 OS << "\nTypes:\n";
3423 for (const TypeLeafKind &Kind : Shared->TypeKinds)
3424 PrintItem(formatTypeLeafKind(K: Kind));
3425 Shared->TypeKinds.clear();
3426
3427 Count = 0;
3428 OS << "\nSymbols:\n";
3429 for (const SymbolKind &Kind : Shared->SymbolKinds)
3430 PrintItem(LVCodeViewReader::getSymbolKindName(Kind));
3431 Shared->SymbolKinds.clear();
3432
3433 OS << "\n";
3434}
3435
3436Error LVLogicalVisitor::inlineSiteAnnotation(LVScope *AbstractFunction,
3437 LVScope *InlinedFunction,
3438 InlineSiteSym &InlineSite) {
3439 // Get the parent scope to update the address ranges of the nested
3440 // scope representing the inlined function.
3441 LVAddress ParentLowPC = 0;
3442 LVScope *Parent = InlinedFunction->getParentScope();
3443 if (const LVLocations *Locations = Parent->getRanges()) {
3444 if (!Locations->empty())
3445 ParentLowPC = (*Locations->begin())->getLowerAddress();
3446 }
3447
3448 // For the given inlinesite, get the initial line number and its
3449 // source filename. Update the logical scope representing it.
3450 uint32_t LineNumber = 0;
3451 StringRef Filename;
3452 LVInlineeInfo::iterator Iter = InlineeInfo.find(x: InlineSite.Inlinee);
3453 if (Iter != InlineeInfo.end()) {
3454 LineNumber = Iter->second.first;
3455 Filename = Iter->second.second;
3456 AbstractFunction->setLineNumber(LineNumber);
3457 // TODO: This part needs additional work in order to set properly the
3458 // correct filename in order to detect changes between filenames.
3459 // AbstractFunction->setFilename(Filename);
3460 }
3461
3462 LLVM_DEBUG({
3463 dbgs() << "inlineSiteAnnotation\n"
3464 << "Abstract: " << AbstractFunction->getName() << "\n"
3465 << "Inlined: " << InlinedFunction->getName() << "\n"
3466 << "Parent: " << Parent->getName() << "\n"
3467 << "Low PC: " << hexValue(ParentLowPC) << "\n";
3468 });
3469
3470 // Get the source lines if requested by command line option.
3471 if (!options().getPrintLines())
3472 return Error::success();
3473
3474 // Limitation: Currently we don't track changes in the FileOffset. The
3475 // side effects are the caller that it is unable to differentiate the
3476 // source filename for the inlined code.
3477 uint64_t CodeOffset = ParentLowPC;
3478 int32_t LineOffset = LineNumber;
3479 uint32_t FileOffset = 0;
3480
3481 auto UpdateClose = [&]() { LLVM_DEBUG({ dbgs() << ("\n"); }); };
3482 auto UpdateCodeOffset = [&](uint32_t Delta) {
3483 CodeOffset += Delta;
3484 LLVM_DEBUG({
3485 dbgs() << formatv(" code 0x{0} (+0x{1})", utohexstr(CodeOffset),
3486 utohexstr(Delta));
3487 });
3488 };
3489 auto UpdateLineOffset = [&](int32_t Delta) {
3490 LineOffset += Delta;
3491 LLVM_DEBUG({
3492 char Sign = Delta > 0 ? '+' : '-';
3493 dbgs() << formatv(" line {0} ({1}{2})", LineOffset, Sign,
3494 std::abs(Delta));
3495 });
3496 };
3497 auto UpdateFileOffset = [&](int32_t Offset) {
3498 FileOffset = Offset;
3499 LLVM_DEBUG({ dbgs() << formatv(" file {0}", FileOffset); });
3500 };
3501
3502 LVLines InlineeLines;
3503 auto CreateLine = [&]() {
3504 // Create the logical line record.
3505 LVLineDebug *Line = Reader->createLineDebug();
3506 Line->setAddress(CodeOffset);
3507 Line->setLineNumber(LineOffset);
3508 // TODO: This part needs additional work in order to set properly the
3509 // correct filename in order to detect changes between filenames.
3510 // Line->setFilename(Filename);
3511 InlineeLines.push_back(Elt: Line);
3512 };
3513
3514 bool SeenLowAddress = false;
3515 bool SeenHighAddress = false;
3516 uint64_t LowPC = 0;
3517 uint64_t HighPC = 0;
3518
3519 for (auto &Annot : InlineSite.annotations()) {
3520 LLVM_DEBUG({
3521 dbgs() << formatv(" {0}",
3522 fmt_align(toHex(Annot.Bytes), AlignStyle::Left, 9));
3523 });
3524
3525 // Use the opcode to interpret the integer values.
3526 switch (Annot.OpCode) {
3527 case BinaryAnnotationsOpCode::ChangeCodeOffset:
3528 case BinaryAnnotationsOpCode::CodeOffset:
3529 case BinaryAnnotationsOpCode::ChangeCodeLength:
3530 UpdateCodeOffset(Annot.U1);
3531 UpdateClose();
3532 if (Annot.OpCode == BinaryAnnotationsOpCode::ChangeCodeOffset) {
3533 CreateLine();
3534 LowPC = CodeOffset;
3535 SeenLowAddress = true;
3536 break;
3537 }
3538 if (Annot.OpCode == BinaryAnnotationsOpCode::ChangeCodeLength) {
3539 HighPC = CodeOffset - 1;
3540 SeenHighAddress = true;
3541 }
3542 break;
3543 case BinaryAnnotationsOpCode::ChangeCodeLengthAndCodeOffset:
3544 UpdateCodeOffset(Annot.U2);
3545 UpdateClose();
3546 break;
3547 case BinaryAnnotationsOpCode::ChangeLineOffset:
3548 case BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset:
3549 UpdateCodeOffset(Annot.U1);
3550 UpdateLineOffset(Annot.S1);
3551 UpdateClose();
3552 if (Annot.OpCode ==
3553 BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset)
3554 CreateLine();
3555 break;
3556 case BinaryAnnotationsOpCode::ChangeFile:
3557 UpdateFileOffset(Annot.U1);
3558 UpdateClose();
3559 break;
3560 default:
3561 break;
3562 }
3563 if (SeenLowAddress && SeenHighAddress) {
3564 SeenLowAddress = false;
3565 SeenHighAddress = false;
3566 InlinedFunction->addObject(LowerAddress: LowPC, UpperAddress: HighPC);
3567 }
3568 }
3569
3570 Reader->addInlineeLines(Scope: InlinedFunction, Lines&: InlineeLines);
3571 UpdateClose();
3572
3573 return Error::success();
3574}
3575