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_REL_INDIR
1145Error LVSymbolVisitor::visitKnownRecord(
1146 CVSymbol &Record, DefRangeRegisterRelIndirSym &DefRangeRegisterRelIndir) {
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.printBoolean("HasSpilledUDTMember",
1153 DefRangeRegisterRelIndir.hasSpilledUDTMember());
1154 W.printNumber("OffsetInParent", DefRangeRegisterRelIndir.offsetInParent());
1155 W.printNumber("BasePointerOffset",
1156 DefRangeRegisterRelIndir.Hdr.BasePointerOffset);
1157 W.printNumber("OffsetInUdt", DefRangeRegisterRelIndir.Hdr.OffsetInUdt);
1158 printLocalVariableAddrRange(DefRangeRegisterRelIndir.Range,
1159 DefRangeRegisterRelIndir.getRelocationOffset());
1160 printLocalVariableAddrGap(DefRangeRegisterRelIndir.Gaps);
1161 });
1162
1163 if (LVSymbol *Symbol = LocalSymbol) {
1164 Symbol->setHasCodeViewLocation();
1165 LocalSymbol = nullptr;
1166
1167 // Add location debug location. Operands: [Register, Offset, OffsetInUdt].
1168 dwarf::Attribute Attr =
1169 dwarf::Attribute(SymbolKind::S_DEFRANGE_REGISTER_REL_INDIR);
1170 const uint64_t Operand1 = DefRangeRegisterRelIndir.Hdr.Register;
1171 const uint64_t Operand2 = DefRangeRegisterRelIndir.Hdr.BasePointerOffset;
1172 const uint64_t Operand3 = DefRangeRegisterRelIndir.Hdr.OffsetInUdt;
1173
1174 const LocalVariableAddrRange Range = DefRangeRegisterRelIndir.Range;
1175 const LVAddress Address =
1176 Reader->linearAddress(Segment: Range.ISectStart, Offset: Range.OffsetStart);
1177
1178 Symbol->addLocation(Attr, LowPC: Address, HighPC: Address + Range.Range, SectionOffset: 0, LocDescOffset: 0);
1179 Symbol->addLocationOperands(Opcode: LVSmall(Attr), Operands: {Operand1, Operand2, Operand3});
1180 }
1181
1182 return Error::success();
1183}
1184
1185// S_DEFRANGE_REGISTER
1186Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
1187 DefRangeRegisterSym &DefRangeRegister) {
1188 // DefRanges don't have types, just registers and code offsets.
1189 LLVM_DEBUG({
1190 if (LocalSymbol)
1191 W.getOStream() << formatv("Symbol: {0}, ", LocalSymbol->getName());
1192
1193 W.printEnum("Register", uint16_t(DefRangeRegister.Hdr.Register),
1194 getRegisterNames(Reader->getCompileUnitCPUType()));
1195 W.printNumber("MayHaveNoName", DefRangeRegister.Hdr.MayHaveNoName);
1196 printLocalVariableAddrRange(DefRangeRegister.Range,
1197 DefRangeRegister.getRelocationOffset());
1198 printLocalVariableAddrGap(DefRangeRegister.Gaps);
1199 });
1200
1201 if (LVSymbol *Symbol = LocalSymbol) {
1202 Symbol->setHasCodeViewLocation();
1203 LocalSymbol = nullptr;
1204
1205 // Add location debug location. Operands: [Register, 0].
1206 dwarf::Attribute Attr = dwarf::Attribute(SymbolKind::S_DEFRANGE_REGISTER);
1207 uint64_t Operand1 = DefRangeRegister.Hdr.Register;
1208
1209 LocalVariableAddrRange Range = DefRangeRegister.Range;
1210 LVAddress Address =
1211 Reader->linearAddress(Segment: Range.ISectStart, Offset: Range.OffsetStart);
1212
1213 Symbol->addLocation(Attr, LowPC: Address, HighPC: Address + Range.Range, SectionOffset: 0, LocDescOffset: 0);
1214 Symbol->addLocationOperands(Opcode: LVSmall(Attr), Operands: {Operand1});
1215 }
1216
1217 return Error::success();
1218}
1219
1220// S_DEFRANGE_SUBFIELD_REGISTER
1221Error LVSymbolVisitor::visitKnownRecord(
1222 CVSymbol &Record, DefRangeSubfieldRegisterSym &DefRangeSubfieldRegister) {
1223 // DefRanges don't have types, just registers and code offsets.
1224 LLVM_DEBUG({
1225 if (LocalSymbol)
1226 W.getOStream() << formatv("Symbol: {0}, ", LocalSymbol->getName());
1227
1228 W.printEnum("Register", uint16_t(DefRangeSubfieldRegister.Hdr.Register),
1229 getRegisterNames(Reader->getCompileUnitCPUType()));
1230 W.printNumber("MayHaveNoName", DefRangeSubfieldRegister.Hdr.MayHaveNoName);
1231 W.printNumber("OffsetInParent",
1232 DefRangeSubfieldRegister.Hdr.OffsetInParent);
1233 printLocalVariableAddrRange(DefRangeSubfieldRegister.Range,
1234 DefRangeSubfieldRegister.getRelocationOffset());
1235 printLocalVariableAddrGap(DefRangeSubfieldRegister.Gaps);
1236 });
1237
1238 if (LVSymbol *Symbol = LocalSymbol) {
1239 Symbol->setHasCodeViewLocation();
1240 LocalSymbol = nullptr;
1241
1242 // Add location debug location. Operands: [Register, 0].
1243 dwarf::Attribute Attr =
1244 dwarf::Attribute(SymbolKind::S_DEFRANGE_SUBFIELD_REGISTER);
1245 uint64_t Operand1 = DefRangeSubfieldRegister.Hdr.Register;
1246
1247 LocalVariableAddrRange Range = DefRangeSubfieldRegister.Range;
1248 LVAddress Address =
1249 Reader->linearAddress(Segment: Range.ISectStart, Offset: Range.OffsetStart);
1250
1251 Symbol->addLocation(Attr, LowPC: Address, HighPC: Address + Range.Range, SectionOffset: 0, LocDescOffset: 0);
1252 Symbol->addLocationOperands(Opcode: LVSmall(Attr), Operands: {Operand1});
1253 }
1254
1255 return Error::success();
1256}
1257
1258// S_DEFRANGE_SUBFIELD
1259Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
1260 DefRangeSubfieldSym &DefRangeSubfield) {
1261 // DefRanges don't have types, just registers and code offsets.
1262 LLVM_DEBUG({
1263 if (LocalSymbol)
1264 W.getOStream() << formatv("Symbol: {0}, ", LocalSymbol->getName());
1265
1266 if (ObjDelegate) {
1267 DebugStringTableSubsectionRef Strings = ObjDelegate->getStringTable();
1268 auto ExpectedProgram = Strings.getString(DefRangeSubfield.Program);
1269 if (!ExpectedProgram) {
1270 consumeError(ExpectedProgram.takeError());
1271 return llvm::make_error<CodeViewError>(
1272 "String table offset outside of bounds of String Table!");
1273 }
1274 W.printString("Program", *ExpectedProgram);
1275 }
1276 W.printNumber("OffsetInParent", DefRangeSubfield.OffsetInParent);
1277 printLocalVariableAddrRange(DefRangeSubfield.Range,
1278 DefRangeSubfield.getRelocationOffset());
1279 printLocalVariableAddrGap(DefRangeSubfield.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_SUBFIELD);
1288 uint64_t Operand1 = DefRangeSubfield.Program;
1289
1290 LocalVariableAddrRange Range = DefRangeSubfield.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_DEFRANGE
1302Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
1303 DefRangeSym &DefRange) {
1304 // DefRanges don't have types, just registers and code offsets.
1305 LLVM_DEBUG({
1306 if (LocalSymbol)
1307 W.getOStream() << formatv("Symbol: {0}, ", LocalSymbol->getName());
1308
1309 if (ObjDelegate) {
1310 DebugStringTableSubsectionRef Strings = ObjDelegate->getStringTable();
1311 auto ExpectedProgram = Strings.getString(DefRange.Program);
1312 if (!ExpectedProgram) {
1313 consumeError(ExpectedProgram.takeError());
1314 return llvm::make_error<CodeViewError>(
1315 "String table offset outside of bounds of String Table!");
1316 }
1317 W.printString("Program", *ExpectedProgram);
1318 }
1319 printLocalVariableAddrRange(DefRange.Range, DefRange.getRelocationOffset());
1320 printLocalVariableAddrGap(DefRange.Gaps);
1321 });
1322
1323 if (LVSymbol *Symbol = LocalSymbol) {
1324 Symbol->setHasCodeViewLocation();
1325 LocalSymbol = nullptr;
1326
1327 // Add location debug location. Operands: [Program, 0].
1328 dwarf::Attribute Attr = dwarf::Attribute(SymbolKind::S_DEFRANGE);
1329 uint64_t Operand1 = DefRange.Program;
1330
1331 LocalVariableAddrRange Range = DefRange.Range;
1332 LVAddress Address =
1333 Reader->linearAddress(Segment: Range.ISectStart, Offset: Range.OffsetStart);
1334
1335 Symbol->addLocation(Attr, LowPC: Address, HighPC: Address + Range.Range, SectionOffset: 0, LocDescOffset: 0);
1336 Symbol->addLocationOperands(Opcode: LVSmall(Attr), Operands: {Operand1, /*Operand2=*/0});
1337 }
1338
1339 return Error::success();
1340}
1341
1342// S_FRAMEPROC
1343Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
1344 FrameProcSym &FrameProc) {
1345 if (LVScope *Function = LogicalVisitor->getReaderScope()) {
1346 // S_FRAMEPROC contains extra information for the function described
1347 // by any of the previous generated records:
1348 // S_GPROC32, S_LPROC32, S_LPROC32_ID, S_GPROC32_ID.
1349
1350 // The generated sequence is:
1351 // S_GPROC32_ID ...
1352 // S_FRAMEPROC ...
1353
1354 // Collect additional inline flags for the current scope function.
1355 FrameProcedureOptions Flags = FrameProc.Flags;
1356 if (FrameProcedureOptions::MarkedInline ==
1357 (Flags & FrameProcedureOptions::MarkedInline))
1358 Function->setInlineCode(dwarf::DW_INL_declared_inlined);
1359 if (FrameProcedureOptions::Inlined ==
1360 (Flags & FrameProcedureOptions::Inlined))
1361 Function->setInlineCode(dwarf::DW_INL_inlined);
1362
1363 // To determine the symbol kind for any symbol declared in that function,
1364 // we can access the S_FRAMEPROC for the parent scope function. It contains
1365 // information about the local fp and param fp registers and compare with
1366 // the register in the S_REGREL32 to get a match.
1367 codeview::CPUType CPU = Reader->getCompileUnitCPUType();
1368 LocalFrameRegister = FrameProc.getLocalFramePtrReg(CPU);
1369 ParamFrameRegister = FrameProc.getParamFramePtrReg(CPU);
1370 }
1371
1372 return Error::success();
1373}
1374
1375// S_GDATA32, S_LDATA32, S_LMANDATA, S_GMANDATA
1376Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record, DataSym &Data) {
1377 LLVM_DEBUG({
1378 printTypeIndex("Type", Data.Type);
1379 W.printString("DisplayName", Data.Name);
1380 });
1381
1382 if (LVSymbol *Symbol = LogicalVisitor->CurrentSymbol) {
1383 StringRef LinkageName;
1384 if (ObjDelegate)
1385 ObjDelegate->getLinkageName(RelocOffset: Data.getRelocationOffset(), Offset: Data.DataOffset,
1386 RelocSym: &LinkageName);
1387
1388 Symbol->setName(Data.Name);
1389 Symbol->setLinkageName(LinkageName);
1390
1391 // The MSVC generates local data as initialization for aggregates. It
1392 // contains the address for an initialization function.
1393 // The symbols contains the '$initializer$' pattern. Allow them only if
1394 // the '--internal=system' option is given.
1395 // 0 | S_LDATA32 `Struct$initializer$`
1396 // type = 0x1040 (void ()*)
1397 if (getReader().isSystemEntry(Element: Symbol) && !options().getAttributeSystem()) {
1398 Symbol->resetIncludeInPrint();
1399 return Error::success();
1400 }
1401
1402 if (LVScope *Namespace = Shared->NamespaceDeduction.get(ScopedName: Data.Name)) {
1403 // The variable is already at different scope. In order to reflect
1404 // the correct parent, move it to the namespace.
1405 if (Symbol->getParentScope()->removeElement(Element: Symbol))
1406 Namespace->addElement(Symbol);
1407 }
1408
1409 Symbol->setType(LogicalVisitor->getElement(StreamIdx: StreamTPI, TI: Data.Type));
1410 if (Record.kind() == SymbolKind::S_GDATA32)
1411 Symbol->setIsExternal();
1412 }
1413
1414 return Error::success();
1415}
1416
1417// S_INLINESITE
1418Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
1419 InlineSiteSym &InlineSite) {
1420 LLVM_DEBUG({ printTypeIndex("Inlinee", InlineSite.Inlinee); });
1421
1422 if (LVScope *InlinedFunction = LogicalVisitor->CurrentScope) {
1423 LVScope *AbstractFunction = Reader->createScopeFunction();
1424 AbstractFunction->setIsSubprogram();
1425 AbstractFunction->setTag(dwarf::DW_TAG_subprogram);
1426 AbstractFunction->setInlineCode(dwarf::DW_INL_inlined);
1427 AbstractFunction->setIsInlinedAbstract();
1428 InlinedFunction->setReference(AbstractFunction);
1429
1430 LogicalVisitor->startProcessArgumentList();
1431 // 'Inlinee' is a Type ID.
1432 CVType CVFunctionType = Ids.getType(Index: InlineSite.Inlinee);
1433 if (Error Err = LogicalVisitor->finishVisitation(
1434 Record&: CVFunctionType, TI: InlineSite.Inlinee, Element: AbstractFunction))
1435 return Err;
1436 LogicalVisitor->stopProcessArgumentList();
1437
1438 // For inlined functions set the linkage name to be the same as
1439 // the name. It used to find their lines and ranges.
1440 StringRef Name = AbstractFunction->getName();
1441 InlinedFunction->setName(Name);
1442 InlinedFunction->setLinkageName(Name);
1443
1444 // Process annotation bytes to calculate code and line offsets.
1445 if (Error Err = LogicalVisitor->inlineSiteAnnotation(
1446 AbstractFunction, InlinedFunction, InlineSite))
1447 return Err;
1448 }
1449
1450 return Error::success();
1451}
1452
1453// S_LOCAL
1454Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record, LocalSym &Local) {
1455 LLVM_DEBUG({
1456 printTypeIndex("Type", Local.Type);
1457 W.printFlags("Flags", uint16_t(Local.Flags), getLocalFlagNames());
1458 W.printString("VarName", Local.Name);
1459 });
1460
1461 if (LVSymbol *Symbol = LogicalVisitor->CurrentSymbol) {
1462 Symbol->setName(Local.Name);
1463
1464 // Symbol was created as 'variable'; determine its real kind.
1465 Symbol->resetIsVariable();
1466
1467 // Be sure the 'this' symbol is marked as 'compiler generated'.
1468 if (bool(Local.Flags & LocalSymFlags::IsCompilerGenerated) ||
1469 Local.Name == "this") {
1470 Symbol->setIsArtificial();
1471 Symbol->setIsParameter();
1472 } else {
1473 bool(Local.Flags & LocalSymFlags::IsParameter) ? Symbol->setIsParameter()
1474 : Symbol->setIsVariable();
1475 }
1476
1477 // Update correct debug information tag.
1478 if (Symbol->getIsParameter())
1479 Symbol->setTag(dwarf::DW_TAG_formal_parameter);
1480
1481 setLocalVariableType(Symbol, TI: Local.Type);
1482
1483 // The CodeView records (S_DEFFRAME_*) describing debug location for
1484 // this symbol, do not have any direct reference to it. Those records
1485 // are emitted after this symbol. Record the current symbol.
1486 LocalSymbol = Symbol;
1487 }
1488
1489 return Error::success();
1490}
1491
1492// S_OBJNAME
1493Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record, ObjNameSym &ObjName) {
1494 LLVM_DEBUG({
1495 W.printHex("Signature", ObjName.Signature);
1496 W.printString("ObjectName", ObjName.Name);
1497 });
1498
1499 CurrentObjectName = ObjName.Name;
1500 return Error::success();
1501}
1502
1503// S_GPROC32, S_LPROC32, S_LPROC32_ID, S_GPROC32_ID
1504Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record, ProcSym &Proc) {
1505 if (InFunctionScope)
1506 return llvm::make_error<CodeViewError>(Args: "Visiting a ProcSym while inside "
1507 "function scope!");
1508
1509 InFunctionScope = true;
1510
1511 LLVM_DEBUG({
1512 printTypeIndex("FunctionType", Proc.FunctionType);
1513 W.printHex("Segment", Proc.Segment);
1514 W.printFlags("Flags", static_cast<uint8_t>(Proc.Flags),
1515 getProcSymFlagNames());
1516 W.printString("DisplayName", Proc.Name);
1517 });
1518
1519 // Clang and Microsoft generated different debug information records:
1520 // For functions definitions:
1521 // Clang: S_GPROC32 -> LF_FUNC_ID -> LF_PROCEDURE
1522 // Microsoft: S_GPROC32 -> LF_PROCEDURE
1523
1524 // For member function definition:
1525 // Clang: S_GPROC32 -> LF_MFUNC_ID -> LF_MFUNCTION
1526 // Microsoft: S_GPROC32 -> LF_MFUNCTION
1527 // In order to support both sequences, if we found LF_FUNCTION_ID, just
1528 // get the TypeIndex for LF_PROCEDURE.
1529
1530 // For the given test case, we have the sequence:
1531 // namespace NSP_local {
1532 // void foo_local() {
1533 // }
1534 // }
1535 //
1536 // 0x1000 | LF_STRING_ID String: NSP_local
1537 // 0x1002 | LF_PROCEDURE
1538 // return type = 0x0003 (void), # args = 0, param list = 0x1001
1539 // calling conv = cdecl, options = None
1540 // 0x1003 | LF_FUNC_ID
1541 // name = foo_local, type = 0x1002, parent scope = 0x1000
1542 // 0 | S_GPROC32_ID `NSP_local::foo_local`
1543 // type = `0x1003 (foo_local)`
1544 // 0x1004 | LF_STRING_ID String: suite
1545 // 0x1005 | LF_STRING_ID String: suite_local.cpp
1546 //
1547 // The LF_STRING_ID can hold different information:
1548 // 0x1000 - The enclosing namespace.
1549 // 0x1004 - The compile unit directory name.
1550 // 0x1005 - The compile unit name.
1551 //
1552 // Before deducting its scope, we need to evaluate its type and create any
1553 // associated namespaces.
1554 if (LVScope *Function = LogicalVisitor->CurrentScope) {
1555 StringRef LinkageName;
1556 if (ObjDelegate)
1557 ObjDelegate->getLinkageName(RelocOffset: Proc.getRelocationOffset(), Offset: Proc.CodeOffset,
1558 RelocSym: &LinkageName);
1559
1560 // The line table can be accessed using the linkage name.
1561 Reader->addToSymbolTable(Name: LinkageName, Function);
1562 Function->setName(Proc.Name);
1563 Function->setLinkageName(LinkageName);
1564
1565 if (options().getGeneralCollectRanges()) {
1566 // Record converted segment::offset addressing for this scope.
1567 LVAddress Addendum = Reader->getSymbolTableAddress(Name: LinkageName);
1568 LVAddress LowPC =
1569 Reader->linearAddress(Segment: Proc.Segment, Offset: Proc.CodeOffset, Addendum);
1570 LVAddress HighPC = LowPC + Proc.CodeSize - 1;
1571 Function->addObject(LowerAddress: LowPC, UpperAddress: HighPC);
1572
1573 // If the scope is a function, add it to the public names.
1574 if ((options().getAttributePublics() || options().getPrintAnyLine()) &&
1575 !Function->getIsInlinedFunction())
1576 Reader->getCompileUnit()->addPublicName(Scope: Function, LowPC, HighPC);
1577 }
1578
1579 if (Function->getIsSystem() && !options().getAttributeSystem()) {
1580 Function->resetIncludeInPrint();
1581 return Error::success();
1582 }
1583
1584 TypeIndex TIFunctionType = Proc.FunctionType;
1585 if (TIFunctionType.isSimple())
1586 Function->setType(LogicalVisitor->getElement(StreamIdx: StreamTPI, TI: TIFunctionType));
1587 else {
1588 // We have to detect the correct stream, using the lexical parent
1589 // name, as there is not other obvious way to get the stream.
1590 // Normal function: LF_FUNC_ID (TPI)/(IPI)
1591 // LF_PROCEDURE (TPI)
1592 // Lambda function: LF_MFUNCTION (TPI)
1593 // Member function: LF_MFUNC_ID (TPI)/(IPI)
1594
1595 StringRef OuterComponent;
1596 std::tie(args&: OuterComponent, args: std::ignore) = getInnerComponent(Name: Proc.Name);
1597 TypeIndex TI = Shared->ForwardReferences.find(Name: OuterComponent);
1598
1599 std::optional<CVType> CVFunctionType;
1600 auto GetRecordType = [&]() -> bool {
1601 CVFunctionType = Ids.tryGetType(Index: TIFunctionType);
1602 if (!CVFunctionType)
1603 return false;
1604
1605 if (TI.isNoneType())
1606 // Normal function.
1607 if (CVFunctionType->kind() == LF_FUNC_ID)
1608 return true;
1609
1610 // Member function.
1611 return (CVFunctionType->kind() == LF_MFUNC_ID);
1612 };
1613
1614 // We can have a LF_FUNC_ID, LF_PROCEDURE or LF_MFUNCTION.
1615 if (!GetRecordType()) {
1616 CVFunctionType = Types.tryGetType(Index: TIFunctionType);
1617 if (!CVFunctionType)
1618 return llvm::make_error<CodeViewError>(Args: "Invalid type index");
1619 }
1620
1621 if (Error Err = LogicalVisitor->finishVisitation(
1622 Record&: *CVFunctionType, TI: TIFunctionType, Element: Function))
1623 return Err;
1624 }
1625
1626 if (Record.kind() == SymbolKind::S_GPROC32 ||
1627 Record.kind() == SymbolKind::S_GPROC32_ID)
1628 Function->setIsExternal();
1629
1630 // We don't have a way to see if the symbol is compiler generated. Use
1631 // the linkage name, to detect `scalar deleting destructor' functions.
1632 std::string DemangledSymbol = demangle(MangledName: LinkageName);
1633 if (DemangledSymbol.find(s: "scalar deleting dtor") != std::string::npos) {
1634 Function->setIsArtificial();
1635 } else {
1636 // Clang generates global ctor and dtor names containing the substrings:
1637 // 'dynamic initializer for' and 'dynamic atexit destructor for'.
1638 if (DemangledSymbol.find(s: "dynamic atexit destructor for") !=
1639 std::string::npos)
1640 Function->setIsArtificial();
1641 }
1642 }
1643
1644 return Error::success();
1645}
1646
1647// S_END
1648Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
1649 ScopeEndSym &ScopeEnd) {
1650 InFunctionScope = false;
1651 return Error::success();
1652}
1653
1654// S_THUNK32
1655Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record, Thunk32Sym &Thunk) {
1656 if (InFunctionScope)
1657 return llvm::make_error<CodeViewError>(Args: "Visiting a Thunk32Sym while inside "
1658 "function scope!");
1659
1660 InFunctionScope = true;
1661
1662 LLVM_DEBUG({
1663 W.printHex("Segment", Thunk.Segment);
1664 W.printString("Name", Thunk.Name);
1665 });
1666
1667 if (LVScope *Function = LogicalVisitor->CurrentScope)
1668 Function->setName(Thunk.Name);
1669
1670 return Error::success();
1671}
1672
1673// S_UDT, S_COBOLUDT
1674Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record, UDTSym &UDT) {
1675 LLVM_DEBUG({
1676 printTypeIndex("Type", UDT.Type);
1677 W.printString("UDTName", UDT.Name);
1678 });
1679
1680 if (LVType *Type = LogicalVisitor->CurrentType) {
1681 if (LVScope *Namespace = Shared->NamespaceDeduction.get(ScopedName: UDT.Name)) {
1682 if (Type->getParentScope()->removeElement(Element: Type))
1683 Namespace->addElement(Type);
1684 }
1685
1686 Type->setName(UDT.Name);
1687
1688 // We have to determine if the typedef is a real C/C++ definition or is
1689 // the S_UDT record that describe all the user defined types.
1690 // 0 | S_UDT `Name` original type = 0x1009
1691 // 0x1009 | LF_STRUCTURE `Name`
1692 // Ignore type definitions for RTTI types:
1693 // _s__RTTIBaseClassArray, _s__RTTIBaseClassDescriptor,
1694 // _s__RTTICompleteObjectLocator, _s__RTTIClassHierarchyDescriptor.
1695 if (getReader().isSystemEntry(Element: Type))
1696 Type->resetIncludeInPrint();
1697 else {
1698 StringRef RecordName = getRecordName(Types, TI: UDT.Type);
1699 if (UDT.Name == RecordName)
1700 Type->resetIncludeInPrint();
1701 Type->setType(LogicalVisitor->getElement(StreamIdx: StreamTPI, TI: UDT.Type));
1702 }
1703 }
1704
1705 return Error::success();
1706}
1707
1708// S_UNAMESPACE
1709Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record,
1710 UsingNamespaceSym &UN) {
1711 LLVM_DEBUG({ W.printString("Namespace", UN.Name); });
1712 return Error::success();
1713}
1714
1715// S_ARMSWITCHTABLE
1716Error LVSymbolVisitor::visitKnownRecord(CVSymbol &CVR,
1717 JumpTableSym &JumpTable) {
1718 LLVM_DEBUG({
1719 W.printHex("BaseOffset", JumpTable.BaseOffset);
1720 W.printNumber("BaseSegment", JumpTable.BaseSegment);
1721 W.printFlags("SwitchType", static_cast<uint16_t>(JumpTable.SwitchType),
1722 getJumpTableEntrySizeNames());
1723 W.printHex("BranchOffset", JumpTable.BranchOffset);
1724 W.printHex("TableOffset", JumpTable.TableOffset);
1725 W.printNumber("BranchSegment", JumpTable.BranchSegment);
1726 W.printNumber("TableSegment", JumpTable.TableSegment);
1727 W.printNumber("EntriesCount", JumpTable.EntriesCount);
1728 });
1729 return Error::success();
1730}
1731
1732// S_CALLERS, S_CALLEES, S_INLINEES
1733Error LVSymbolVisitor::visitKnownRecord(CVSymbol &Record, CallerSym &Caller) {
1734 LLVM_DEBUG({
1735 llvm::StringRef FieldName;
1736 switch (Caller.getKind()) {
1737 case SymbolRecordKind::CallerSym:
1738 FieldName = "Callee";
1739 break;
1740 case SymbolRecordKind::CalleeSym:
1741 FieldName = "Caller";
1742 break;
1743 case SymbolRecordKind::InlineesSym:
1744 FieldName = "Inlinee";
1745 break;
1746 default:
1747 return llvm::make_error<CodeViewError>(
1748 "Unknown CV Record type for a CallerSym object!");
1749 }
1750 for (auto FuncID : Caller.Indices) {
1751 printTypeIndex(FieldName, FuncID);
1752 }
1753 });
1754 return Error::success();
1755}
1756
1757void LVSymbolVisitor::setLocalVariableType(LVSymbol *Symbol, TypeIndex TI) {
1758 LVElement *Element = LogicalVisitor->getElement(StreamIdx: StreamTPI, TI);
1759 if (Element && Element->getIsScoped()) {
1760 // We have a local type. Find its parent function.
1761 LVScope *Parent = Symbol->getFunctionParent();
1762 // The element representing the type has been already finalized. If
1763 // the type is an aggregate type, its members have been already added.
1764 // As the type is local, its level will be changed.
1765
1766 // FIXME: Currently the algorithm used to scope lambda functions is
1767 // incorrect. Before we allocate the type at this scope, check if is
1768 // already allocated in other scope.
1769 if (!Element->getParentScope()) {
1770 Parent->addElement(Element);
1771 Element->updateLevel(Parent);
1772 }
1773 }
1774 Symbol->setType(Element);
1775}
1776
1777#undef DEBUG_TYPE
1778#define DEBUG_TYPE "CodeViewLogicalVisitor"
1779
1780//===----------------------------------------------------------------------===//
1781// Logical visitor.
1782//===----------------------------------------------------------------------===//
1783LVLogicalVisitor::LVLogicalVisitor(LVCodeViewReader *Reader, ScopedPrinter &W,
1784 InputFile &Input)
1785 : Reader(Reader), W(W), Input(Input) {
1786 // The LogicalVisitor connects the CodeViewReader with the visitors that
1787 // traverse the types, symbols, etc. Do any initialization that is needed.
1788 Shared = std::make_shared<LVShared>(args&: Reader, args: this);
1789}
1790
1791void LVLogicalVisitor::printTypeIndex(StringRef FieldName, TypeIndex TI,
1792 uint32_t StreamIdx) {
1793 codeview::printTypeIndex(Printer&: W, FieldName, TI,
1794 Types&: StreamIdx == StreamTPI ? types() : ids());
1795}
1796
1797void LVLogicalVisitor::printTypeBegin(CVType &Record, TypeIndex TI,
1798 LVElement *Element, uint32_t StreamIdx) {
1799 W.getOStream() << "\n";
1800 W.startLine() << formatTypeLeafKind(K: Record.kind());
1801 W.getOStream() << " (" << HexNumber(TI.getIndex()) << ")";
1802 W.getOStream() << " {\n";
1803 W.indent();
1804 W.printEnum(Label: "TypeLeafKind", Value: unsigned(Record.kind()), EnumValues: ArrayRef(LeafTypeNames));
1805 printTypeIndex(FieldName: "TI", TI, StreamIdx);
1806 W.startLine() << "Element: " << HexNumber(Element->getOffset()) << " "
1807 << Element->getName() << "\n";
1808}
1809
1810void LVLogicalVisitor::printTypeEnd(CVType &Record) {
1811 W.unindent();
1812 W.startLine() << "}\n";
1813}
1814
1815void LVLogicalVisitor::printMemberBegin(CVMemberRecord &Record, TypeIndex TI,
1816 LVElement *Element,
1817 uint32_t StreamIdx) {
1818 W.getOStream() << "\n";
1819 W.startLine() << formatTypeLeafKind(K: Record.Kind);
1820 W.getOStream() << " (" << HexNumber(TI.getIndex()) << ")";
1821 W.getOStream() << " {\n";
1822 W.indent();
1823 W.printEnum(Label: "TypeLeafKind", Value: unsigned(Record.Kind), EnumValues: ArrayRef(LeafTypeNames));
1824 printTypeIndex(FieldName: "TI", TI, StreamIdx);
1825 W.startLine() << "Element: " << HexNumber(Element->getOffset()) << " "
1826 << Element->getName() << "\n";
1827}
1828
1829void LVLogicalVisitor::printMemberEnd(CVMemberRecord &Record) {
1830 W.unindent();
1831 W.startLine() << "}\n";
1832}
1833
1834Error LVLogicalVisitor::visitUnknownType(CVType &Record, TypeIndex TI) {
1835 LLVM_DEBUG({
1836 printTypeIndex("\nTI", TI, StreamTPI);
1837 W.printNumber("Length", uint32_t(Record.content().size()));
1838 });
1839 return Error::success();
1840}
1841
1842// LF_ARGLIST (TPI)
1843Error LVLogicalVisitor::visitKnownRecord(CVType &Record, ArgListRecord &Args,
1844 TypeIndex TI, LVElement *Element) {
1845 ArrayRef<TypeIndex> Indices = Args.getIndices();
1846 uint32_t Size = Indices.size();
1847 LLVM_DEBUG({
1848 printTypeBegin(Record, TI, Element, StreamTPI);
1849 W.printNumber("NumArgs", Size);
1850 ListScope Arguments(W, "Arguments");
1851 for (uint32_t I = 0; I < Size; ++I)
1852 printTypeIndex("ArgType", Indices[I], StreamTPI);
1853 printTypeEnd(Record);
1854 });
1855
1856 LVScope *Function = static_cast<LVScope *>(Element);
1857 for (uint32_t Index = 0; Index < Size; ++Index) {
1858 TypeIndex ParameterType = Indices[Index];
1859 createParameter(TI: ParameterType, Name: StringRef(), Parent: Function);
1860 }
1861
1862 return Error::success();
1863}
1864
1865// LF_ARRAY (TPI)
1866Error LVLogicalVisitor::visitKnownRecord(CVType &Record, ArrayRecord &AT,
1867 TypeIndex TI, LVElement *Element) {
1868 LLVM_DEBUG({
1869 printTypeBegin(Record, TI, Element, StreamTPI);
1870 printTypeIndex("ElementType", AT.getElementType(), StreamTPI);
1871 printTypeIndex("IndexType", AT.getIndexType(), StreamTPI);
1872 W.printNumber("SizeOf", AT.getSize());
1873 W.printString("Name", AT.getName());
1874 printTypeEnd(Record);
1875 });
1876
1877 if (Element->getIsFinalized())
1878 return Error::success();
1879 Element->setIsFinalized();
1880
1881 LVScopeArray *Array = static_cast<LVScopeArray *>(Element);
1882 if (!Array)
1883 return Error::success();
1884
1885 Reader->getCompileUnit()->addElement(Scope: Array);
1886 TypeIndex TIElementType = AT.getElementType();
1887
1888 LVType *PrevSubrange = nullptr;
1889 LazyRandomTypeCollection &Types = types();
1890
1891 // As the logical view is modeled on DWARF, for each dimension we have to
1892 // create a DW_TAG_subrange_type, with dimension size.
1893 // The subrange type can be: unsigned __int32 or unsigned __int64.
1894 auto AddSubrangeType = [&](ArrayRecord &AR) {
1895 LVType *Subrange = Reader->createTypeSubrange();
1896 Subrange->setTag(dwarf::DW_TAG_subrange_type);
1897 Subrange->setType(getElement(StreamIdx: StreamTPI, TI: AR.getIndexType()));
1898 Subrange->setCount(AR.getSize());
1899 Subrange->setOffset(
1900 TIElementType.isSimple()
1901 ? (uint32_t)(TypeLeafKind)TIElementType.getSimpleKind()
1902 : TIElementType.getIndex());
1903 Array->addElement(Type: Subrange);
1904
1905 if (PrevSubrange)
1906 if (int64_t Count = Subrange->getCount())
1907 PrevSubrange->setCount(PrevSubrange->getCount() / Count);
1908 PrevSubrange = Subrange;
1909 };
1910
1911 // Preserve the original TypeIndex; it would be updated in the case of:
1912 // - The array type contains qualifiers.
1913 // - In multidimensional arrays, the last LF_ARRAY entry contains the type.
1914 TypeIndex TIArrayType;
1915
1916 // For each dimension in the array, there is a LF_ARRAY entry. The last
1917 // entry contains the array type, which can be a LF_MODIFIER in the case
1918 // of the type being modified by a qualifier (const, etc).
1919 ArrayRecord AR(AT);
1920 CVType CVEntry = Record;
1921 while (CVEntry.kind() == LF_ARRAY) {
1922 // Create the subrange information, required by the logical view. Once
1923 // the array has been processed, the dimension sizes will updated, as
1924 // the sizes are a progression. For instance:
1925 // sizeof(int) = 4
1926 // int Array[2]; Sizes: 8 Dim: 8 / 4 -> [2]
1927 // int Array[2][3]; Sizes: 24, 12 Dim: 24 / 12 -> [2]
1928 // Dim: 12 / 4 -> [3]
1929 // int Array[2][3][4]; sizes: 96, 48, 16 Dim: 96 / 48 -> [2]
1930 // Dim: 48 / 16 -> [3]
1931 // Dim: 16 / 4 -> [4]
1932 AddSubrangeType(AR);
1933 TIArrayType = TIElementType;
1934
1935 // The current ElementType can be a modifier, in which case we need to
1936 // get the type being modified.
1937 // If TypeIndex is not a simple type, check if we have a qualified type.
1938 if (!TIElementType.isSimple()) {
1939 CVType CVElementType = Types.getType(Index: TIElementType);
1940 if (CVElementType.kind() == LF_MODIFIER) {
1941 LVElement *QualifiedType =
1942 Shared->TypeRecords.find(StreamIdx: StreamTPI, TI: TIElementType);
1943 if (Error Err =
1944 finishVisitation(Record&: CVElementType, TI: TIElementType, Element: QualifiedType))
1945 return Err;
1946 // Get the TypeIndex of the type that the LF_MODIFIER modifies.
1947 TIElementType = getModifiedType(CVT: CVElementType);
1948 }
1949 }
1950 // Ends the traversal, as we have reached a simple type (int, char, etc).
1951 if (TIElementType.isSimple())
1952 break;
1953
1954 // Read next dimension linked entry, if any.
1955 CVEntry = Types.getType(Index: TIElementType);
1956 if (Error Err = TypeDeserializer::deserializeAs(
1957 CVT&: const_cast<CVType &>(CVEntry), Record&: AR)) {
1958 consumeError(Err: std::move(Err));
1959 break;
1960 }
1961 TIElementType = AR.getElementType();
1962 // NOTE: The typeindex has a value of: 0x0280.0000
1963 getTrueType(TI&: TIElementType);
1964 }
1965
1966 Array->setName(AT.getName());
1967 TIArrayType = Shared->ForwardReferences.remap(TI: TIArrayType);
1968 Array->setType(getElement(StreamIdx: StreamTPI, TI: TIArrayType));
1969
1970 if (PrevSubrange)
1971 // In the case of an aggregate type (class, struct, union, interface),
1972 // get the aggregate size. As the original record is pointing to its
1973 // reference, we have to update it.
1974 if (uint64_t Size =
1975 isAggregate(CVT: CVEntry)
1976 ? getSizeInBytesForTypeRecord(CVT: Types.getType(Index: TIArrayType))
1977 : getSizeInBytesForTypeIndex(TI: TIElementType))
1978 PrevSubrange->setCount(PrevSubrange->getCount() / Size);
1979
1980 return Error::success();
1981}
1982
1983// LF_BITFIELD (TPI)
1984Error LVLogicalVisitor::visitKnownRecord(CVType &Record, BitFieldRecord &BF,
1985 TypeIndex TI, LVElement *Element) {
1986 LLVM_DEBUG({
1987 printTypeBegin(Record, TI, Element, StreamTPI);
1988 printTypeIndex("Type", TI, StreamTPI);
1989 W.printNumber("BitSize", BF.getBitSize());
1990 W.printNumber("BitOffset", BF.getBitOffset());
1991 printTypeEnd(Record);
1992 });
1993
1994 Element->setType(getElement(StreamIdx: StreamTPI, TI: BF.getType()));
1995 Element->setBitSize(BF.getBitSize());
1996 return Error::success();
1997}
1998
1999// LF_BUILDINFO (TPI)/(IPI)
2000Error LVLogicalVisitor::visitKnownRecord(CVType &Record, BuildInfoRecord &BI,
2001 TypeIndex TI, LVElement *Element) {
2002 LLVM_DEBUG({
2003 printTypeBegin(Record, TI, Element, StreamIPI);
2004 W.printNumber("NumArgs", static_cast<uint32_t>(BI.getArgs().size()));
2005 ListScope Arguments(W, "Arguments");
2006 for (TypeIndex Arg : BI.getArgs())
2007 printTypeIndex("ArgType", Arg, StreamIPI);
2008 printTypeEnd(Record);
2009 });
2010
2011 // The given 'Element' refers to the current compilation unit.
2012 // All the args are references into the TPI/IPI stream.
2013 TypeIndex TIName = BI.getArgs()[BuildInfoRecord::BuildInfoArg::SourceFile];
2014 std::string Name = std::string(ids().getTypeName(Index: TIName));
2015
2016 // There are cases where LF_BUILDINFO fields are empty.
2017 if (!Name.empty())
2018 Element->setName(Name);
2019
2020 return Error::success();
2021}
2022
2023// LF_CLASS, LF_STRUCTURE, LF_INTERFACE (TPI)
2024Error LVLogicalVisitor::visitKnownRecord(CVType &Record, ClassRecord &Class,
2025 TypeIndex TI, LVElement *Element) {
2026 LLVM_DEBUG({
2027 printTypeBegin(Record, TI, Element, StreamTPI);
2028 W.printNumber("MemberCount", Class.getMemberCount());
2029 printTypeIndex("FieldList", Class.getFieldList(), StreamTPI);
2030 printTypeIndex("DerivedFrom", Class.getDerivationList(), StreamTPI);
2031 printTypeIndex("VShape", Class.getVTableShape(), StreamTPI);
2032 W.printNumber("SizeOf", Class.getSize());
2033 W.printString("Name", Class.getName());
2034 if (Class.hasUniqueName())
2035 W.printString("UniqueName", Class.getUniqueName());
2036 printTypeEnd(Record);
2037 });
2038
2039 if (Element->getIsFinalized())
2040 return Error::success();
2041 Element->setIsFinalized();
2042
2043 LVScopeAggregate *Scope = static_cast<LVScopeAggregate *>(Element);
2044 if (!Scope)
2045 return Error::success();
2046
2047 Scope->setName(Class.getName());
2048 if (Class.hasUniqueName())
2049 Scope->setLinkageName(Class.getUniqueName());
2050 Scope->setBitSize(Class.getSize() * DWARF_CHAR_BIT);
2051
2052 if (Class.isNested()) {
2053 Scope->setIsNested();
2054 createParents(ScopedName: Class.getName(), Element: Scope);
2055 }
2056
2057 if (Class.isScoped())
2058 Scope->setIsScoped();
2059
2060 // Nested types will be added to their parents at creation. The forward
2061 // references are only processed to finish the referenced element creation.
2062 if (!(Class.isNested() || Class.isScoped())) {
2063 if (LVScope *Namespace = Shared->NamespaceDeduction.get(ScopedName: Class.getName()))
2064 Namespace->addElement(Scope);
2065 else
2066 Reader->getCompileUnit()->addElement(Scope);
2067 }
2068
2069 LazyRandomTypeCollection &Types = types();
2070 TypeIndex TIFieldList = Class.getFieldList();
2071 if (TIFieldList.isNoneType()) {
2072 TypeIndex ForwardType = Shared->ForwardReferences.find(Name: Class.getName());
2073 if (!ForwardType.isNoneType()) {
2074 CVType CVReference = Types.getType(Index: ForwardType);
2075 TypeRecordKind RK = static_cast<TypeRecordKind>(CVReference.kind());
2076 ClassRecord ReferenceRecord(RK);
2077 if (Error Err = TypeDeserializer::deserializeAs(
2078 CVT&: const_cast<CVType &>(CVReference), Record&: ReferenceRecord))
2079 return Err;
2080 TIFieldList = ReferenceRecord.getFieldList();
2081 }
2082 }
2083
2084 if (!TIFieldList.isNoneType()) {
2085 // Pass down the TypeIndex 'TI' for the aggregate containing the field list.
2086 CVType CVFieldList = Types.getType(Index: TIFieldList);
2087 if (Error Err = finishVisitation(Record&: CVFieldList, TI, Element: Scope))
2088 return Err;
2089 }
2090
2091 return Error::success();
2092}
2093
2094// LF_ENUM (TPI)
2095Error LVLogicalVisitor::visitKnownRecord(CVType &Record, EnumRecord &Enum,
2096 TypeIndex TI, LVElement *Element) {
2097 LLVM_DEBUG({
2098 printTypeBegin(Record, TI, Element, StreamTPI);
2099 W.printNumber("NumEnumerators", Enum.getMemberCount());
2100 printTypeIndex("UnderlyingType", Enum.getUnderlyingType(), StreamTPI);
2101 printTypeIndex("FieldListType", Enum.getFieldList(), StreamTPI);
2102 W.printString("Name", Enum.getName());
2103 printTypeEnd(Record);
2104 });
2105
2106 LVScopeEnumeration *Scope = static_cast<LVScopeEnumeration *>(Element);
2107 if (!Scope)
2108 return Error::success();
2109
2110 if (Scope->getIsFinalized())
2111 return Error::success();
2112 Scope->setIsFinalized();
2113
2114 // Set the name, as in the case of nested, it would determine the relation
2115 // to any potential parent, via the LF_NESTTYPE record.
2116 Scope->setName(Enum.getName());
2117 if (Enum.hasUniqueName())
2118 Scope->setLinkageName(Enum.getUniqueName());
2119
2120 Scope->setType(getElement(StreamIdx: StreamTPI, TI: Enum.getUnderlyingType()));
2121
2122 if (Enum.isNested()) {
2123 Scope->setIsNested();
2124 createParents(ScopedName: Enum.getName(), Element: Scope);
2125 }
2126
2127 if (Enum.isScoped()) {
2128 Scope->setIsScoped();
2129 Scope->setIsEnumClass();
2130 }
2131
2132 // Nested types will be added to their parents at creation.
2133 if (!(Enum.isNested() || Enum.isScoped())) {
2134 if (LVScope *Namespace = Shared->NamespaceDeduction.get(ScopedName: Enum.getName()))
2135 Namespace->addElement(Scope);
2136 else
2137 Reader->getCompileUnit()->addElement(Scope);
2138 }
2139
2140 TypeIndex TIFieldList = Enum.getFieldList();
2141 if (!TIFieldList.isNoneType()) {
2142 LazyRandomTypeCollection &Types = types();
2143 CVType CVFieldList = Types.getType(Index: TIFieldList);
2144 if (Error Err = finishVisitation(Record&: CVFieldList, TI: TIFieldList, Element: Scope))
2145 return Err;
2146 }
2147
2148 return Error::success();
2149}
2150
2151// LF_FIELDLIST (TPI)
2152Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2153 FieldListRecord &FieldList,
2154 TypeIndex TI, LVElement *Element) {
2155 LLVM_DEBUG({
2156 printTypeBegin(Record, TI, Element, StreamTPI);
2157 printTypeEnd(Record);
2158 });
2159
2160 if (Error Err = visitFieldListMemberStream(TI, Element, FieldList: FieldList.Data))
2161 return Err;
2162
2163 return Error::success();
2164}
2165
2166// LF_FUNC_ID (TPI)/(IPI)
2167Error LVLogicalVisitor::visitKnownRecord(CVType &Record, FuncIdRecord &Func,
2168 TypeIndex TI, LVElement *Element) {
2169 // ParentScope and FunctionType are references into the TPI stream.
2170 LLVM_DEBUG({
2171 printTypeBegin(Record, TI, Element, StreamIPI);
2172 printTypeIndex("ParentScope", Func.getParentScope(), StreamTPI);
2173 printTypeIndex("FunctionType", Func.getFunctionType(), StreamTPI);
2174 W.printString("Name", Func.getName());
2175 printTypeEnd(Record);
2176 });
2177
2178 // The TypeIndex (LF_PROCEDURE) returned by 'getFunctionType' is the
2179 // function propotype, we need to use the function definition.
2180 if (LVScope *FunctionDcl = static_cast<LVScope *>(Element)) {
2181 // For inlined functions, the inlined instance has been already processed
2182 // (all its information is contained in the Symbols section).
2183 // 'Element' points to the created 'abstract' (out-of-line) function.
2184 // Use the parent scope information to allocate it to the correct scope.
2185 LazyRandomTypeCollection &Types = types();
2186 TypeIndex TIParent = Func.getParentScope();
2187 if (FunctionDcl->getIsInlinedAbstract()) {
2188 FunctionDcl->setName(Func.getName());
2189 if (TIParent.isNoneType())
2190 Reader->getCompileUnit()->addElement(Scope: FunctionDcl);
2191 }
2192
2193 if (!TIParent.isNoneType()) {
2194 CVType CVParentScope = ids().getType(Index: TIParent);
2195 if (Error Err = finishVisitation(Record&: CVParentScope, TI: TIParent, Element: FunctionDcl))
2196 return Err;
2197 }
2198
2199 TypeIndex TIFunctionType = Func.getFunctionType();
2200 CVType CVFunctionType = Types.getType(Index: TIFunctionType);
2201 if (Error Err =
2202 finishVisitation(Record&: CVFunctionType, TI: TIFunctionType, Element: FunctionDcl))
2203 return Err;
2204
2205 FunctionDcl->setIsFinalized();
2206 }
2207
2208 return Error::success();
2209}
2210
2211// LF_LABEL (TPI)
2212Error LVLogicalVisitor::visitKnownRecord(CVType &Record, LabelRecord &LR,
2213 TypeIndex TI, LVElement *Element) {
2214 LLVM_DEBUG({
2215 printTypeBegin(Record, TI, Element, StreamTPI);
2216 printTypeEnd(Record);
2217 });
2218 return Error::success();
2219}
2220
2221// LF_MFUNC_ID (TPI)/(IPI)
2222Error LVLogicalVisitor::visitKnownRecord(CVType &Record, MemberFuncIdRecord &Id,
2223 TypeIndex TI, LVElement *Element) {
2224 // ClassType and FunctionType are references into the TPI stream.
2225 LLVM_DEBUG({
2226 printTypeBegin(Record, TI, Element, StreamIPI);
2227 printTypeIndex("ClassType", Id.getClassType(), StreamTPI);
2228 printTypeIndex("FunctionType", Id.getFunctionType(), StreamTPI);
2229 W.printString("Name", Id.getName());
2230 printTypeEnd(Record);
2231 });
2232
2233 LVScope *FunctionDcl = static_cast<LVScope *>(Element);
2234 if (FunctionDcl->getIsInlinedAbstract()) {
2235 // For inlined functions, the inlined instance has been already processed
2236 // (all its information is contained in the Symbols section).
2237 // 'Element' points to the created 'abstract' (out-of-line) function.
2238 // Use the parent scope information to allocate it to the correct scope.
2239 if (LVScope *Class = static_cast<LVScope *>(
2240 Shared->TypeRecords.find(StreamIdx: StreamTPI, TI: Id.getClassType())))
2241 Class->addElement(Scope: FunctionDcl);
2242 }
2243
2244 TypeIndex TIFunctionType = Id.getFunctionType();
2245 CVType CVFunction = types().getType(Index: TIFunctionType);
2246 if (Error Err = finishVisitation(Record&: CVFunction, TI: TIFunctionType, Element))
2247 return Err;
2248
2249 return Error::success();
2250}
2251
2252// LF_MFUNCTION (TPI)
2253Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2254 MemberFunctionRecord &MF, TypeIndex TI,
2255 LVElement *Element) {
2256 LLVM_DEBUG({
2257 printTypeBegin(Record, TI, Element, StreamTPI);
2258 printTypeIndex("ReturnType", MF.getReturnType(), StreamTPI);
2259 printTypeIndex("ClassType", MF.getClassType(), StreamTPI);
2260 printTypeIndex("ThisType", MF.getThisType(), StreamTPI);
2261 W.printNumber("NumParameters", MF.getParameterCount());
2262 printTypeIndex("ArgListType", MF.getArgumentList(), StreamTPI);
2263 W.printNumber("ThisAdjustment", MF.getThisPointerAdjustment());
2264 printTypeEnd(Record);
2265 });
2266
2267 if (LVScope *MemberFunction = static_cast<LVScope *>(Element)) {
2268 LVElement *Class = getElement(StreamIdx: StreamTPI, TI: MF.getClassType());
2269
2270 MemberFunction->setIsFinalized();
2271 MemberFunction->setType(getElement(StreamIdx: StreamTPI, TI: MF.getReturnType()));
2272 MemberFunction->setOffset(TI.getIndex());
2273 MemberFunction->setOffsetFromTypeIndex();
2274
2275 if (ProcessArgumentList) {
2276 ProcessArgumentList = false;
2277
2278 if (!MemberFunction->getIsStatic()) {
2279 LVElement *ThisPointer = getElement(StreamIdx: StreamTPI, TI: MF.getThisType());
2280 // When creating the 'this' pointer, check if it points to a reference.
2281 ThisPointer->setType(Class);
2282 LVSymbol *This =
2283 createParameter(Element: ThisPointer, Name: StringRef(), Parent: MemberFunction);
2284 This->setIsArtificial();
2285 }
2286
2287 // Create formal parameters.
2288 LazyRandomTypeCollection &Types = types();
2289 CVType CVArguments = Types.getType(Index: MF.getArgumentList());
2290 if (Error Err = finishVisitation(Record&: CVArguments, TI: MF.getArgumentList(),
2291 Element: MemberFunction))
2292 return Err;
2293 }
2294 }
2295
2296 return Error::success();
2297}
2298
2299// LF_METHODLIST (TPI)
2300Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2301 MethodOverloadListRecord &Overloads,
2302 TypeIndex TI, LVElement *Element) {
2303 LLVM_DEBUG({
2304 printTypeBegin(Record, TI, Element, StreamTPI);
2305 printTypeEnd(Record);
2306 });
2307
2308 for (OneMethodRecord &Method : Overloads.Methods) {
2309 CVMemberRecord Record;
2310 Record.Kind = LF_METHOD;
2311 Method.Name = OverloadedMethodName;
2312 if (Error Err = visitKnownMember(Record, Method, TI, Element))
2313 return Err;
2314 }
2315
2316 return Error::success();
2317}
2318
2319// LF_MODIFIER (TPI)
2320Error LVLogicalVisitor::visitKnownRecord(CVType &Record, ModifierRecord &Mod,
2321 TypeIndex TI, LVElement *Element) {
2322 LLVM_DEBUG({
2323 printTypeBegin(Record, TI, Element, StreamTPI);
2324 printTypeIndex("ModifiedType", Mod.getModifiedType(), StreamTPI);
2325 printTypeEnd(Record);
2326 });
2327
2328 // Create the modified type, which will be attached to the type(s) that
2329 // contains the modifiers.
2330 LVElement *ModifiedType = getElement(StreamIdx: StreamTPI, TI: Mod.getModifiedType());
2331
2332 // At this point the types recording the qualifiers do not have a
2333 // scope parent. They must be assigned to the current compile unit.
2334 LVScopeCompileUnit *CompileUnit = Reader->getCompileUnit();
2335
2336 // The incoming element does not have a defined kind. Use the given
2337 // modifiers to complete its type. A type can have more than one modifier;
2338 // in that case, we have to create an extra type to have the other modifier.
2339 LVType *LastLink = static_cast<LVType *>(Element);
2340 if (!LastLink->getParentScope())
2341 CompileUnit->addElement(Type: LastLink);
2342
2343 bool SeenModifier = false;
2344 uint16_t Mods = static_cast<uint16_t>(Mod.getModifiers());
2345 if (Mods & uint16_t(ModifierOptions::Const)) {
2346 SeenModifier = true;
2347 LastLink->setTag(dwarf::DW_TAG_const_type);
2348 LastLink->setIsConst();
2349 LastLink->setName("const");
2350 }
2351 if (Mods & uint16_t(ModifierOptions::Volatile)) {
2352 if (SeenModifier) {
2353 LVType *Volatile = Reader->createType();
2354 Volatile->setIsModifier();
2355 LastLink->setType(Volatile);
2356 LastLink = Volatile;
2357 CompileUnit->addElement(Type: LastLink);
2358 }
2359 LastLink->setTag(dwarf::DW_TAG_volatile_type);
2360 LastLink->setIsVolatile();
2361 LastLink->setName("volatile");
2362 }
2363 if (Mods & uint16_t(ModifierOptions::Unaligned)) {
2364 if (SeenModifier) {
2365 LVType *Unaligned = Reader->createType();
2366 Unaligned->setIsModifier();
2367 LastLink->setType(Unaligned);
2368 LastLink = Unaligned;
2369 CompileUnit->addElement(Type: LastLink);
2370 }
2371 LastLink->setTag(dwarf::DW_TAG_unaligned);
2372 LastLink->setIsUnaligned();
2373 LastLink->setName("unaligned");
2374 }
2375
2376 LastLink->setType(ModifiedType);
2377 return Error::success();
2378}
2379
2380// LF_POINTER (TPI)
2381Error LVLogicalVisitor::visitKnownRecord(CVType &Record, PointerRecord &Ptr,
2382 TypeIndex TI, LVElement *Element) {
2383 LLVM_DEBUG({
2384 printTypeBegin(Record, TI, Element, StreamTPI);
2385 printTypeIndex("PointeeType", Ptr.getReferentType(), StreamTPI);
2386 W.printNumber("IsFlat", Ptr.isFlat());
2387 W.printNumber("IsConst", Ptr.isConst());
2388 W.printNumber("IsVolatile", Ptr.isVolatile());
2389 W.printNumber("IsUnaligned", Ptr.isUnaligned());
2390 W.printNumber("IsRestrict", Ptr.isRestrict());
2391 W.printNumber("IsThisPtr&", Ptr.isLValueReferenceThisPtr());
2392 W.printNumber("IsThisPtr&&", Ptr.isRValueReferenceThisPtr());
2393 W.printNumber("SizeOf", Ptr.getSize());
2394
2395 if (Ptr.isPointerToMember()) {
2396 const MemberPointerInfo &MI = Ptr.getMemberInfo();
2397 printTypeIndex("ClassType", MI.getContainingType(), StreamTPI);
2398 }
2399 printTypeEnd(Record);
2400 });
2401
2402 // Find the pointed-to type.
2403 LVType *Pointer = static_cast<LVType *>(Element);
2404 LVElement *Pointee = nullptr;
2405
2406 PointerMode Mode = Ptr.getMode();
2407 Pointee = Ptr.isPointerToMember()
2408 ? Shared->TypeRecords.find(StreamIdx: StreamTPI, TI: Ptr.getReferentType())
2409 : getElement(StreamIdx: StreamTPI, TI: Ptr.getReferentType());
2410
2411 // At this point the types recording the qualifiers do not have a
2412 // scope parent. They must be assigned to the current compile unit.
2413 LVScopeCompileUnit *CompileUnit = Reader->getCompileUnit();
2414
2415 // Order for the different modifiers:
2416 // <restrict> <pointer, Reference, ValueReference> <const, volatile>
2417 // Const and volatile already processed.
2418 bool SeenModifier = false;
2419 LVType *LastLink = Pointer;
2420 if (!LastLink->getParentScope())
2421 CompileUnit->addElement(Type: LastLink);
2422
2423 if (Ptr.isRestrict()) {
2424 SeenModifier = true;
2425 LVType *Restrict = Reader->createType();
2426 Restrict->setTag(dwarf::DW_TAG_restrict_type);
2427 Restrict->setIsRestrict();
2428 Restrict->setName("restrict");
2429 LastLink->setType(Restrict);
2430 LastLink = Restrict;
2431 CompileUnit->addElement(Type: LastLink);
2432 }
2433 if (Mode == PointerMode::LValueReference) {
2434 if (SeenModifier) {
2435 LVType *LReference = Reader->createType();
2436 LReference->setIsModifier();
2437 LastLink->setType(LReference);
2438 LastLink = LReference;
2439 CompileUnit->addElement(Type: LastLink);
2440 }
2441 LastLink->setTag(dwarf::DW_TAG_reference_type);
2442 LastLink->setIsReference();
2443 LastLink->setName("&");
2444 }
2445 if (Mode == PointerMode::RValueReference) {
2446 if (SeenModifier) {
2447 LVType *RReference = Reader->createType();
2448 RReference->setIsModifier();
2449 LastLink->setType(RReference);
2450 LastLink = RReference;
2451 CompileUnit->addElement(Type: LastLink);
2452 }
2453 LastLink->setTag(dwarf::DW_TAG_rvalue_reference_type);
2454 LastLink->setIsRvalueReference();
2455 LastLink->setName("&&");
2456 }
2457
2458 // When creating the pointer, check if it points to a reference.
2459 LastLink->setType(Pointee);
2460 return Error::success();
2461}
2462
2463// LF_PROCEDURE (TPI)
2464Error LVLogicalVisitor::visitKnownRecord(CVType &Record, ProcedureRecord &Proc,
2465 TypeIndex TI, LVElement *Element) {
2466 LLVM_DEBUG({
2467 printTypeBegin(Record, TI, Element, StreamTPI);
2468 printTypeIndex("ReturnType", Proc.getReturnType(), StreamTPI);
2469 W.printNumber("NumParameters", Proc.getParameterCount());
2470 printTypeIndex("ArgListType", Proc.getArgumentList(), StreamTPI);
2471 printTypeEnd(Record);
2472 });
2473
2474 // There is no need to traverse the argument list, as the CodeView format
2475 // declares the parameters as a 'S_LOCAL' symbol tagged as parameter.
2476 // Only process parameters when dealing with inline functions.
2477 if (LVScope *FunctionDcl = static_cast<LVScope *>(Element)) {
2478 FunctionDcl->setType(getElement(StreamIdx: StreamTPI, TI: Proc.getReturnType()));
2479
2480 if (ProcessArgumentList) {
2481 ProcessArgumentList = false;
2482 // Create formal parameters.
2483 LazyRandomTypeCollection &Types = types();
2484 CVType CVArguments = Types.getType(Index: Proc.getArgumentList());
2485 if (Error Err = finishVisitation(Record&: CVArguments, TI: Proc.getArgumentList(),
2486 Element: FunctionDcl))
2487 return Err;
2488 }
2489 }
2490
2491 return Error::success();
2492}
2493
2494// LF_UNION (TPI)
2495Error LVLogicalVisitor::visitKnownRecord(CVType &Record, UnionRecord &Union,
2496 TypeIndex TI, LVElement *Element) {
2497 LLVM_DEBUG({
2498 printTypeBegin(Record, TI, Element, StreamTPI);
2499 W.printNumber("MemberCount", Union.getMemberCount());
2500 printTypeIndex("FieldList", Union.getFieldList(), StreamTPI);
2501 W.printNumber("SizeOf", Union.getSize());
2502 W.printString("Name", Union.getName());
2503 if (Union.hasUniqueName())
2504 W.printString("UniqueName", Union.getUniqueName());
2505 printTypeEnd(Record);
2506 });
2507
2508 LVScopeAggregate *Scope = static_cast<LVScopeAggregate *>(Element);
2509 if (!Scope)
2510 return Error::success();
2511
2512 if (Scope->getIsFinalized())
2513 return Error::success();
2514 Scope->setIsFinalized();
2515
2516 Scope->setName(Union.getName());
2517 if (Union.hasUniqueName())
2518 Scope->setLinkageName(Union.getUniqueName());
2519 Scope->setBitSize(Union.getSize() * DWARF_CHAR_BIT);
2520
2521 if (Union.isNested()) {
2522 Scope->setIsNested();
2523 createParents(ScopedName: Union.getName(), Element: Scope);
2524 } else {
2525 if (LVScope *Namespace = Shared->NamespaceDeduction.get(ScopedName: Union.getName()))
2526 Namespace->addElement(Scope);
2527 else
2528 Reader->getCompileUnit()->addElement(Scope);
2529 }
2530
2531 if (!Union.getFieldList().isNoneType()) {
2532 LazyRandomTypeCollection &Types = types();
2533 // Pass down the TypeIndex 'TI' for the aggregate containing the field list.
2534 CVType CVFieldList = Types.getType(Index: Union.getFieldList());
2535 if (Error Err = finishVisitation(Record&: CVFieldList, TI, Element: Scope))
2536 return Err;
2537 }
2538
2539 return Error::success();
2540}
2541
2542// LF_TYPESERVER2 (TPI)
2543Error LVLogicalVisitor::visitKnownRecord(CVType &Record, TypeServer2Record &TS,
2544 TypeIndex TI, LVElement *Element) {
2545 LLVM_DEBUG({
2546 printTypeBegin(Record, TI, Element, StreamTPI);
2547 W.printString("Guid", formatv("{0}", TS.getGuid()).str());
2548 W.printNumber("Age", TS.getAge());
2549 W.printString("Name", TS.getName());
2550 printTypeEnd(Record);
2551 });
2552 return Error::success();
2553}
2554
2555// LF_VFTABLE (TPI)
2556Error LVLogicalVisitor::visitKnownRecord(CVType &Record, VFTableRecord &VFT,
2557 TypeIndex TI, LVElement *Element) {
2558 LLVM_DEBUG({
2559 printTypeBegin(Record, TI, Element, StreamTPI);
2560 printTypeIndex("CompleteClass", VFT.getCompleteClass(), StreamTPI);
2561 printTypeIndex("OverriddenVFTable", VFT.getOverriddenVTable(), StreamTPI);
2562 W.printHex("VFPtrOffset", VFT.getVFPtrOffset());
2563 W.printString("VFTableName", VFT.getName());
2564 for (const StringRef &N : VFT.getMethodNames())
2565 W.printString("MethodName", N);
2566 printTypeEnd(Record);
2567 });
2568 return Error::success();
2569}
2570
2571// LF_VTSHAPE (TPI)
2572Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2573 VFTableShapeRecord &Shape,
2574 TypeIndex TI, LVElement *Element) {
2575 LLVM_DEBUG({
2576 printTypeBegin(Record, TI, Element, StreamTPI);
2577 W.printNumber("VFEntryCount", Shape.getEntryCount());
2578 printTypeEnd(Record);
2579 });
2580 return Error::success();
2581}
2582
2583// LF_SUBSTR_LIST (TPI)/(IPI)
2584Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2585 StringListRecord &Strings,
2586 TypeIndex TI, LVElement *Element) {
2587 // All the indices are references into the TPI/IPI stream.
2588 LLVM_DEBUG({
2589 printTypeBegin(Record, TI, Element, StreamIPI);
2590 ArrayRef<TypeIndex> Indices = Strings.getIndices();
2591 uint32_t Size = Indices.size();
2592 W.printNumber("NumStrings", Size);
2593 ListScope Arguments(W, "Strings");
2594 for (uint32_t I = 0; I < Size; ++I)
2595 printTypeIndex("String", Indices[I], StreamIPI);
2596 printTypeEnd(Record);
2597 });
2598 return Error::success();
2599}
2600
2601// LF_STRING_ID (TPI)/(IPI)
2602Error LVLogicalVisitor::visitKnownRecord(CVType &Record, StringIdRecord &String,
2603 TypeIndex TI, LVElement *Element) {
2604 // All args are references into the TPI/IPI stream.
2605 LLVM_DEBUG({
2606 printTypeIndex("\nTI", TI, StreamIPI);
2607 printTypeIndex("Id", String.getId(), StreamIPI);
2608 W.printString("StringData", String.getString());
2609 });
2610
2611 if (LVScope *Namespace = Shared->NamespaceDeduction.get(
2612 ScopedName: String.getString(), /*CheckScope=*/false)) {
2613 // The function is already at different scope. In order to reflect
2614 // the correct parent, move it to the namespace.
2615 if (LVScope *Scope = Element->getParentScope())
2616 Scope->removeElement(Element);
2617 Namespace->addElement(Element);
2618 }
2619
2620 return Error::success();
2621}
2622
2623// LF_UDT_SRC_LINE (TPI)/(IPI)
2624Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2625 UdtSourceLineRecord &SourceLine,
2626 TypeIndex TI, LVElement *Element) {
2627 // All args are references into the TPI/IPI stream.
2628 LLVM_DEBUG({
2629 printTypeIndex("\nTI", TI, StreamIPI);
2630 printTypeIndex("UDT", SourceLine.getUDT(), StreamIPI);
2631 printTypeIndex("SourceFile", SourceLine.getSourceFile(), StreamIPI);
2632 W.printNumber("LineNumber", SourceLine.getLineNumber());
2633 });
2634 return Error::success();
2635}
2636
2637// LF_UDT_MOD_SRC_LINE (TPI)/(IPI)
2638Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2639 UdtModSourceLineRecord &ModSourceLine,
2640 TypeIndex TI, LVElement *Element) {
2641 // All args are references into the TPI/IPI stream.
2642 LLVM_DEBUG({
2643 printTypeBegin(Record, TI, Element, StreamIPI);
2644 printTypeIndex("\nTI", TI, StreamIPI);
2645 printTypeIndex("UDT", ModSourceLine.getUDT(), StreamIPI);
2646 printTypeIndex("SourceFile", ModSourceLine.getSourceFile(), StreamIPI);
2647 W.printNumber("LineNumber", ModSourceLine.getLineNumber());
2648 W.printNumber("Module", ModSourceLine.getModule());
2649 printTypeEnd(Record);
2650 });
2651 return Error::success();
2652}
2653
2654// LF_PRECOMP (TPI)
2655Error LVLogicalVisitor::visitKnownRecord(CVType &Record, PrecompRecord &Precomp,
2656 TypeIndex TI, LVElement *Element) {
2657 LLVM_DEBUG({
2658 printTypeBegin(Record, TI, Element, StreamTPI);
2659 W.printHex("StartIndex", Precomp.getStartTypeIndex());
2660 W.printHex("Count", Precomp.getTypesCount());
2661 W.printHex("Signature", Precomp.getSignature());
2662 W.printString("PrecompFile", Precomp.getPrecompFilePath());
2663 printTypeEnd(Record);
2664 });
2665 return Error::success();
2666}
2667
2668// LF_ENDPRECOMP (TPI)
2669Error LVLogicalVisitor::visitKnownRecord(CVType &Record,
2670 EndPrecompRecord &EndPrecomp,
2671 TypeIndex TI, LVElement *Element) {
2672 LLVM_DEBUG({
2673 printTypeBegin(Record, TI, Element, StreamTPI);
2674 W.printHex("Signature", EndPrecomp.getSignature());
2675 printTypeEnd(Record);
2676 });
2677 return Error::success();
2678}
2679
2680Error LVLogicalVisitor::visitUnknownMember(CVMemberRecord &Record,
2681 TypeIndex TI) {
2682 LLVM_DEBUG({ W.printHex("UnknownMember", unsigned(Record.Kind)); });
2683 return Error::success();
2684}
2685
2686// LF_BCLASS, LF_BINTERFACE
2687Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2688 BaseClassRecord &Base, TypeIndex TI,
2689 LVElement *Element) {
2690 LLVM_DEBUG({
2691 printMemberBegin(Record, TI, Element, StreamTPI);
2692 printTypeIndex("BaseType", Base.getBaseType(), StreamTPI);
2693 W.printHex("BaseOffset", Base.getBaseOffset());
2694 printMemberEnd(Record);
2695 });
2696
2697 createElement(Kind: Record.Kind);
2698 if (LVSymbol *Symbol = CurrentSymbol) {
2699 LVElement *BaseClass = getElement(StreamIdx: StreamTPI, TI: Base.getBaseType());
2700 Symbol->setName(BaseClass->getName());
2701 Symbol->setType(BaseClass);
2702 Symbol->setAccessibilityCode(Base.getAccess());
2703 static_cast<LVScope *>(Element)->addElement(Symbol);
2704 }
2705
2706 return Error::success();
2707}
2708
2709// LF_MEMBER
2710Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2711 DataMemberRecord &Field, TypeIndex TI,
2712 LVElement *Element) {
2713 LLVM_DEBUG({
2714 printMemberBegin(Record, TI, Element, StreamTPI);
2715 printTypeIndex("Type", Field.getType(), StreamTPI);
2716 W.printHex("FieldOffset", Field.getFieldOffset());
2717 W.printString("Name", Field.getName());
2718 printMemberEnd(Record);
2719 });
2720
2721 // Create the data member.
2722 createDataMember(Record, Parent: static_cast<LVScope *>(Element), Name: Field.getName(),
2723 Type: Field.getType(), Access: Field.getAccess());
2724 return Error::success();
2725}
2726
2727// LF_ENUMERATE
2728Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2729 EnumeratorRecord &Enum, TypeIndex TI,
2730 LVElement *Element) {
2731 LLVM_DEBUG({
2732 printMemberBegin(Record, TI, Element, StreamTPI);
2733 W.printNumber("EnumValue", Enum.getValue());
2734 W.printString("Name", Enum.getName());
2735 printMemberEnd(Record);
2736 });
2737
2738 createElement(Kind: Record.Kind);
2739 if (LVType *Type = CurrentType) {
2740 Type->setName(Enum.getName());
2741 SmallString<16> Value;
2742 Enum.getValue().toString(Str&: Value, Radix: 16, Signed: true, formatAsCLiteral: true);
2743 Type->setValue(Value);
2744 static_cast<LVScope *>(Element)->addElement(Type: CurrentType);
2745 }
2746
2747 return Error::success();
2748}
2749
2750// LF_INDEX
2751Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2752 ListContinuationRecord &Cont,
2753 TypeIndex TI, LVElement *Element) {
2754 LLVM_DEBUG({
2755 printMemberBegin(Record, TI, Element, StreamTPI);
2756 printTypeIndex("ContinuationIndex", Cont.getContinuationIndex(), StreamTPI);
2757 printMemberEnd(Record);
2758 });
2759 return Error::success();
2760}
2761
2762// LF_NESTTYPE
2763Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2764 NestedTypeRecord &Nested, TypeIndex TI,
2765 LVElement *Element) {
2766 LLVM_DEBUG({
2767 printMemberBegin(Record, TI, Element, StreamTPI);
2768 printTypeIndex("Type", Nested.getNestedType(), StreamTPI);
2769 W.printString("Name", Nested.getName());
2770 printMemberEnd(Record);
2771 });
2772
2773 if (LVElement *Typedef = createElement(Kind: SymbolKind::S_UDT)) {
2774 Typedef->setName(Nested.getName());
2775 LVElement *NestedType = getElement(StreamIdx: StreamTPI, TI: Nested.getNestedType());
2776 Typedef->setType(NestedType);
2777 LVScope *Scope = static_cast<LVScope *>(Element);
2778 Scope->addElement(Element: Typedef);
2779
2780 if (NestedType && NestedType->getIsNested()) {
2781 // 'Element' is an aggregate type that may contains this nested type
2782 // definition. Used their scoped names, to decide on their relationship.
2783 StringRef RecordName = getRecordName(Types&: types(), TI);
2784
2785 StringRef NestedTypeName = NestedType->getName();
2786 if (NestedTypeName.size() && RecordName.size()) {
2787 StringRef OuterComponent;
2788 std::tie(args&: OuterComponent, args: std::ignore) =
2789 getInnerComponent(Name: NestedTypeName);
2790 // We have an already created nested type. Add it to the current scope
2791 // and update all its children if any.
2792 if (OuterComponent.size() && OuterComponent == RecordName) {
2793 if (!NestedType->getIsScopedAlready()) {
2794 Scope->addElement(Element: NestedType);
2795 NestedType->setIsScopedAlready();
2796 NestedType->updateLevel(Parent: Scope);
2797 }
2798 Typedef->resetIncludeInPrint();
2799 }
2800 }
2801 }
2802 }
2803
2804 return Error::success();
2805}
2806
2807// LF_ONEMETHOD
2808Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2809 OneMethodRecord &Method, TypeIndex TI,
2810 LVElement *Element) {
2811 LLVM_DEBUG({
2812 printMemberBegin(Record, TI, Element, StreamTPI);
2813 printTypeIndex("Type", Method.getType(), StreamTPI);
2814 // If virtual, then read the vftable offset.
2815 if (Method.isIntroducingVirtual())
2816 W.printHex("VFTableOffset", Method.getVFTableOffset());
2817 W.printString("Name", Method.getName());
2818 printMemberEnd(Record);
2819 });
2820
2821 // All the LF_ONEMETHOD objects share the same type description.
2822 // We have to create a scope object for each one and get the required
2823 // information from the LF_MFUNCTION object.
2824 ProcessArgumentList = true;
2825 if (LVElement *MemberFunction = createElement(Kind: TypeLeafKind::LF_ONEMETHOD)) {
2826 MemberFunction->setIsFinalized();
2827 static_cast<LVScope *>(Element)->addElement(Element: MemberFunction);
2828
2829 MemberFunction->setName(Method.getName());
2830 MemberFunction->setAccessibilityCode(Method.getAccess());
2831
2832 MethodKind Kind = Method.getMethodKind();
2833 if (Kind == MethodKind::Static)
2834 MemberFunction->setIsStatic();
2835 MemberFunction->setVirtualityCode(Kind);
2836
2837 MethodOptions Flags = Method.Attrs.getFlags();
2838 if (MethodOptions::CompilerGenerated ==
2839 (Flags & MethodOptions::CompilerGenerated))
2840 MemberFunction->setIsArtificial();
2841
2842 LazyRandomTypeCollection &Types = types();
2843 CVType CVMethodType = Types.getType(Index: Method.getType());
2844 if (Error Err =
2845 finishVisitation(Record&: CVMethodType, TI: Method.getType(), Element: MemberFunction))
2846 return Err;
2847 }
2848 ProcessArgumentList = false;
2849
2850 return Error::success();
2851}
2852
2853// LF_METHOD
2854Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2855 OverloadedMethodRecord &Method,
2856 TypeIndex TI, LVElement *Element) {
2857 LLVM_DEBUG({
2858 printMemberBegin(Record, TI, Element, StreamTPI);
2859 W.printHex("MethodCount", Method.getNumOverloads());
2860 printTypeIndex("MethodListIndex", Method.getMethodList(), StreamTPI);
2861 W.printString("Name", Method.getName());
2862 printMemberEnd(Record);
2863 });
2864
2865 // Record the overloaded method name, which will be used during the
2866 // traversal of the method list.
2867 LazyRandomTypeCollection &Types = types();
2868 OverloadedMethodName = Method.getName();
2869 CVType CVMethods = Types.getType(Index: Method.getMethodList());
2870 if (Error Err = finishVisitation(Record&: CVMethods, TI: Method.getMethodList(), Element))
2871 return Err;
2872
2873 return Error::success();
2874}
2875
2876// LF_STMEMBER
2877Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2878 StaticDataMemberRecord &Field,
2879 TypeIndex TI, LVElement *Element) {
2880 LLVM_DEBUG({
2881 printMemberBegin(Record, TI, Element, StreamTPI);
2882 printTypeIndex("Type", Field.getType(), StreamTPI);
2883 W.printString("Name", Field.getName());
2884 printMemberEnd(Record);
2885 });
2886
2887 // Create the data member.
2888 createDataMember(Record, Parent: static_cast<LVScope *>(Element), Name: Field.getName(),
2889 Type: Field.getType(), Access: Field.getAccess());
2890 return Error::success();
2891}
2892
2893// LF_VFUNCTAB
2894Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2895 VFPtrRecord &VFTable, TypeIndex TI,
2896 LVElement *Element) {
2897 LLVM_DEBUG({
2898 printMemberBegin(Record, TI, Element, StreamTPI);
2899 printTypeIndex("Type", VFTable.getType(), StreamTPI);
2900 printMemberEnd(Record);
2901 });
2902 return Error::success();
2903}
2904
2905// LF_VBCLASS, LF_IVBCLASS
2906Error LVLogicalVisitor::visitKnownMember(CVMemberRecord &Record,
2907 VirtualBaseClassRecord &Base,
2908 TypeIndex TI, LVElement *Element) {
2909 LLVM_DEBUG({
2910 printMemberBegin(Record, TI, Element, StreamTPI);
2911 printTypeIndex("BaseType", Base.getBaseType(), StreamTPI);
2912 printTypeIndex("VBPtrType", Base.getVBPtrType(), StreamTPI);
2913 W.printHex("VBPtrOffset", Base.getVBPtrOffset());
2914 W.printHex("VBTableIndex", Base.getVTableIndex());
2915 printMemberEnd(Record);
2916 });
2917
2918 createElement(Kind: Record.Kind);
2919 if (LVSymbol *Symbol = CurrentSymbol) {
2920 LVElement *BaseClass = getElement(StreamIdx: StreamTPI, TI: Base.getBaseType());
2921 Symbol->setName(BaseClass->getName());
2922 Symbol->setType(BaseClass);
2923 Symbol->setAccessibilityCode(Base.getAccess());
2924 Symbol->setVirtualityCode(MethodKind::Virtual);
2925 static_cast<LVScope *>(Element)->addElement(Symbol);
2926 }
2927
2928 return Error::success();
2929}
2930
2931Error LVLogicalVisitor::visitMemberRecord(CVMemberRecord &Record,
2932 TypeVisitorCallbacks &Callbacks,
2933 TypeIndex TI, LVElement *Element) {
2934 if (Error Err = Callbacks.visitMemberBegin(Record))
2935 return Err;
2936
2937 switch (Record.Kind) {
2938 default:
2939 if (Error Err = Callbacks.visitUnknownMember(Record))
2940 return Err;
2941 break;
2942#define MEMBER_RECORD(EnumName, EnumVal, Name) \
2943 case EnumName: { \
2944 if (Error Err = \
2945 visitKnownMember<Name##Record>(Record, Callbacks, TI, Element)) \
2946 return Err; \
2947 break; \
2948 }
2949#define MEMBER_RECORD_ALIAS(EnumName, EnumVal, Name, AliasName) \
2950 MEMBER_RECORD(EnumVal, EnumVal, AliasName)
2951#define TYPE_RECORD(EnumName, EnumVal, Name)
2952#define TYPE_RECORD_ALIAS(EnumName, EnumVal, Name, AliasName)
2953#include "llvm/DebugInfo/CodeView/CodeViewTypes.def"
2954 }
2955
2956 if (Error Err = Callbacks.visitMemberEnd(Record))
2957 return Err;
2958
2959 return Error::success();
2960}
2961
2962Error LVLogicalVisitor::finishVisitation(CVType &Record, TypeIndex TI,
2963 LVElement *Element) {
2964 switch (Record.kind()) {
2965 default:
2966 if (Error Err = visitUnknownType(Record, TI))
2967 return Err;
2968 break;
2969#define TYPE_RECORD(EnumName, EnumVal, Name) \
2970 case EnumName: { \
2971 if (Error Err = visitKnownRecord<Name##Record>(Record, TI, Element)) \
2972 return Err; \
2973 break; \
2974 }
2975#define TYPE_RECORD_ALIAS(EnumName, EnumVal, Name, AliasName) \
2976 TYPE_RECORD(EnumVal, EnumVal, AliasName)
2977#define MEMBER_RECORD(EnumName, EnumVal, Name)
2978#define MEMBER_RECORD_ALIAS(EnumName, EnumVal, Name, AliasName)
2979#include "llvm/DebugInfo/CodeView/CodeViewTypes.def"
2980 }
2981
2982 return Error::success();
2983}
2984
2985// Customized version of 'FieldListVisitHelper'.
2986Error LVLogicalVisitor::visitFieldListMemberStream(
2987 TypeIndex TI, LVElement *Element, ArrayRef<uint8_t> FieldList) {
2988 BinaryByteStream Stream(FieldList, llvm::endianness::little);
2989 BinaryStreamReader Reader(Stream);
2990 FieldListDeserializer Deserializer(Reader);
2991 TypeVisitorCallbackPipeline Pipeline;
2992 Pipeline.addCallbackToPipeline(Callbacks&: Deserializer);
2993
2994 TypeLeafKind Leaf;
2995 while (!Reader.empty()) {
2996 if (Error Err = Reader.readEnum(Dest&: Leaf))
2997 return Err;
2998
2999 CVMemberRecord Record;
3000 Record.Kind = Leaf;
3001 if (Error Err = visitMemberRecord(Record, Callbacks&: Pipeline, TI, Element))
3002 return Err;
3003 }
3004
3005 return Error::success();
3006}
3007
3008void LVLogicalVisitor::addElement(LVScope *Scope, bool IsCompileUnit) {
3009 // The CodeView specifications does not treat S_COMPILE2 and S_COMPILE3
3010 // as symbols that open a scope. The CodeView reader, treat them in a
3011 // similar way as DWARF. As there is no a symbole S_END to close the
3012 // compile unit, we need to check for the next compile unit.
3013 if (IsCompileUnit) {
3014 if (!ScopeStack.empty())
3015 popScope();
3016 InCompileUnitScope = true;
3017 }
3018
3019 pushScope(Scope);
3020 ReaderParent->addElement(Scope);
3021}
3022
3023void LVLogicalVisitor::addElement(LVSymbol *Symbol) {
3024 ReaderScope->addElement(Symbol);
3025}
3026
3027void LVLogicalVisitor::addElement(LVType *Type) {
3028 ReaderScope->addElement(Type);
3029}
3030
3031LVElement *LVLogicalVisitor::createElement(TypeLeafKind Kind) {
3032 CurrentScope = nullptr;
3033 CurrentSymbol = nullptr;
3034 CurrentType = nullptr;
3035
3036 if (Kind < TypeIndex::FirstNonSimpleIndex) {
3037 CurrentType = Reader->createType();
3038 CurrentType->setIsBase();
3039 CurrentType->setTag(dwarf::DW_TAG_base_type);
3040 if (options().getAttributeBase())
3041 CurrentType->setIncludeInPrint();
3042 return CurrentType;
3043 }
3044
3045 switch (Kind) {
3046 // Types.
3047 case TypeLeafKind::LF_ENUMERATE:
3048 CurrentType = Reader->createTypeEnumerator();
3049 CurrentType->setTag(dwarf::DW_TAG_enumerator);
3050 return CurrentType;
3051 case TypeLeafKind::LF_MODIFIER:
3052 CurrentType = Reader->createType();
3053 CurrentType->setIsModifier();
3054 return CurrentType;
3055 case TypeLeafKind::LF_POINTER:
3056 CurrentType = Reader->createType();
3057 CurrentType->setIsPointer();
3058 CurrentType->setName("*");
3059 CurrentType->setTag(dwarf::DW_TAG_pointer_type);
3060 return CurrentType;
3061
3062 // Symbols.
3063 case TypeLeafKind::LF_BCLASS:
3064 case TypeLeafKind::LF_IVBCLASS:
3065 case TypeLeafKind::LF_VBCLASS:
3066 CurrentSymbol = Reader->createSymbol();
3067 CurrentSymbol->setTag(dwarf::DW_TAG_inheritance);
3068 CurrentSymbol->setIsInheritance();
3069 return CurrentSymbol;
3070 case TypeLeafKind::LF_MEMBER:
3071 case TypeLeafKind::LF_STMEMBER:
3072 CurrentSymbol = Reader->createSymbol();
3073 CurrentSymbol->setIsMember();
3074 CurrentSymbol->setTag(dwarf::DW_TAG_member);
3075 return CurrentSymbol;
3076
3077 // Scopes.
3078 case TypeLeafKind::LF_ARRAY:
3079 CurrentScope = Reader->createScopeArray();
3080 CurrentScope->setTag(dwarf::DW_TAG_array_type);
3081 return CurrentScope;
3082 case TypeLeafKind::LF_CLASS:
3083 CurrentScope = Reader->createScopeAggregate();
3084 CurrentScope->setTag(dwarf::DW_TAG_class_type);
3085 CurrentScope->setIsClass();
3086 return CurrentScope;
3087 case TypeLeafKind::LF_ENUM:
3088 CurrentScope = Reader->createScopeEnumeration();
3089 CurrentScope->setTag(dwarf::DW_TAG_enumeration_type);
3090 return CurrentScope;
3091 case TypeLeafKind::LF_METHOD:
3092 case TypeLeafKind::LF_ONEMETHOD:
3093 case TypeLeafKind::LF_PROCEDURE:
3094 CurrentScope = Reader->createScopeFunction();
3095 CurrentScope->setIsSubprogram();
3096 CurrentScope->setTag(dwarf::DW_TAG_subprogram);
3097 return CurrentScope;
3098 case TypeLeafKind::LF_STRUCTURE:
3099 CurrentScope = Reader->createScopeAggregate();
3100 CurrentScope->setIsStructure();
3101 CurrentScope->setTag(dwarf::DW_TAG_structure_type);
3102 return CurrentScope;
3103 case TypeLeafKind::LF_UNION:
3104 CurrentScope = Reader->createScopeAggregate();
3105 CurrentScope->setIsUnion();
3106 CurrentScope->setTag(dwarf::DW_TAG_union_type);
3107 return CurrentScope;
3108 default:
3109 // If '--internal=tag' and '--print=warning' are specified in the command
3110 // line, we record and print each seen 'TypeLeafKind'.
3111 break;
3112 }
3113 return nullptr;
3114}
3115
3116LVElement *LVLogicalVisitor::createElement(SymbolKind Kind) {
3117 CurrentScope = nullptr;
3118 CurrentSymbol = nullptr;
3119 CurrentType = nullptr;
3120 switch (Kind) {
3121 // Types.
3122 case SymbolKind::S_UDT:
3123 CurrentType = Reader->createTypeDefinition();
3124 CurrentType->setTag(dwarf::DW_TAG_typedef);
3125 return CurrentType;
3126
3127 // Symbols.
3128 case SymbolKind::S_CONSTANT:
3129 CurrentSymbol = Reader->createSymbol();
3130 CurrentSymbol->setIsConstant();
3131 CurrentSymbol->setTag(dwarf::DW_TAG_constant);
3132 return CurrentSymbol;
3133
3134 case SymbolKind::S_BPREL32:
3135 case SymbolKind::S_REGREL32:
3136 case SymbolKind::S_REGREL32_INDIR:
3137 case SymbolKind::S_GDATA32:
3138 case SymbolKind::S_LDATA32:
3139 case SymbolKind::S_LOCAL:
3140 // During the symbol traversal more information is available to
3141 // determine if the symbol is a parameter or a variable. At this
3142 // stage mark it as variable.
3143 CurrentSymbol = Reader->createSymbol();
3144 CurrentSymbol->setIsVariable();
3145 CurrentSymbol->setTag(dwarf::DW_TAG_variable);
3146 return CurrentSymbol;
3147
3148 // Scopes.
3149 case SymbolKind::S_BLOCK32:
3150 CurrentScope = Reader->createScope();
3151 CurrentScope->setIsLexicalBlock();
3152 CurrentScope->setTag(dwarf::DW_TAG_lexical_block);
3153 return CurrentScope;
3154 case SymbolKind::S_COMPILE2:
3155 case SymbolKind::S_COMPILE3:
3156 CurrentScope = Reader->createScopeCompileUnit();
3157 CurrentScope->setTag(dwarf::DW_TAG_compile_unit);
3158 Reader->setCompileUnit(static_cast<LVScopeCompileUnit *>(CurrentScope));
3159 return CurrentScope;
3160 case SymbolKind::S_INLINESITE:
3161 case SymbolKind::S_INLINESITE2:
3162 CurrentScope = Reader->createScopeFunctionInlined();
3163 CurrentScope->setIsInlinedFunction();
3164 CurrentScope->setTag(dwarf::DW_TAG_inlined_subroutine);
3165 return CurrentScope;
3166 case SymbolKind::S_LPROC32:
3167 case SymbolKind::S_GPROC32:
3168 case SymbolKind::S_LPROC32_ID:
3169 case SymbolKind::S_GPROC32_ID:
3170 case SymbolKind::S_SEPCODE:
3171 case SymbolKind::S_THUNK32:
3172 CurrentScope = Reader->createScopeFunction();
3173 CurrentScope->setIsSubprogram();
3174 CurrentScope->setTag(dwarf::DW_TAG_subprogram);
3175 return CurrentScope;
3176 default:
3177 // If '--internal=tag' and '--print=warning' are specified in the command
3178 // line, we record and print each seen 'SymbolKind'.
3179 break;
3180 }
3181 return nullptr;
3182}
3183
3184LVElement *LVLogicalVisitor::createElement(TypeIndex TI, TypeLeafKind Kind) {
3185 LVElement *Element = Shared->TypeRecords.find(StreamIdx: StreamTPI, TI);
3186 if (!Element) {
3187 // We are dealing with a base type or pointer to a base type, which are
3188 // not included explicitly in the CodeView format.
3189 if (Kind < TypeIndex::FirstNonSimpleIndex) {
3190 Element = createElement(Kind);
3191 Element->setIsFinalized();
3192 Shared->TypeRecords.add(StreamIdx: StreamTPI, TI: (TypeIndex)Kind, Kind, Element);
3193 Element->setOffset(Kind);
3194 return Element;
3195 }
3196 // We are dealing with a pointer to a base type.
3197 if (TI.getIndex() < TypeIndex::FirstNonSimpleIndex) {
3198 Element = createElement(Kind);
3199 Shared->TypeRecords.add(StreamIdx: StreamTPI, TI, Kind, Element);
3200 Element->setOffset(TI.getIndex());
3201 Element->setOffsetFromTypeIndex();
3202 return Element;
3203 }
3204
3205 W.printString(Value: "** Not implemented. **");
3206 printTypeIndex(FieldName: "TypeIndex", TI, StreamIdx: StreamTPI);
3207 W.printString(Label: "TypeLeafKind", Value: formatTypeLeafKind(K: Kind));
3208 return nullptr;
3209 }
3210
3211 Element->setOffset(TI.getIndex());
3212 Element->setOffsetFromTypeIndex();
3213 return Element;
3214}
3215
3216void LVLogicalVisitor::createDataMember(CVMemberRecord &Record, LVScope *Parent,
3217 StringRef Name, TypeIndex TI,
3218 MemberAccess Access) {
3219 LLVM_DEBUG({
3220 printTypeIndex("TypeIndex", TI, StreamTPI);
3221 W.printString("TypeName", Name);
3222 });
3223
3224 createElement(Kind: Record.Kind);
3225 if (LVSymbol *Symbol = CurrentSymbol) {
3226 Symbol->setName(Name);
3227 if (TI.isNoneType() || TI.isSimple())
3228 Symbol->setType(getElement(StreamIdx: StreamTPI, TI));
3229 else {
3230 LazyRandomTypeCollection &Types = types();
3231 CVType CVMemberType = Types.getType(Index: TI);
3232 if (CVMemberType.kind() == LF_BITFIELD) {
3233 if (Error Err = finishVisitation(Record&: CVMemberType, TI, Element: Symbol)) {
3234 consumeError(Err: std::move(Err));
3235 return;
3236 }
3237 } else
3238 Symbol->setType(getElement(StreamIdx: StreamTPI, TI));
3239 }
3240 Symbol->setAccessibilityCode(Access);
3241 Parent->addElement(Symbol);
3242 }
3243}
3244
3245LVSymbol *LVLogicalVisitor::createParameter(LVElement *Element, StringRef Name,
3246 LVScope *Parent) {
3247 LVSymbol *Parameter = Reader->createSymbol();
3248 Parent->addElement(Symbol: Parameter);
3249 Parameter->setIsParameter();
3250 Parameter->setTag(dwarf::DW_TAG_formal_parameter);
3251 Parameter->setName(Name);
3252 Parameter->setType(Element);
3253 return Parameter;
3254}
3255
3256LVSymbol *LVLogicalVisitor::createParameter(TypeIndex TI, StringRef Name,
3257 LVScope *Parent) {
3258 return createParameter(Element: getElement(StreamIdx: StreamTPI, TI), Name, Parent);
3259}
3260
3261LVType *LVLogicalVisitor::createBaseType(TypeIndex TI, StringRef TypeName) {
3262 TypeLeafKind SimpleKind = (TypeLeafKind)TI.getSimpleKind();
3263 TypeIndex TIR = (TypeIndex)SimpleKind;
3264 LLVM_DEBUG({
3265 printTypeIndex("TypeIndex", TIR, StreamTPI);
3266 W.printString("TypeName", TypeName);
3267 });
3268
3269 if (LVElement *Element = Shared->TypeRecords.find(StreamIdx: StreamTPI, TI: TIR))
3270 return static_cast<LVType *>(Element);
3271
3272 if (createElement(TI: TIR, Kind: SimpleKind)) {
3273 CurrentType->setName(TypeName);
3274 CurrentType->setBitSize(getSizeInBytesForTypeIndex(TI: TIR) * DWARF_CHAR_BIT);
3275 Reader->getCompileUnit()->addElement(Type: CurrentType);
3276 }
3277 return CurrentType;
3278}
3279
3280LVType *LVLogicalVisitor::createPointerType(TypeIndex TI, StringRef TypeName) {
3281 LLVM_DEBUG({
3282 printTypeIndex("TypeIndex", TI, StreamTPI);
3283 W.printString("TypeName", TypeName);
3284 });
3285
3286 if (LVElement *Element = Shared->TypeRecords.find(StreamIdx: StreamTPI, TI))
3287 return static_cast<LVType *>(Element);
3288
3289 LVType *Pointee = createBaseType(TI, TypeName: TypeName.drop_back(N: 1));
3290 if (createElement(TI, Kind: TypeLeafKind::LF_POINTER)) {
3291 CurrentType->setIsFinalized();
3292 CurrentType->setType(Pointee);
3293 Reader->getCompileUnit()->addElement(Type: CurrentType);
3294 }
3295 return CurrentType;
3296}
3297
3298void LVLogicalVisitor::createParents(StringRef ScopedName, LVElement *Element) {
3299 // For the given test case:
3300 //
3301 // struct S { enum E { ... }; };
3302 // S::E V;
3303 //
3304 // 0 | S_LOCAL `V`
3305 // type=0x1004 (S::E), flags = none
3306 // 0x1004 | LF_ENUM `S::E`
3307 // options: has unique name | is nested
3308 // 0x1009 | LF_STRUCTURE `S`
3309 // options: contains nested class
3310 //
3311 // When the local 'V' is processed, its type 'E' is created. But There is
3312 // no direct reference to its parent 'S'. We use the scoped name for 'E',
3313 // to create its parents.
3314
3315 // The input scoped name must have at least parent and nested names.
3316 // Drop the last element name, as it corresponds to the nested type.
3317 LVStringRefs Components = getAllLexicalComponents(Name: ScopedName);
3318 if (Components.size() < 2)
3319 return;
3320 Components.pop_back();
3321
3322 LVStringRefs::size_type FirstNamespace;
3323 LVStringRefs::size_type FirstAggregate;
3324 std::tie(args&: FirstNamespace, args&: FirstAggregate) =
3325 Shared->NamespaceDeduction.find(Components);
3326
3327 LLVM_DEBUG({
3328 W.printString("First Namespace", Components[FirstNamespace]);
3329 W.printString("First NonNamespace", Components[FirstAggregate]);
3330 });
3331
3332 // Create any referenced namespaces.
3333 if (FirstNamespace < FirstAggregate) {
3334 Shared->NamespaceDeduction.get(
3335 Components: LVStringRefs(Components.begin() + FirstNamespace,
3336 Components.begin() + FirstAggregate));
3337 }
3338
3339 // Traverse the enclosing scopes (aggregates) and create them. In the
3340 // case of nested empty aggregates, MSVC does not emit a full record
3341 // description. It emits only the reference record.
3342 LVScope *Aggregate = nullptr;
3343 TypeIndex TIAggregate;
3344 std::string AggregateName = getScopedName(
3345 Components: LVStringRefs(Components.begin(), Components.begin() + FirstAggregate));
3346
3347 // This traversal is executed at least once.
3348 for (LVStringRefs::size_type Index = FirstAggregate;
3349 Index < Components.size(); ++Index) {
3350 AggregateName = getScopedName(Components: LVStringRefs(Components.begin() + Index,
3351 Components.begin() + Index + 1),
3352 BaseName: AggregateName);
3353 TIAggregate = Shared->ForwardReferences.remap(
3354 TI: Shared->TypeRecords.find(StreamIdx: StreamTPI, Name: AggregateName));
3355 Aggregate =
3356 TIAggregate.isNoneType()
3357 ? nullptr
3358 : static_cast<LVScope *>(getElement(StreamIdx: StreamTPI, TI: TIAggregate));
3359 }
3360
3361 // Workaround for cases where LF_NESTTYPE is missing for nested templates.
3362 // If we manage to get parent information from the scoped name, we can add
3363 // the nested type without relying on the LF_NESTTYPE.
3364 if (Aggregate && !Element->getIsScopedAlready()) {
3365 Aggregate->addElement(Element);
3366 Element->setIsScopedAlready();
3367 }
3368}
3369
3370LVElement *LVLogicalVisitor::getElement(uint32_t StreamIdx, TypeIndex TI,
3371 LVScope *Parent) {
3372 LLVM_DEBUG({ printTypeIndex("TypeIndex", TI, StreamTPI); });
3373 TI = Shared->ForwardReferences.remap(TI);
3374 LLVM_DEBUG({ printTypeIndex("TypeIndex Remap", TI, StreamTPI); });
3375
3376 LVElement *Element = Shared->TypeRecords.find(StreamIdx, TI);
3377 if (!Element) {
3378 if (TI.isNoneType() || TI.isSimple()) {
3379 StringRef TypeName = TypeIndex::simpleTypeName(TI);
3380 // If the name ends with "*", create 2 logical types: a pointer and a
3381 // pointee type. TypeIndex is composed of a SympleTypeMode byte followed
3382 // by a SimpleTypeKind byte. The logical pointer will be identified by
3383 // the full TypeIndex value and the pointee by the SimpleTypeKind.
3384 return (TypeName.back() == '*') ? createPointerType(TI, TypeName)
3385 : createBaseType(TI, TypeName);
3386 }
3387
3388 LLVM_DEBUG({ W.printHex("TypeIndex not implemented: ", TI.getIndex()); });
3389 return nullptr;
3390 }
3391
3392 // The element has been finalized.
3393 if (Element->getIsFinalized())
3394 return Element;
3395
3396 // Add the element in case of a given parent.
3397 if (Parent)
3398 Parent->addElement(Element);
3399
3400 // Check for a composite type.
3401 LazyRandomTypeCollection &Types = types();
3402 CVType CVRecord = Types.getType(Index: TI);
3403 if (Error Err = finishVisitation(Record&: CVRecord, TI, Element)) {
3404 consumeError(Err: std::move(Err));
3405 return nullptr;
3406 }
3407 Element->setIsFinalized();
3408 return Element;
3409}
3410
3411void LVLogicalVisitor::processLines() {
3412 // Traverse the collected LF_UDT_SRC_LINE records and add the source line
3413 // information to the logical elements.
3414 for (const TypeIndex &Entry : Shared->LineRecords) {
3415 CVType CVRecord = ids().getType(Index: Entry);
3416 UdtSourceLineRecord Line;
3417 if (Error Err = TypeDeserializer::deserializeAs(
3418 CVT&: const_cast<CVType &>(CVRecord), Record&: Line))
3419 consumeError(Err: std::move(Err));
3420 else {
3421 LLVM_DEBUG({
3422 printTypeIndex("UDT", Line.getUDT(), StreamIPI);
3423 printTypeIndex("SourceFile", Line.getSourceFile(), StreamIPI);
3424 W.printNumber("LineNumber", Line.getLineNumber());
3425 });
3426
3427 // The TypeIndex returned by 'getUDT()' must point to an already
3428 // created logical element. If no logical element is found, it means
3429 // the LF_UDT_SRC_LINE is associated with a system TypeIndex.
3430 if (LVElement *Element = Shared->TypeRecords.find(
3431 StreamIdx: StreamTPI, TI: Line.getUDT(), /*Create=*/false)) {
3432 Element->setLineNumber(Line.getLineNumber());
3433 Element->setFilenameIndex(
3434 Shared->StringRecords.findIndex(TI: Line.getSourceFile()));
3435 }
3436 }
3437 }
3438}
3439
3440void LVLogicalVisitor::processNamespaces() {
3441 // Create namespaces.
3442 Shared->NamespaceDeduction.init();
3443}
3444
3445void LVLogicalVisitor::processFiles() { Shared->StringRecords.addFilenames(); }
3446
3447void LVLogicalVisitor::printRecords(raw_ostream &OS) const {
3448 if (!options().getInternalTag())
3449 return;
3450
3451 unsigned Count = 0;
3452 auto PrintItem = [&](StringRef Name) {
3453 auto NewLine = [&]() {
3454 if (++Count == 4) {
3455 Count = 0;
3456 OS << "\n";
3457 }
3458 };
3459 OS << format(Fmt: "%20s", Vals: Name.str().c_str());
3460 NewLine();
3461 };
3462
3463 OS << "\nTypes:\n";
3464 for (const TypeLeafKind &Kind : Shared->TypeKinds)
3465 PrintItem(formatTypeLeafKind(K: Kind));
3466 Shared->TypeKinds.clear();
3467
3468 Count = 0;
3469 OS << "\nSymbols:\n";
3470 for (const SymbolKind &Kind : Shared->SymbolKinds)
3471 PrintItem(LVCodeViewReader::getSymbolKindName(Kind));
3472 Shared->SymbolKinds.clear();
3473
3474 OS << "\n";
3475}
3476
3477Error LVLogicalVisitor::inlineSiteAnnotation(LVScope *AbstractFunction,
3478 LVScope *InlinedFunction,
3479 InlineSiteSym &InlineSite) {
3480 // Get the parent scope to update the address ranges of the nested
3481 // scope representing the inlined function.
3482 LVAddress ParentLowPC = 0;
3483 LVScope *Parent = InlinedFunction->getParentScope();
3484 if (const LVLocations *Locations = Parent->getRanges()) {
3485 if (!Locations->empty())
3486 ParentLowPC = (*Locations->begin())->getLowerAddress();
3487 }
3488
3489 // For the given inlinesite, get the initial line number and its
3490 // source filename. Update the logical scope representing it.
3491 uint32_t LineNumber = 0;
3492 StringRef Filename;
3493 LVInlineeInfo::iterator Iter = InlineeInfo.find(x: InlineSite.Inlinee);
3494 if (Iter != InlineeInfo.end()) {
3495 LineNumber = Iter->second.first;
3496 Filename = Iter->second.second;
3497 AbstractFunction->setLineNumber(LineNumber);
3498 // TODO: This part needs additional work in order to set properly the
3499 // correct filename in order to detect changes between filenames.
3500 // AbstractFunction->setFilename(Filename);
3501 }
3502
3503 LLVM_DEBUG({
3504 dbgs() << "inlineSiteAnnotation\n"
3505 << "Abstract: " << AbstractFunction->getName() << "\n"
3506 << "Inlined: " << InlinedFunction->getName() << "\n"
3507 << "Parent: " << Parent->getName() << "\n"
3508 << "Low PC: " << hexValue(ParentLowPC) << "\n";
3509 });
3510
3511 // Get the source lines if requested by command line option.
3512 if (!options().getPrintLines())
3513 return Error::success();
3514
3515 // Limitation: Currently we don't track changes in the FileOffset. The
3516 // side effects are the caller that it is unable to differentiate the
3517 // source filename for the inlined code.
3518 uint64_t CodeOffset = ParentLowPC;
3519 int32_t LineOffset = LineNumber;
3520 uint32_t FileOffset = 0;
3521
3522 auto UpdateClose = [&]() { LLVM_DEBUG({ dbgs() << ("\n"); }); };
3523 auto UpdateCodeOffset = [&](uint32_t Delta) {
3524 CodeOffset += Delta;
3525 LLVM_DEBUG({
3526 dbgs() << formatv(" code 0x{0} (+0x{1})", utohexstr(CodeOffset),
3527 utohexstr(Delta));
3528 });
3529 };
3530 auto UpdateLineOffset = [&](int32_t Delta) {
3531 LineOffset += Delta;
3532 LLVM_DEBUG({
3533 char Sign = Delta > 0 ? '+' : '-';
3534 dbgs() << formatv(" line {0} ({1}{2})", LineOffset, Sign,
3535 std::abs(Delta));
3536 });
3537 };
3538 auto UpdateFileOffset = [&](int32_t Offset) {
3539 FileOffset = Offset;
3540 LLVM_DEBUG({ dbgs() << formatv(" file {0}", FileOffset); });
3541 };
3542
3543 LVLines InlineeLines;
3544 auto CreateLine = [&]() {
3545 // Create the logical line record.
3546 LVLineDebug *Line = Reader->createLineDebug();
3547 Line->setAddress(CodeOffset);
3548 Line->setLineNumber(LineOffset);
3549 // TODO: This part needs additional work in order to set properly the
3550 // correct filename in order to detect changes between filenames.
3551 // Line->setFilename(Filename);
3552 InlineeLines.push_back(Elt: Line);
3553 };
3554
3555 bool SeenLowAddress = false;
3556 bool SeenHighAddress = false;
3557 uint64_t LowPC = 0;
3558 uint64_t HighPC = 0;
3559
3560 for (auto &Annot : InlineSite.annotations()) {
3561 LLVM_DEBUG({
3562 dbgs() << formatv(" {0}",
3563 fmt_align(toHex(Annot.Bytes), AlignStyle::Left, 9));
3564 });
3565
3566 // Use the opcode to interpret the integer values.
3567 switch (Annot.OpCode) {
3568 case BinaryAnnotationsOpCode::ChangeCodeOffset:
3569 case BinaryAnnotationsOpCode::CodeOffset:
3570 case BinaryAnnotationsOpCode::ChangeCodeLength:
3571 UpdateCodeOffset(Annot.U1);
3572 UpdateClose();
3573 if (Annot.OpCode == BinaryAnnotationsOpCode::ChangeCodeOffset) {
3574 CreateLine();
3575 LowPC = CodeOffset;
3576 SeenLowAddress = true;
3577 break;
3578 }
3579 if (Annot.OpCode == BinaryAnnotationsOpCode::ChangeCodeLength) {
3580 HighPC = CodeOffset - 1;
3581 SeenHighAddress = true;
3582 }
3583 break;
3584 case BinaryAnnotationsOpCode::ChangeCodeLengthAndCodeOffset:
3585 UpdateCodeOffset(Annot.U2);
3586 UpdateClose();
3587 break;
3588 case BinaryAnnotationsOpCode::ChangeLineOffset:
3589 case BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset:
3590 UpdateCodeOffset(Annot.U1);
3591 UpdateLineOffset(Annot.S1);
3592 UpdateClose();
3593 if (Annot.OpCode ==
3594 BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset)
3595 CreateLine();
3596 break;
3597 case BinaryAnnotationsOpCode::ChangeFile:
3598 UpdateFileOffset(Annot.U1);
3599 UpdateClose();
3600 break;
3601 default:
3602 break;
3603 }
3604 if (SeenLowAddress && SeenHighAddress) {
3605 SeenLowAddress = false;
3606 SeenHighAddress = false;
3607 InlinedFunction->addObject(LowerAddress: LowPC, UpperAddress: HighPC);
3608 }
3609 }
3610
3611 Reader->addInlineeLines(Scope: InlinedFunction, Lines&: InlineeLines);
3612 UpdateClose();
3613
3614 return Error::success();
3615}
3616