LLVM 23.0.0git
CodeViewDebug.cpp
Go to the documentation of this file.
1//===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.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 file contains support for writing Microsoft CodeView debug info.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CodeViewDebug.h"
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/Twine.h"
33#include "llvm/Config/llvm-config.h"
44#include "llvm/IR/Constants.h"
45#include "llvm/IR/DataLayout.h"
47#include "llvm/IR/Function.h"
48#include "llvm/IR/GlobalValue.h"
50#include "llvm/IR/Metadata.h"
51#include "llvm/IR/Module.h"
52#include "llvm/MC/MCAsmInfo.h"
53#include "llvm/MC/MCContext.h"
55#include "llvm/MC/MCStreamer.h"
56#include "llvm/MC/MCSymbol.h"
59#include "llvm/Support/Error.h"
62#include "llvm/Support/Path.h"
63#include "llvm/Support/SMLoc.h"
68#include <algorithm>
69#include <cassert>
70#include <cctype>
71#include <cstddef>
72#include <limits>
73
74using namespace llvm;
75using namespace llvm::codeview;
76
77namespace {
78class CVMCAdapter : public CodeViewRecordStreamer {
79public:
80 CVMCAdapter(MCStreamer &OS, TypeCollection &TypeTable)
81 : OS(&OS), TypeTable(TypeTable) {}
82
83 void emitBytes(StringRef Data) override { OS->emitBytes(Data); }
84
85 void emitIntValue(uint64_t Value, unsigned Size) override {
86 OS->emitIntValueInHex(Value, Size);
87 }
88
89 void emitBinaryData(StringRef Data) override { OS->emitBinaryData(Data); }
90
91 void AddComment(const Twine &T) override { OS->AddComment(T); }
92
93 void AddRawComment(const Twine &T) override { OS->emitRawComment(T); }
94
95 bool isVerboseAsm() override { return OS->isVerboseAsm(); }
96
97 std::string getTypeName(TypeIndex TI) override {
98 std::string TypeName;
99 if (!TI.isNoneType()) {
100 if (TI.isSimple())
101 TypeName = std::string(TypeIndex::simpleTypeName(TI));
102 else
103 TypeName = std::string(TypeTable.getTypeName(TI));
104 }
105 return TypeName;
106 }
107
108private:
109 MCStreamer *OS = nullptr;
110 TypeCollection &TypeTable;
111};
112} // namespace
113
115 switch (Type) {
117 return CPUType::Pentium3;
119 return CPUType::X64;
121 // LLVM currently doesn't support Windows CE and so thumb
122 // here is indiscriminately mapped to ARMNT specifically.
123 return CPUType::ARMNT;
125 return CPUType::ARM64;
127 return CPUType::MIPS;
129 return CPUType::Unknown;
130 default:
131 report_fatal_error("target architecture doesn't map to a CodeView CPUType");
132 }
133}
134
136 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {}
137
138StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
139 std::string &Filepath = FileToFilepathMap[File];
140 if (!Filepath.empty())
141 return Filepath;
142
143 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
144
145 // If this is a Unix-style path, just use it as is. Don't try to canonicalize
146 // it textually because one of the path components could be a symlink.
147 if (Dir.starts_with("/") || Filename.starts_with("/")) {
149 return Filename;
150 Filepath = std::string(Dir);
151 if (Dir.back() != '/')
152 Filepath += '/';
153 Filepath += Filename;
154 return Filepath;
155 }
156
157 // Clang emits directory and relative filename info into the IR, but CodeView
158 // operates on full paths. We could change Clang to emit full paths too, but
159 // that would increase the IR size and probably not needed for other users.
160 // For now, just concatenate and canonicalize the path here.
161 if (Filename.find(':') == 1)
162 Filepath = std::string(Filename);
163 else
164 Filepath = (Dir + "\\" + Filename).str();
165
166 // Canonicalize the path. We have to do it textually because we may no longer
167 // have access the file in the filesystem.
168 // First, replace all slashes with backslashes.
169 llvm::replace(Filepath, '/', '\\');
170
171 // Remove all "\.\" with "\".
172 size_t Cursor = 0;
173 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
174 Filepath.erase(Cursor, 2);
175
176 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
177 // path should be well-formatted, e.g. start with a drive letter, etc.
178 Cursor = 0;
179 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
180 // Something's wrong if the path starts with "\..\", abort.
181 if (Cursor == 0)
182 break;
183
184 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
185 if (PrevSlash == std::string::npos)
186 // Something's wrong, abort.
187 break;
188
189 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
190 // The next ".." might be following the one we've just erased.
191 Cursor = PrevSlash;
192 }
193
194 // Remove all duplicate backslashes.
195 Cursor = 0;
196 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
197 Filepath.erase(Cursor, 1);
198
199 return Filepath;
200}
201
202unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
203 StringRef FullPath = getFullFilepath(F);
204 unsigned NextId = FileIdMap.size() + 1;
205 auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
206 if (Insertion.second) {
207 // We have to compute the full filepath and emit a .cv_file directive.
208 ArrayRef<uint8_t> ChecksumAsBytes;
209 FileChecksumKind CSKind = FileChecksumKind::None;
210 if (F->getChecksum()) {
211 std::string Checksum = fromHex(F->getChecksum()->Value);
212 void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
213 memcpy(CKMem, Checksum.data(), Checksum.size());
214 ChecksumAsBytes = ArrayRef<uint8_t>(
215 reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
216 switch (F->getChecksum()->Kind) {
217 case DIFile::CSK_MD5:
218 CSKind = FileChecksumKind::MD5;
219 break;
220 case DIFile::CSK_SHA1:
221 CSKind = FileChecksumKind::SHA1;
222 break;
224 CSKind = FileChecksumKind::SHA256;
225 break;
226 }
227 }
228 bool Success = OS.emitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
229 static_cast<unsigned>(CSKind));
230 (void)Success;
231 assert(Success && ".cv_file directive failed");
232 }
233 return Insertion.first->second;
234}
235
236CodeViewDebug::InlineSite &
237CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
238 const DISubprogram *Inlinee) {
239 auto SiteInsertion = CurFn->InlineSites.try_emplace(InlinedAt);
240 InlineSite *Site = &SiteInsertion.first->second;
241 if (SiteInsertion.second) {
242 unsigned ParentFuncId = CurFn->FuncId;
243 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
244 ParentFuncId =
245 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
246 .SiteFuncId;
247
248 Site->SiteFuncId = NextFuncId++;
249 OS.emitCVInlineSiteIdDirective(
250 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
251 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
252 Site->Inlinee = Inlinee;
253 InlinedSubprograms.insert(Inlinee);
254 auto InlineeIdx = getFuncIdForSubprogram(Inlinee);
255
256 if (InlinedAt->getInlinedAt() == nullptr)
257 CurFn->Inlinees.insert(InlineeIdx);
258 }
259 return *Site;
260}
261
263 StringRef ScopeName = Scope->getName();
264 if (!ScopeName.empty())
265 return ScopeName;
266
267 switch (Scope->getTag()) {
268 case dwarf::DW_TAG_enumeration_type:
269 case dwarf::DW_TAG_class_type:
270 case dwarf::DW_TAG_structure_type:
271 case dwarf::DW_TAG_union_type:
272 return "<unnamed-tag>";
273 case dwarf::DW_TAG_namespace:
274 return "`anonymous namespace'";
275 default:
276 return StringRef();
277 }
278}
279
280const DISubprogram *CodeViewDebug::collectParentScopeNames(
281 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
282 const DISubprogram *ClosestSubprogram = nullptr;
283 while (Scope != nullptr) {
284 if (ClosestSubprogram == nullptr)
285 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
286
287 // If a type appears in a scope chain, make sure it gets emitted. The
288 // frontend will be responsible for deciding if this should be a forward
289 // declaration or a complete type.
290 if (const auto *Ty = dyn_cast<DICompositeType>(Scope))
291 DeferredCompleteTypes.push_back(Ty);
292
293 StringRef ScopeName = getPrettyScopeName(Scope);
294 if (!ScopeName.empty())
295 QualifiedNameComponents.push_back(ScopeName);
296 Scope = Scope->getScope();
297 }
298 return ClosestSubprogram;
299}
300
301static std::string formatNestedName(ArrayRef<StringRef> QualifiedNameComponents,
302 StringRef TypeName) {
303 std::string FullyQualifiedName;
304 for (StringRef QualifiedNameComponent :
305 llvm::reverse(QualifiedNameComponents)) {
306 FullyQualifiedName.append(std::string(QualifiedNameComponent));
307 FullyQualifiedName.append("::");
308 }
309 FullyQualifiedName.append(std::string(TypeName));
310 return FullyQualifiedName;
311}
312
314 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
316 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
317 // inner TypeLoweringScopes don't attempt to emit deferred types.
318 if (CVD.TypeEmissionLevel == 1)
319 CVD.emitDeferredCompleteTypes();
320 --CVD.TypeEmissionLevel;
321 }
323};
324
325std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Scope,
326 StringRef Name) {
327 // Ensure types in the scope chain are emitted as soon as possible.
328 // This can create otherwise a situation where S_UDTs are emitted while
329 // looping in emitDebugInfoForUDTs.
330 TypeLoweringScope S(*this);
331 SmallVector<StringRef, 5> QualifiedNameComponents;
332 collectParentScopeNames(Scope, QualifiedNameComponents);
333 return formatNestedName(QualifiedNameComponents, Name);
334}
335
336std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Ty) {
337 const DIScope *Scope = Ty->getScope();
338 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
339}
340
341TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
342 // No scope means global scope and that uses the zero index.
343 //
344 // We also use zero index when the scope is a DISubprogram
345 // to suppress the emission of LF_STRING_ID for the function,
346 // which can trigger a link-time error with the linker in
347 // VS2019 version 16.11.2 or newer.
348 // Note, however, skipping the debug info emission for the DISubprogram
349 // is a temporary fix. The root issue here is that we need to figure out
350 // the proper way to encode a function nested in another function
351 // (as introduced by the Fortran 'contains' keyword) in CodeView.
352 if (!Scope || isa<DIFile>(Scope) || isa<DISubprogram>(Scope))
353 return TypeIndex();
354
355 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
356
357 // Check if we've already translated this scope.
358 auto I = TypeIndices.find({Scope, nullptr});
359 if (I != TypeIndices.end())
360 return I->second;
361
362 // Build the fully qualified name of the scope.
363 std::string ScopeName = getFullyQualifiedName(Scope);
364 StringIdRecord SID(TypeIndex(), ScopeName);
365 auto TI = TypeTable.writeLeafType(SID);
366 return recordTypeIndexForDINode(Scope, TI);
367}
368
370 // Remove template args from the display name. Assume that the template args
371 // are the last thing in the name.
372 if (Name.empty() || Name.back() != '>')
373 return Name;
374
375 int OpenBrackets = 0;
376 for (int i = Name.size() - 1; i >= 0; --i) {
377 if (Name[i] == '>')
378 ++OpenBrackets;
379 else if (Name[i] == '<') {
380 --OpenBrackets;
381 if (OpenBrackets == 0)
382 return Name.substr(0, i);
383 }
384 }
385 return Name;
386}
387
388TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
389 assert(SP);
390
391 // Check if we've already translated this subprogram.
392 auto I = TypeIndices.find({SP, nullptr});
393 if (I != TypeIndices.end())
394 return I->second;
395
396 // The display name includes function template arguments. Drop them to match
397 // MSVC. We need to have the template arguments in the DISubprogram name
398 // because they are used in other symbol records, such as S_GPROC32_IDs.
399 StringRef DisplayName = removeTemplateArgs(SP->getName());
400
401 const DIScope *Scope = SP->getScope();
402 TypeIndex TI;
403 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
404 // If the scope is a DICompositeType, then this must be a method. Member
405 // function types take some special handling, and require access to the
406 // subprogram.
407 TypeIndex ClassType = getTypeIndex(Class);
408 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
409 DisplayName);
410 TI = TypeTable.writeLeafType(MFuncId);
411 } else {
412 // Otherwise, this must be a free function.
413 TypeIndex ParentScope = getScopeIndex(Scope);
414 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
415 TI = TypeTable.writeLeafType(FuncId);
416 }
417
418 return recordTypeIndexForDINode(SP, TI);
419}
420
421static bool isNonTrivial(const DICompositeType *DCTy) {
422 return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
423}
424
425static FunctionOptions
427 const DICompositeType *ClassTy = nullptr,
428 StringRef SPName = StringRef("")) {
430 const DIType *ReturnTy = nullptr;
431 if (auto TypeArray = Ty->getTypeArray()) {
432 if (TypeArray.size())
433 ReturnTy = TypeArray[0];
434 }
435
436 // Add CxxReturnUdt option to functions that return nontrivial record types
437 // or methods that return record types.
438 if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy))
439 if (isNonTrivial(ReturnDCTy) || ClassTy)
441
442 // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
443 if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) {
445
446 // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
447
448 }
449 return FO;
450}
451
452TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
453 const DICompositeType *Class) {
454 // Always use the method declaration as the key for the function type. The
455 // method declaration contains the this adjustment.
456 if (SP->getDeclaration())
457 SP = SP->getDeclaration();
458 assert(!SP->getDeclaration() && "should use declaration as key");
459
460 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
461 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
462 auto I = TypeIndices.find({SP, Class});
463 if (I != TypeIndices.end())
464 return I->second;
465
466 // Make sure complete type info for the class is emitted *after* the member
467 // function type, as the complete class type is likely to reference this
468 // member function type.
469 TypeLoweringScope S(*this);
470 const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
471
472 FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
473 TypeIndex TI = lowerTypeMemberFunction(
474 SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
475 return recordTypeIndexForDINode(SP, TI, Class);
476}
477
478TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
479 TypeIndex TI,
480 const DIType *ClassTy) {
481 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
482 (void)InsertResult;
483 assert(InsertResult.second && "DINode was already assigned a type index");
484 return TI;
485}
486
487unsigned CodeViewDebug::getPointerSizeInBytes() {
488 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
489}
490
491void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
492 const LexicalScope *LS) {
493 if (const DILocation *InlinedAt = LS->getInlinedAt()) {
494 // This variable was inlined. Associate it with the InlineSite.
495 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
496 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
497 Site.InlinedLocals.emplace_back(std::move(Var));
498 } else {
499 // This variable goes into the corresponding lexical scope.
500 ScopeVariables[LS].emplace_back(std::move(Var));
501 }
502}
503
505 const DILocation *Loc) {
506 if (!llvm::is_contained(Locs, Loc))
507 Locs.push_back(Loc);
508}
509
510void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
511 const MachineFunction *MF) {
512 // Skip this instruction if it has the same location as the previous one.
513 if (!DL || DL == PrevInstLoc)
514 return;
515
516 const DIScope *Scope = DL->getScope();
517 if (!Scope)
518 return;
519
520 // Skip this line if it is longer than the maximum we can record.
521 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
522 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
523 LI.isNeverStepInto())
524 return;
525
526 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
527 if (CI.getStartColumn() != DL.getCol())
528 return;
529
530 if (!CurFn->HaveLineInfo)
531 CurFn->HaveLineInfo = true;
532 unsigned FileId = 0;
533 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
534 FileId = CurFn->LastFileId;
535 else
536 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
537 PrevInstLoc = DL;
538
539 unsigned FuncId = CurFn->FuncId;
540 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
541 const DILocation *Loc = DL.get();
542
543 // If this location was actually inlined from somewhere else, give it the ID
544 // of the inline call site.
545 FuncId =
546 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
547
548 // Ensure we have links in the tree of inline call sites.
549 bool FirstLoc = true;
550 while ((SiteLoc = Loc->getInlinedAt())) {
551 InlineSite &Site =
552 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
553 if (!FirstLoc)
554 addLocIfNotPresent(Site.ChildSites, Loc);
555 FirstLoc = false;
556 Loc = SiteLoc;
557 }
558 addLocIfNotPresent(CurFn->ChildSites, Loc);
559 }
560
561 OS.emitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
562 /*PrologueEnd=*/false, /*IsStmt=*/false,
563 DL->getFilename(), SMLoc());
564}
565
566void CodeViewDebug::emitCodeViewMagicVersion() {
567 OS.emitValueToAlignment(Align(4));
568 OS.AddComment("Debug section magic");
569 OS.emitInt32(COFF::DEBUG_SECTION_MAGIC);
570}
571
572static SourceLanguage
574 switch (DWLName) {
575 case dwarf::DW_LNAME_C:
576 return SourceLanguage::C;
577 case dwarf::DW_LNAME_C_plus_plus:
578 return SourceLanguage::Cpp;
579 case dwarf::DW_LNAME_Fortran:
580 return SourceLanguage::Fortran;
581 case dwarf::DW_LNAME_Pascal:
582 return SourceLanguage::Pascal;
583 case dwarf::DW_LNAME_Cobol:
584 return SourceLanguage::Cobol;
585 case dwarf::DW_LNAME_Java:
586 return SourceLanguage::Java;
587 case dwarf::DW_LNAME_D:
588 return SourceLanguage::D;
589 case dwarf::DW_LNAME_Swift:
590 return SourceLanguage::Swift;
591 case dwarf::DW_LNAME_Rust:
592 return SourceLanguage::Rust;
593 case dwarf::DW_LNAME_ObjC:
594 return SourceLanguage::ObjC;
595 case dwarf::DW_LNAME_ObjC_plus_plus:
596 return SourceLanguage::ObjCpp;
597 default:
598 // There's no CodeView representation for this language, and CV doesn't
599 // have an "unknown" option for the language field, so we'll use MASM,
600 // as it's very low level.
601 return SourceLanguage::Masm;
602 }
603}
604
606 auto MaybeLName = dwarf::toDW_LNAME(DWLang);
607 if (!MaybeLName)
609
610 return MapDWARFLanguageToCVLang(MaybeLName->first);
611}
612
614 // If COFF debug section is not available, skip any debug info related stuff.
615 if (!Asm->getObjFileLowering().getCOFFDebugSymbolsSection()) {
616 Asm = nullptr;
617 return;
618 }
619
620 CompilerInfoAsm = Asm;
621 TheCPU = mapArchToCVCPUType(M->getTargetTriple().getArch());
622
623 // Get the current source language.
624 const MDNode *Node;
625 if (Asm->hasDebugInfo()) {
626 Node = *M->debug_compile_units_begin();
627 } else {
628 // When emitting only compiler information, we may have only NoDebug CUs,
629 // which would be skipped by debug_compile_units_begin.
630 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
631 if (CUs->operands().empty()) {
632 Asm = nullptr;
633 return;
634 }
635 Node = *CUs->operands().begin();
636 }
637
638 TheCU = cast<DICompileUnit>(Node);
639 DISourceLanguageName Lang = TheCU->getSourceLanguage();
640 CurrentSourceLanguage =
641 Lang.hasVersionedName()
643 static_cast<dwarf::SourceLanguageName>(Lang.getName()))
645 static_cast<dwarf::SourceLanguage>(Lang.getName()));
646 if (!M->getCodeViewFlag() ||
647 TheCU->getEmissionKind() == DICompileUnit::NoDebug) {
648 Asm = nullptr;
649 return;
650 }
651
652 collectGlobalVariableInfo();
653
654 // Check if we should emit type record hashes.
655 ConstantInt *GH =
656 mdconst::extract_or_null<ConstantInt>(M->getModuleFlag("CodeViewGHash"));
657 EmitDebugGlobalHashes = GH && !GH->isZero();
658}
659
661 if (!CompilerInfoAsm)
662 return;
663
664 // The COFF .debug$S section consists of several subsections, each starting
665 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
666 // of the payload followed by the payload itself. The subsections are 4-byte
667 // aligned.
668
669 // Use the generic .debug$S section, and make a subsection for all the inlined
670 // subprograms.
671 switchToDebugSectionForSymbol(nullptr);
672
673 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
674 emitObjName();
675 emitCompilerInformation();
676 endCVSubsection(CompilerInfo);
677 if (!Asm)
678 return;
679
680 emitSecureHotPatchInformation();
681
682 emitInlineeLinesSubsection();
683
684 // Emit per-function debug information.
685 for (auto &P : FnDebugInfo)
686 if (!P.first->isDeclarationForLinker())
687 emitDebugInfoForFunction(P.first, *P.second);
688
689 // Get types used by globals without emitting anything.
690 // This is meant to collect all static const data members so they can be
691 // emitted as globals.
692 collectDebugInfoForGlobals();
693
694 // Emit retained types.
695 emitDebugInfoForRetainedTypes();
696
697 // Emit global variable debug information.
698 setCurrentSubprogram(nullptr);
699 emitDebugInfoForGlobals();
700
701 // Switch back to the generic .debug$S section after potentially processing
702 // comdat symbol sections.
703 switchToDebugSectionForSymbol(nullptr);
704
705 // Emit UDT records for any types used by global variables.
706 if (!GlobalUDTs.empty()) {
707 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
708 emitDebugInfoForUDTs(GlobalUDTs);
709 endCVSubsection(SymbolsEnd);
710 }
711
712 // This subsection holds a file index to offset in string table table.
713 OS.AddComment("File index to string table offset subsection");
714 OS.emitCVFileChecksumsDirective();
715
716 // This subsection holds the string table.
717 OS.AddComment("String table");
718 OS.emitCVStringTableDirective();
719
720 // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
721 // subsection in the generic .debug$S section at the end. There is no
722 // particular reason for this ordering other than to match MSVC.
723 emitBuildInfo();
724
725 // Emit type information and hashes last, so that any types we translate while
726 // emitting function info are included.
727 emitTypeInformation();
728
729 if (EmitDebugGlobalHashes)
730 emitTypeGlobalHashes();
731
732 clear();
733}
734
735static void
737 unsigned MaxFixedRecordLength = 0xF00) {
738 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
739 // after a fixed length portion of the record. The fixed length portion should
740 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
741 // overall record size is less than the maximum allowed.
742 SmallString<32> NullTerminatedString(
743 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
744 NullTerminatedString.push_back('\0');
745 OS.emitBytes(NullTerminatedString);
746}
747
748void CodeViewDebug::emitTypeInformation() {
749 if (TypeTable.empty())
750 return;
751
752 // Start the .debug$T or .debug$P section with 0x4.
753 OS.switchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
754 emitCodeViewMagicVersion();
755
756 TypeTableCollection Table(TypeTable.records());
757 TypeVisitorCallbackPipeline Pipeline;
758
759 // To emit type record using Codeview MCStreamer adapter
760 CVMCAdapter CVMCOS(OS, Table);
761 TypeRecordMapping typeMapping(CVMCOS);
762 Pipeline.addCallbackToPipeline(typeMapping);
763
764 std::optional<TypeIndex> B = Table.getFirst();
765 while (B) {
766 // This will fail if the record data is invalid.
767 CVType Record = Table.getType(*B);
768
769 Error E = codeview::visitTypeRecord(Record, *B, Pipeline);
770
771 if (E) {
772 logAllUnhandledErrors(std::move(E), errs(), "error: ");
773 llvm_unreachable("produced malformed type record");
774 }
775
776 B = Table.getNext(*B);
777 }
778}
779
780void CodeViewDebug::emitTypeGlobalHashes() {
781 if (TypeTable.empty())
782 return;
783
784 // Start the .debug$H section with the version and hash algorithm, currently
785 // hardcoded to version 0, SHA1.
786 OS.switchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
787
788 OS.emitValueToAlignment(Align(4));
789 OS.AddComment("Magic");
791 OS.AddComment("Section Version");
792 OS.emitInt16(0);
793 OS.AddComment("Hash Algorithm");
794 OS.emitInt16(uint16_t(GlobalTypeHashAlg::BLAKE3));
795
796 TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
797 for (const auto &GHR : TypeTable.hashes()) {
798 if (OS.isVerboseAsm()) {
799 // Emit an EOL-comment describing which TypeIndex this hash corresponds
800 // to, as well as the stringified SHA1 hash.
801 SmallString<32> Comment;
802 raw_svector_ostream CommentOS(Comment);
803 CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
804 OS.AddComment(Comment);
805 ++TI;
806 }
807 assert(GHR.Hash.size() == 8);
808 StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
809 GHR.Hash.size());
810 OS.emitBinaryData(S);
811 }
812}
813
814void CodeViewDebug::emitObjName() {
815 MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_OBJNAME);
816
817 StringRef PathRef(CompilerInfoAsm->TM.Options.ObjectFilenameForDebug);
818 llvm::SmallString<256> PathStore(PathRef);
819
820 if (PathRef.empty() || PathRef == "-") {
821 // Don't emit the filename if we're writing to stdout or to /dev/null.
822 PathRef = {};
823 } else {
824 PathRef = PathStore;
825 }
826
827 OS.AddComment("Signature");
828 OS.emitIntValue(0, 4);
829
830 OS.AddComment("Object name");
831 emitNullTerminatedSymbolName(OS, PathRef);
832
833 endSymbolRecord(CompilerEnd);
834}
835
836void CodeViewDebug::emitSecureHotPatchInformation() {
837 MCSymbol *hotPatchInfo = nullptr;
838
839 for (const auto &F : MMI->getModule()->functions()) {
840 if (!F.isDeclarationForLinker() &&
841 F.hasFnAttribute("marked_for_windows_hot_patching")) {
842 if (hotPatchInfo == nullptr)
843 hotPatchInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
844 MCSymbol *HotPatchEnd = beginSymbolRecord(SymbolKind::S_HOTPATCHFUNC);
845 auto *SP = F.getSubprogram();
846 OS.AddComment("Function");
847 OS.emitInt32(getFuncIdForSubprogram(SP).getIndex());
848 OS.AddComment("Name");
849 emitNullTerminatedSymbolName(OS, F.getName());
850 endSymbolRecord(HotPatchEnd);
851 }
852 }
853
854 if (hotPatchInfo != nullptr)
855 endCVSubsection(hotPatchInfo);
856}
857
858namespace {
859struct Version {
860 int Part[4];
861};
862} // end anonymous namespace
863
864// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
865// the version number.
866static Version parseVersion(StringRef Name) {
867 Version V = {{0}};
868 int N = 0;
869 for (const char C : Name) {
870 if (isdigit(C)) {
871 V.Part[N] *= 10;
872 V.Part[N] += C - '0';
873 V.Part[N] =
874 std::min<int>(V.Part[N], std::numeric_limits<uint16_t>::max());
875 } else if (C == '.') {
876 ++N;
877 if (N >= 4)
878 return V;
879 } else if (N > 0)
880 return V;
881 }
882 return V;
883}
884
885void CodeViewDebug::emitCompilerInformation() {
886 MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
887 uint32_t Flags = 0;
888
889 // The low byte of the flags indicates the source language.
890 Flags = CurrentSourceLanguage;
891 // TODO: Figure out which other flags need to be set.
892 if (MMI->getModule()->getProfileSummary(/*IsCS*/ false) != nullptr) {
893 Flags |= static_cast<uint32_t>(CompileSym3Flags::PGO);
894 }
895 using ArchType = llvm::Triple::ArchType;
896 ArchType Arch = MMI->getModule()->getTargetTriple().getArch();
897 if (CompilerInfoAsm->TM.Options.Hotpatch || Arch == ArchType::thumb ||
898 Arch == ArchType::aarch64) {
899 Flags |= static_cast<uint32_t>(CompileSym3Flags::HotPatch);
900 }
901
902 OS.AddComment("Flags and language");
903 OS.emitInt32(Flags);
904
905 OS.AddComment("CPUType");
906 OS.emitInt16(static_cast<uint64_t>(TheCPU));
907
908 StringRef CompilerVersion = "0";
909 if (TheCU)
910 CompilerVersion = TheCU->getProducer();
911
912 Version FrontVer = parseVersion(CompilerVersion);
913 OS.AddComment("Frontend version");
914 for (int N : FrontVer.Part) {
915 OS.emitInt16(N);
916 }
917
918 // Some Microsoft tools, like Binscope, expect a backend version number of at
919 // least 8.something, so we'll coerce the LLVM version into a form that
920 // guarantees it'll be big enough without really lying about the version.
921 int Major = 1000 * LLVM_VERSION_MAJOR +
922 10 * LLVM_VERSION_MINOR +
923 LLVM_VERSION_PATCH;
924 // Clamp it for builds that use unusually large version numbers.
925 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
926 Version BackVer = {{ Major, 0, 0, 0 }};
927 OS.AddComment("Backend version");
928 for (int N : BackVer.Part)
929 OS.emitInt16(N);
930
931 OS.AddComment("Null-terminated compiler version string");
932 emitNullTerminatedSymbolName(OS, CompilerVersion);
933
934 endSymbolRecord(CompilerEnd);
935}
936
938 StringRef S) {
939 StringIdRecord SIR(TypeIndex(0x0), S);
940 return TypeTable.writeLeafType(SIR);
941}
942
943void CodeViewDebug::emitBuildInfo() {
944 // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
945 // build info. The known prefix is:
946 // - Absolute path of current directory
947 // - Compiler path
948 // - Main source file path, relative to CWD or absolute
949 // - Type server PDB file
950 // - Canonical compiler command line
951 // If frontend and backend compilation are separated (think llc or LTO), it's
952 // not clear if the compiler path should refer to the executable for the
953 // frontend or the backend. Leave it blank for now.
954 TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
955 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
956 const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
957 const auto *CU = cast<DICompileUnit>(Node);
958 const DIFile *MainSourceFile = CU->getFile();
959 BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
960 getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
961 BuildInfoArgs[BuildInfoRecord::SourceFile] =
962 getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
963 // FIXME: PDB is intentionally blank unless we implement /Zi type servers.
964 BuildInfoArgs[BuildInfoRecord::TypeServerPDB] =
965 getStringIdTypeIdx(TypeTable, "");
966 BuildInfoArgs[BuildInfoRecord::BuildTool] =
967 getStringIdTypeIdx(TypeTable, Asm->TM.Options.MCOptions.Argv0);
969 TypeTable, Asm->TM.Options.MCOptions.CommandlineArgs);
970
971 BuildInfoRecord BIR(BuildInfoArgs);
972 TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
973
974 // Make a new .debug$S subsection for the S_BUILDINFO record, which points
975 // from the module symbols into the type stream.
976 MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
977 MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
978 OS.AddComment("LF_BUILDINFO index");
979 OS.emitInt32(BuildInfoIndex.getIndex());
980 endSymbolRecord(BIEnd);
981 endCVSubsection(BISubsecEnd);
982}
983
984void CodeViewDebug::emitInlineeLinesSubsection() {
985 if (InlinedSubprograms.empty())
986 return;
987
988 OS.AddComment("Inlinee lines subsection");
989 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
990
991 // We emit the checksum info for files. This is used by debuggers to
992 // determine if a pdb matches the source before loading it. Visual Studio,
993 // for instance, will display a warning that the breakpoints are not valid if
994 // the pdb does not match the source.
995 OS.AddComment("Inlinee lines signature");
996 OS.emitInt32(unsigned(InlineeLinesSignature::Normal));
997
998 for (const DISubprogram *SP : InlinedSubprograms) {
999 assert(TypeIndices.count({SP, nullptr}));
1000 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
1001
1002 OS.addBlankLine();
1003 unsigned FileId = maybeRecordFile(SP->getFile());
1004 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
1005 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
1006 OS.addBlankLine();
1007 OS.AddComment("Type index of inlined function");
1008 OS.emitInt32(InlineeIdx.getIndex());
1009 OS.AddComment("Offset into filechecksum table");
1010 OS.emitCVFileChecksumOffsetDirective(FileId);
1011 OS.AddComment("Starting line number");
1012 OS.emitInt32(SP->getLine());
1013 }
1014
1015 endCVSubsection(InlineEnd);
1016}
1017
1018void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
1019 const DILocation *InlinedAt,
1020 const InlineSite &Site) {
1021 assert(TypeIndices.count({Site.Inlinee, nullptr}));
1022 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
1023
1024 // SymbolRecord
1025 MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
1026
1027 OS.AddComment("PtrParent");
1028 OS.emitInt32(0);
1029 OS.AddComment("PtrEnd");
1030 OS.emitInt32(0);
1031 OS.AddComment("Inlinee type index");
1032 OS.emitInt32(InlineeIdx.getIndex());
1033
1034 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
1035 unsigned StartLineNum = Site.Inlinee->getLine();
1036
1037 OS.emitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
1038 FI.Begin, FI.End);
1039
1040 endSymbolRecord(InlineEnd);
1041
1042 emitLocalVariableList(FI, Site.InlinedLocals);
1043
1044 // Recurse on child inlined call sites before closing the scope.
1045 for (const DILocation *ChildSite : Site.ChildSites) {
1046 auto I = FI.InlineSites.find(ChildSite);
1047 assert(I != FI.InlineSites.end() &&
1048 "child site not in function inline site map");
1049 emitInlinedCallSite(FI, ChildSite, I->second);
1050 }
1051
1052 // Close the scope.
1053 emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
1054}
1055
1056void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
1057 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
1058 // comdat key. A section may be comdat because of -ffunction-sections or
1059 // because it is comdat in the IR.
1060 MCSectionCOFF *GVSec =
1061 GVSym ? static_cast<MCSectionCOFF *>(&GVSym->getSection()) : nullptr;
1062 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
1063
1064 auto *DebugSec = static_cast<MCSectionCOFF *>(
1065 CompilerInfoAsm->getObjFileLowering().getCOFFDebugSymbolsSection());
1066 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
1067
1068 OS.switchSection(DebugSec);
1069
1070 // Emit the magic version number if this is the first time we've switched to
1071 // this section.
1072 if (ComdatDebugSections.insert(DebugSec).second)
1073 emitCodeViewMagicVersion();
1074}
1075
1076// Emit an S_THUNK32/S_END symbol pair for a thunk routine.
1077// The only supported thunk ordinal is currently the standard type.
1078void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
1079 FunctionInfo &FI,
1080 const MCSymbol *Fn) {
1081 std::string FuncName =
1082 std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
1083 const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
1084
1085 OS.AddComment("Symbol subsection for " + Twine(FuncName));
1086 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
1087
1088 // Emit S_THUNK32
1089 MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
1090 OS.AddComment("PtrParent");
1091 OS.emitInt32(0);
1092 OS.AddComment("PtrEnd");
1093 OS.emitInt32(0);
1094 OS.AddComment("PtrNext");
1095 OS.emitInt32(0);
1096 OS.AddComment("Thunk section relative address");
1097 OS.emitCOFFSecRel32(Fn, /*Offset=*/0);
1098 OS.AddComment("Thunk section index");
1099 OS.emitCOFFSectionIndex(Fn);
1100 OS.AddComment("Code size");
1101 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
1102 OS.AddComment("Ordinal");
1103 OS.emitInt8(unsigned(ordinal));
1104 OS.AddComment("Function name");
1105 emitNullTerminatedSymbolName(OS, FuncName);
1106 // Additional fields specific to the thunk ordinal would go here.
1107 endSymbolRecord(ThunkRecordEnd);
1108
1109 // Local variables/inlined routines are purposely omitted here. The point of
1110 // marking this as a thunk is so Visual Studio will NOT stop in this routine.
1111
1112 // Emit S_PROC_ID_END
1113 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1114
1115 endCVSubsection(SymbolsEnd);
1116}
1117
1118void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
1119 FunctionInfo &FI) {
1120 // For each function there is a separate subsection which holds the PC to
1121 // file:line table.
1122 const MCSymbol *Fn = Asm->getSymbol(GV);
1123 assert(Fn);
1124
1125 // Switch to the to a comdat section, if appropriate.
1126 switchToDebugSectionForSymbol(Fn);
1127
1128 std::string FuncName;
1129 auto *SP = GV->getSubprogram();
1130 assert(SP);
1131 setCurrentSubprogram(SP);
1132
1133 if (SP->isThunk()) {
1134 emitDebugInfoForThunk(GV, FI, Fn);
1135 return;
1136 }
1137
1138 // If we have a display name, build the fully qualified name by walking the
1139 // chain of scopes.
1140 if (!SP->getName().empty())
1141 FuncName = getFullyQualifiedName(SP->getScope(), SP->getName());
1142
1143 // If our DISubprogram name is empty, use the mangled name.
1144 if (FuncName.empty())
1145 FuncName = std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
1146
1147 // Emit FPO data, but only on 32-bit x86. No other platforms use it.
1148 if (MMI->getModule()->getTargetTriple().getArch() == Triple::x86)
1149 OS.emitCVFPOData(Fn);
1150
1151 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
1152 OS.AddComment("Symbol subsection for " + Twine(FuncName));
1153 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
1154 {
1155 SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
1156 : SymbolKind::S_GPROC32_ID;
1157 MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
1158
1159 // These fields are filled in by tools like CVPACK which run after the fact.
1160 OS.AddComment("PtrParent");
1161 OS.emitInt32(0);
1162 OS.AddComment("PtrEnd");
1163 OS.emitInt32(0);
1164 OS.AddComment("PtrNext");
1165 OS.emitInt32(0);
1166 // This is the important bit that tells the debugger where the function
1167 // code is located and what's its size:
1168 OS.AddComment("Code size");
1169 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
1170 OS.AddComment("Offset after prologue");
1171 OS.emitInt32(0);
1172 OS.AddComment("Offset before epilogue");
1173 OS.emitInt32(0);
1174 OS.AddComment("Function type index");
1175 OS.emitInt32(getFuncIdForSubprogram(GV->getSubprogram()).getIndex());
1176 OS.AddComment("Function section relative address");
1177 OS.emitCOFFSecRel32(Fn, /*Offset=*/0);
1178 OS.AddComment("Function section index");
1179 OS.emitCOFFSectionIndex(Fn);
1180 OS.AddComment("Flags");
1181 ProcSymFlags ProcFlags = ProcSymFlags::HasOptimizedDebugInfo;
1182 if (FI.HasFramePointer)
1183 ProcFlags |= ProcSymFlags::HasFP;
1184 if (GV->hasFnAttribute(Attribute::NoReturn))
1185 ProcFlags |= ProcSymFlags::IsNoReturn;
1186 if (GV->hasFnAttribute(Attribute::NoInline))
1187 ProcFlags |= ProcSymFlags::IsNoInline;
1188 OS.emitInt8(static_cast<uint8_t>(ProcFlags));
1189 // Emit the function display name as a null-terminated string.
1190 OS.AddComment("Function name");
1191 // Truncate the name so we won't overflow the record length field.
1192 emitNullTerminatedSymbolName(OS, FuncName);
1193 endSymbolRecord(ProcRecordEnd);
1194
1195 MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
1196 // Subtract out the CSR size since MSVC excludes that and we include it.
1197 OS.AddComment("FrameSize");
1198 OS.emitInt32(FI.FrameSize - FI.CSRSize);
1199 OS.AddComment("Padding");
1200 OS.emitInt32(0);
1201 OS.AddComment("Offset of padding");
1202 OS.emitInt32(0);
1203 OS.AddComment("Bytes of callee saved registers");
1204 OS.emitInt32(FI.CSRSize);
1205 OS.AddComment("Exception handler offset");
1206 OS.emitInt32(0);
1207 OS.AddComment("Exception handler section");
1208 OS.emitInt16(0);
1209 OS.AddComment("Flags (defines frame register)");
1210 OS.emitInt32(uint32_t(FI.FrameProcOpts));
1211 endSymbolRecord(FrameProcEnd);
1212
1213 emitInlinees(FI.Inlinees);
1214 emitLocalVariableList(FI, FI.Locals);
1215 emitGlobalVariableList(FI.Globals);
1216 emitLexicalBlockList(FI.ChildBlocks, FI);
1217
1218 // Emit inlined call site information. Only emit functions inlined directly
1219 // into the parent function. We'll emit the other sites recursively as part
1220 // of their parent inline site.
1221 for (const DILocation *InlinedAt : FI.ChildSites) {
1222 auto I = FI.InlineSites.find(InlinedAt);
1223 assert(I != FI.InlineSites.end() &&
1224 "child site not in function inline site map");
1225 emitInlinedCallSite(FI, InlinedAt, I->second);
1226 }
1227
1228 for (auto Annot : FI.Annotations) {
1229 MCSymbol *Label = Annot.first;
1230 MDTuple *Strs = cast<MDTuple>(Annot.second);
1231 MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
1232 OS.emitCOFFSecRel32(Label, /*Offset=*/0);
1233 // FIXME: Make sure we don't overflow the max record size.
1234 OS.emitCOFFSectionIndex(Label);
1235 OS.emitInt16(Strs->getNumOperands());
1236 for (Metadata *MD : Strs->operands()) {
1237 // MDStrings are null terminated, so we can do EmitBytes and get the
1238 // nice .asciz directive.
1239 StringRef Str = cast<MDString>(MD)->getString();
1240 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1241 OS.emitBytes(StringRef(Str.data(), Str.size() + 1));
1242 }
1243 endSymbolRecord(AnnotEnd);
1244 }
1245
1246 for (auto HeapAllocSite : FI.HeapAllocSites) {
1247 const MCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
1248 const MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
1249 const DIType *DITy = std::get<2>(HeapAllocSite);
1250 MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
1251 OS.AddComment("Call site offset");
1252 OS.emitCOFFSecRel32(BeginLabel, /*Offset=*/0);
1253 OS.AddComment("Call site section index");
1254 OS.emitCOFFSectionIndex(BeginLabel);
1255 OS.AddComment("Call instruction length");
1256 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
1257 OS.AddComment("Type index");
1258 OS.emitInt32(getCompleteTypeIndex(DITy).getIndex());
1259 endSymbolRecord(HeapAllocEnd);
1260 }
1261
1262 if (SP != nullptr)
1263 emitDebugInfoForUDTs(LocalUDTs);
1264
1265 emitDebugInfoForJumpTables(FI);
1266
1267 // We're done with this function.
1268 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1269 }
1270 endCVSubsection(SymbolsEnd);
1271
1272 // We have an assembler directive that takes care of the whole line table.
1273 OS.emitCVLinetableDirective(FI.FuncId, Fn, FI.End);
1274}
1275
1277CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset,
1278 int32_t DerefOffset) {
1279 LocalVarDef DR;
1280 DR.InMemory = -1;
1281 DR.DataOffset = Offset;
1282 assert(DR.DataOffset == Offset && "truncation");
1283 DR.IsSubfield = 0;
1284 DR.StructOffset = 0;
1285 DR.CVRegister = CVRegister;
1286 DR.DerefOffset = DerefOffset;
1287 return DR;
1288}
1289
1290void CodeViewDebug::collectVariableInfoFromMFTable(
1291 DenseSet<InlinedEntity> &Processed) {
1292 const MachineFunction &MF = *Asm->MF;
1293 const TargetSubtargetInfo &TSI = MF.getSubtarget();
1294 const TargetFrameLowering *TFI = TSI.getFrameLowering();
1295 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1296
1297 for (const MachineFunction::VariableDbgInfo &VI :
1299 if (!VI.Var)
1300 continue;
1301 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1302 "Expected inlined-at fields to agree");
1303
1304 Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
1305 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1306
1307 // If variable scope is not found then skip this variable.
1308 if (!Scope)
1309 continue;
1310
1311 // If the variable has an attached offset expression, extract it.
1312 int64_t ExprOffset = 0;
1313 int64_t DerefOffset = LocalVarDef::NoDeref;
1314 if (VI.Expr) {
1315 SmallVector<uint64_t, 2> FirstRemaining;
1316 if (!VI.Expr->extractLeadingOffset(ExprOffset, FirstRemaining))
1317 continue;
1318 if (!FirstRemaining.empty()) {
1319 if (FirstRemaining.front() != dwarf::DW_OP_deref)
1320 continue;
1321 SmallVector<uint64_t, 1> LastRemaining;
1323 ArrayRef(FirstRemaining).drop_front(), DerefOffset,
1324 LastRemaining))
1325 continue;
1326 if (!LastRemaining.empty())
1327 continue;
1328 }
1329 }
1330
1331 // Get the frame register used and the offset.
1332 Register FrameReg;
1333 StackOffset FrameOffset =
1334 TFI->getFrameIndexReference(*Asm->MF, VI.getStackSlot(), FrameReg);
1335 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
1336
1337 if (FrameOffset.getScalable()) {
1338 // No encoding currently exists for scalable offsets; bail out.
1339 continue;
1340 }
1341 if (DerefOffset < INT32_MIN || DerefOffset > INT32_MAX)
1342 continue;
1343
1344 // Calculate the label ranges.
1345 LocalVarDef DefRange =
1346 createDefRangeMem(CVReg, FrameOffset.getFixed() + ExprOffset,
1347 static_cast<int32_t>(DerefOffset));
1348
1349 LocalVariable Var;
1350 Var.DIVar = VI.Var;
1351
1352 for (const InsnRange &Range : Scope->getRanges()) {
1353 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1354 const MCSymbol *End = getLabelAfterInsn(Range.second);
1355 End = End ? End : Asm->getFunctionEnd();
1356 Var.DefRanges[DefRange].emplace_back(Begin, End);
1357 }
1358
1359 recordLocalVariable(std::move(Var), Scope);
1360 }
1361}
1362
1363void CodeViewDebug::calculateRanges(
1364 LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) {
1365 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1366
1367 // Calculate the definition ranges.
1368 for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) {
1369 const auto &Entry = *I;
1370 if (!Entry.isDbgValue())
1371 continue;
1372 const MachineInstr *DVInst = Entry.getInstr();
1373 assert(DVInst->isDebugValue() && "Invalid History entry");
1374 // FIXME: Find a way to represent constant variables, since they are
1375 // relatively common.
1376 std::optional<DbgVariableLocation> Location =
1378 if (!Location)
1379 {
1380 // When we don't have a location this is usually because LLVM has
1381 // transformed it into a constant and we only have an llvm.dbg.value. We
1382 // can't represent these well in CodeView since S_LOCAL only works on
1383 // registers and memory locations. Instead, we will pretend this to be a
1384 // constant value to at least have it show up in the debugger.
1385 auto Op = DVInst->getDebugOperand(0);
1386 if (Op.isImm())
1387 Var.ConstantValue = APSInt(APInt(64, Op.getImm()), false);
1388 continue;
1389 }
1390
1391 // We can only handle a register, an offsetted load of a register, or an
1392 // indirect offsetted load.
1393 if (!Location->Register || Location->LoadChain.size() > 2)
1394 continue;
1395
1396 // Codeview can only express byte-aligned offsets, ensure that we have a
1397 // byte-boundaried location.
1398 if (Location->FragmentInfo)
1399 if (Location->FragmentInfo->OffsetInBits % 8)
1400 continue;
1401
1402 if (TRI->isIgnoredCVReg(Location->Register)) {
1403 // No encoding currently exists for this register; bail out.
1404 continue;
1405 }
1406
1407 LocalVarDef DR;
1408 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
1409 DR.InMemory = !Location->LoadChain.empty();
1410 DR.DataOffset = 0;
1411 DR.DerefOffset = LocalVarDef::NoDeref;
1412 if (!Location->LoadChain.empty()) {
1413 DR.DataOffset = Location->LoadChain[0];
1414 if (Location->LoadChain.size() >= 2)
1415 DR.DerefOffset = Location->LoadChain[1];
1416 }
1417 if (Location->FragmentInfo) {
1418 DR.IsSubfield = true;
1419 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
1420 } else {
1421 DR.IsSubfield = false;
1422 DR.StructOffset = 0;
1423 }
1424
1425 // Compute the label range.
1426 const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr());
1427 const MCSymbol *End;
1428 if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
1429 auto &EndingEntry = Entries[Entry.getEndIndex()];
1430 End = EndingEntry.isDbgValue()
1431 ? getLabelBeforeInsn(EndingEntry.getInstr())
1432 : getLabelAfterInsn(EndingEntry.getInstr());
1433 } else
1434 End = Asm->getFunctionEnd();
1435
1436 // If the last range end is our begin, just extend the last range.
1437 // Otherwise make a new range.
1438 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1439 Var.DefRanges[DR];
1440 if (!R.empty() && R.back().second == Begin)
1441 R.back().second = End;
1442 else
1443 R.emplace_back(Begin, End);
1444
1445 // FIXME: Do more range combining.
1446 }
1447}
1448
1449void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1450 DenseSet<InlinedEntity> Processed;
1451 // Grab the variable info that was squirreled away in the MMI side-table.
1452 collectVariableInfoFromMFTable(Processed);
1453
1454 for (const auto &I : DbgValues) {
1455 InlinedEntity IV = I.first;
1456 if (Processed.count(IV))
1457 continue;
1458 const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
1459 const DILocation *InlinedAt = IV.second;
1460
1461 // Instruction ranges, specifying where IV is accessible.
1462 const auto &Entries = I.second;
1463
1464 LexicalScope *Scope = nullptr;
1465 if (InlinedAt)
1466 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1467 else
1468 Scope = LScopes.findLexicalScope(DIVar->getScope());
1469 // If variable scope is not found then skip this variable.
1470 if (!Scope)
1471 continue;
1472
1473 LocalVariable Var;
1474 Var.DIVar = DIVar;
1475
1476 calculateRanges(Var, Entries);
1477 recordLocalVariable(std::move(Var), Scope);
1478 }
1479}
1480
1482 const TargetSubtargetInfo &TSI = MF->getSubtarget();
1483 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1484 const MachineFrameInfo &MFI = MF->getFrameInfo();
1485 const Function &GV = MF->getFunction();
1486 auto Insertion = FnDebugInfo.insert({&GV, std::make_unique<FunctionInfo>()});
1487 assert(Insertion.second && "function already has info");
1488 CurFn = Insertion.first->second.get();
1489 CurFn->FuncId = NextFuncId++;
1490 CurFn->Begin = Asm->getFunctionBegin();
1491
1492 // The S_FRAMEPROC record reports the stack size, and how many bytes of
1493 // callee-saved registers were used. For targets that don't use a PUSH
1494 // instruction (AArch64), this will be zero.
1495 CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1496 CurFn->FrameSize = MFI.getStackSize();
1497 CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
1498 CurFn->HasStackRealignment = TRI->hasStackRealignment(*MF);
1499
1500 // For this function S_FRAMEPROC record, figure out which codeview register
1501 // will be the frame pointer.
1502 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1503 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1504 if (CurFn->FrameSize > 0) {
1505 if (!TSI.getFrameLowering()->hasFP(*MF)) {
1506 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1507 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1508 } else {
1509 CurFn->HasFramePointer = true;
1510 // If there is an FP, parameters are always relative to it.
1511 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
1512 if (CurFn->HasStackRealignment) {
1513 // If the stack needs realignment, locals are relative to SP or VFRAME.
1514 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1515 } else {
1516 // Otherwise, locals are relative to EBP, and we probably have VLAs or
1517 // other stack adjustments.
1518 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1519 }
1520 }
1521 }
1522
1523 // Compute other frame procedure options.
1525 if (MFI.hasVarSizedObjects())
1527 if (MF->exposesReturnsTwice())
1529 // FIXME: Set HasLongJmp if we ever track that info.
1530 if (MF->hasInlineAsm())
1532 if (GV.hasPersonalityFn()) {
1536 else
1538 }
1539 if (GV.hasFnAttribute(Attribute::InlineHint))
1541 if (GV.hasFnAttribute(Attribute::Naked))
1543 if (MFI.hasStackProtectorIndex()) {
1545 if (GV.hasFnAttribute(Attribute::StackProtectStrong) ||
1546 GV.hasFnAttribute(Attribute::StackProtectReq)) {
1548 }
1549 } else if (!GV.hasStackProtectorFnAttr()) {
1550 // __declspec(safebuffers) disables stack guards.
1552 }
1553 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1554 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1555 if (Asm->TM.getOptLevel() != CodeGenOptLevel::None && !GV.hasOptSize() &&
1556 !GV.hasOptNone())
1558 if (GV.hasProfileData()) {
1561 }
1562 // FIXME: Set GuardCfg when it is implemented.
1563 CurFn->FrameProcOpts = FPO;
1564
1565 OS.emitCVFuncIdDirective(CurFn->FuncId);
1566
1567 // Find the end of the function prolog. First known non-DBG_VALUE and
1568 // non-frame setup location marks the beginning of the function body.
1569 // FIXME: is there a simpler a way to do this? Can we just search
1570 // for the first instruction of the function, not the last of the prolog?
1572 bool EmptyPrologue = true;
1573 for (const auto &MBB : *MF) {
1574 for (const auto &MI : MBB) {
1575 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1576 MI.getDebugLoc()) {
1577 PrologEndLoc = MI.getDebugLoc();
1578 break;
1579 } else if (!MI.isMetaInstruction()) {
1580 EmptyPrologue = false;
1581 }
1582 }
1583 }
1584
1585 // Record beginning of function if we have a non-empty prologue.
1586 if (PrologEndLoc && !EmptyPrologue) {
1587 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1588 maybeRecordLocation(FnStartDL, MF);
1589 }
1590
1591 // Find heap alloc sites and emit labels around them.
1592 for (const auto &MBB : *MF) {
1593 for (const auto &MI : MBB) {
1594 if (MI.getHeapAllocMarker()) {
1597 }
1598 }
1599 }
1600
1601 // Mark branches that may potentially be using jump tables with labels.
1602 bool isThumb = MMI->getModule()->getTargetTriple().getArch() ==
1604 discoverJumpTableBranches(MF, isThumb);
1605}
1606
1607static bool shouldEmitUdt(const DIType *T) {
1608 if (!T)
1609 return false;
1610
1611 // MSVC does not emit UDTs for typedefs that are scoped to classes.
1612 if (T->getTag() == dwarf::DW_TAG_typedef) {
1613 if (DIScope *Scope = T->getScope()) {
1614 switch (Scope->getTag()) {
1615 case dwarf::DW_TAG_structure_type:
1616 case dwarf::DW_TAG_class_type:
1617 case dwarf::DW_TAG_union_type:
1618 return false;
1619 default:
1620 // do nothing.
1621 ;
1622 }
1623 }
1624 }
1625
1626 while (true) {
1627 if (!T || T->isForwardDecl())
1628 return false;
1629
1631 if (!DT)
1632 return true;
1633 T = DT->getBaseType();
1634 }
1635 return true;
1636}
1637
1638void CodeViewDebug::addToUDTs(const DIType *Ty) {
1639 // Don't record empty UDTs.
1640 if (Ty->getName().empty())
1641 return;
1642 if (!shouldEmitUdt(Ty))
1643 return;
1644
1645 SmallVector<StringRef, 5> ParentScopeNames;
1646 const DISubprogram *ClosestSubprogram =
1647 collectParentScopeNames(Ty->getScope(), ParentScopeNames);
1648
1649 std::string FullyQualifiedName =
1650 formatNestedName(ParentScopeNames, getPrettyScopeName(Ty));
1651
1652 if (ClosestSubprogram == nullptr) {
1653 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1654 } else if (ClosestSubprogram == CurrentSubprogram) {
1655 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1656 }
1657
1658 // TODO: What if the ClosestSubprogram is neither null or the current
1659 // subprogram? Currently, the UDT just gets dropped on the floor.
1660 //
1661 // The current behavior is not desirable. To get maximal fidelity, we would
1662 // need to perform all type translation before beginning emission of .debug$S
1663 // and then make LocalUDTs a member of FunctionInfo
1664}
1665
1666TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1667 // Generic dispatch for lowering an unknown type.
1668 switch (Ty->getTag()) {
1669 case dwarf::DW_TAG_array_type:
1670 return lowerTypeArray(cast<DICompositeType>(Ty));
1671 case dwarf::DW_TAG_typedef:
1672 return lowerTypeAlias(cast<DIDerivedType>(Ty));
1673 case dwarf::DW_TAG_base_type:
1674 return lowerTypeBasic(cast<DIBasicType>(Ty));
1675 case dwarf::DW_TAG_pointer_type:
1676 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1677 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1678 [[fallthrough]];
1679 case dwarf::DW_TAG_reference_type:
1680 case dwarf::DW_TAG_rvalue_reference_type:
1681 return lowerTypePointer(cast<DIDerivedType>(Ty));
1682 case dwarf::DW_TAG_ptr_to_member_type:
1683 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1684 case dwarf::DW_TAG_restrict_type:
1685 case dwarf::DW_TAG_const_type:
1686 case dwarf::DW_TAG_volatile_type:
1687 // TODO: add support for DW_TAG_atomic_type here
1688 return lowerTypeModifier(cast<DIDerivedType>(Ty));
1689 case dwarf::DW_TAG_subroutine_type:
1690 if (ClassTy) {
1691 // The member function type of a member function pointer has no
1692 // ThisAdjustment.
1693 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1694 /*ThisAdjustment=*/0,
1695 /*IsStaticMethod=*/false);
1696 }
1697 return lowerTypeFunction(cast<DISubroutineType>(Ty));
1698 case dwarf::DW_TAG_enumeration_type:
1699 return lowerTypeEnum(cast<DICompositeType>(Ty));
1700 case dwarf::DW_TAG_class_type:
1701 case dwarf::DW_TAG_structure_type:
1702 return lowerTypeClass(cast<DICompositeType>(Ty));
1703 case dwarf::DW_TAG_union_type:
1704 return lowerTypeUnion(cast<DICompositeType>(Ty));
1705 case dwarf::DW_TAG_string_type:
1706 return lowerTypeString(cast<DIStringType>(Ty));
1707 case dwarf::DW_TAG_unspecified_type:
1708 if (Ty->getName() == "decltype(nullptr)")
1709 return TypeIndex::NullptrT();
1710 return TypeIndex::None();
1711 default:
1712 // Use the null type index.
1713 return TypeIndex();
1714 }
1715}
1716
1717TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1718 TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
1719 StringRef TypeName = Ty->getName();
1720
1721 addToUDTs(Ty);
1722
1723 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1724 TypeName == "HRESULT")
1725 return TypeIndex(SimpleTypeKind::HResult);
1726 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1727 TypeName == "wchar_t")
1728 return TypeIndex(SimpleTypeKind::WideCharacter);
1729
1730 return UnderlyingTypeIndex;
1731}
1732
1733TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1734 const DIType *ElementType = Ty->getBaseType();
1735 TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
1736 // IndexType is size_t, which depends on the bitness of the target.
1737 TypeIndex IndexType = getPointerSizeInBytes() == 8
1738 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1739 : TypeIndex(SimpleTypeKind::UInt32Long);
1740
1741 uint64_t ElementSize = getBaseTypeSize(ElementType) / 8;
1742
1743 // Add subranges to array type.
1744 DINodeArray Elements = Ty->getElements();
1745 for (int i = Elements.size() - 1; i >= 0; --i) {
1746 const DINode *Element = Elements[i];
1747 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1748
1749 const DISubrange *Subrange = cast<DISubrange>(Element);
1750 int64_t Count = -1;
1751
1752 // If Subrange has a Count field, use it.
1753 // Otherwise, if it has an upperboud, use (upperbound - lowerbound + 1),
1754 // where lowerbound is from the LowerBound field of the Subrange,
1755 // or the language default lowerbound if that field is unspecified.
1756 if (auto *CI = dyn_cast_if_present<ConstantInt *>(Subrange->getCount()))
1757 Count = CI->getSExtValue();
1758 else if (auto *UI = dyn_cast_if_present<ConstantInt *>(
1759 Subrange->getUpperBound())) {
1760 // Fortran uses 1 as the default lowerbound; other languages use 0.
1761 int64_t Lowerbound = (moduleIsInFortran()) ? 1 : 0;
1762 auto *LI = dyn_cast_if_present<ConstantInt *>(Subrange->getLowerBound());
1763 Lowerbound = (LI) ? LI->getSExtValue() : Lowerbound;
1764 Count = UI->getSExtValue() - Lowerbound + 1;
1765 }
1766
1767 // Forward declarations of arrays without a size and VLAs use a count of -1.
1768 // Emit a count of zero in these cases to match what MSVC does for arrays
1769 // without a size. MSVC doesn't support VLAs, so it's not clear what we
1770 // should do for them even if we could distinguish them.
1771 if (Count == -1)
1772 Count = 0;
1773
1774 // Update the element size and element type index for subsequent subranges.
1775 ElementSize *= Count;
1776
1777 // If this is the outermost array, use the size from the array. It will be
1778 // more accurate if we had a VLA or an incomplete element type size.
1779 uint64_t ArraySize =
1780 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1781
1782 StringRef Name = (i == 0) ? Ty->getName() : "";
1783 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1784 ElementTypeIndex = TypeTable.writeLeafType(AR);
1785 }
1786
1787 return ElementTypeIndex;
1788}
1789
1790// This function lowers a Fortran character type (DIStringType).
1791// Note that it handles only the character*n variant (using SizeInBits
1792// field in DIString to describe the type size) at the moment.
1793// Other variants (leveraging the StringLength and StringLengthExp
1794// fields in DIStringType) remain TBD.
1795TypeIndex CodeViewDebug::lowerTypeString(const DIStringType *Ty) {
1796 TypeIndex CharType = TypeIndex(SimpleTypeKind::NarrowCharacter);
1797 uint64_t ArraySize = Ty->getSizeInBits() >> 3;
1798 StringRef Name = Ty->getName();
1799 // IndexType is size_t, which depends on the bitness of the target.
1800 TypeIndex IndexType = getPointerSizeInBytes() == 8
1801 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1802 : TypeIndex(SimpleTypeKind::UInt32Long);
1803
1804 // Create a type of character array of ArraySize.
1805 ArrayRecord AR(CharType, IndexType, ArraySize, Name);
1806
1807 return TypeTable.writeLeafType(AR);
1808}
1809
1810TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1811 TypeIndex Index;
1813 uint32_t ByteSize;
1814
1815 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1816 ByteSize = Ty->getSizeInBits() / 8;
1817
1818 SimpleTypeKind STK = SimpleTypeKind::None;
1819 switch (Kind) {
1820 case dwarf::DW_ATE_address:
1821 // FIXME: Translate
1822 break;
1823 case dwarf::DW_ATE_boolean:
1824 switch (ByteSize) {
1825 case 1: STK = SimpleTypeKind::Boolean8; break;
1826 case 2: STK = SimpleTypeKind::Boolean16; break;
1827 case 4: STK = SimpleTypeKind::Boolean32; break;
1828 case 8: STK = SimpleTypeKind::Boolean64; break;
1829 case 16: STK = SimpleTypeKind::Boolean128; break;
1830 }
1831 break;
1832 case dwarf::DW_ATE_complex_float:
1833 // The CodeView size for a complex represents the size of
1834 // an individual component.
1835 switch (ByteSize) {
1836 case 4: STK = SimpleTypeKind::Complex16; break;
1837 case 8: STK = SimpleTypeKind::Complex32; break;
1838 case 16: STK = SimpleTypeKind::Complex64; break;
1839 case 20: STK = SimpleTypeKind::Complex80; break;
1840 case 32: STK = SimpleTypeKind::Complex128; break;
1841 }
1842 break;
1843 case dwarf::DW_ATE_float:
1844 switch (ByteSize) {
1845 case 2: STK = SimpleTypeKind::Float16; break;
1846 case 4: STK = SimpleTypeKind::Float32; break;
1847 case 6: STK = SimpleTypeKind::Float48; break;
1848 case 8: STK = SimpleTypeKind::Float64; break;
1849 case 10: STK = SimpleTypeKind::Float80; break;
1850 case 16: STK = SimpleTypeKind::Float128; break;
1851 }
1852 break;
1853 case dwarf::DW_ATE_signed:
1854 switch (ByteSize) {
1855 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1856 case 2: STK = SimpleTypeKind::Int16Short; break;
1857 case 4: STK = SimpleTypeKind::Int32; break;
1858 case 8: STK = SimpleTypeKind::Int64Quad; break;
1859 case 16: STK = SimpleTypeKind::Int128Oct; break;
1860 }
1861 break;
1862 case dwarf::DW_ATE_unsigned:
1863 switch (ByteSize) {
1864 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1865 case 2: STK = SimpleTypeKind::UInt16Short; break;
1866 case 4: STK = SimpleTypeKind::UInt32; break;
1867 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1868 case 16: STK = SimpleTypeKind::UInt128Oct; break;
1869 }
1870 break;
1871 case dwarf::DW_ATE_UTF:
1872 switch (ByteSize) {
1873 case 1: STK = SimpleTypeKind::Character8; break;
1874 case 2: STK = SimpleTypeKind::Character16; break;
1875 case 4: STK = SimpleTypeKind::Character32; break;
1876 }
1877 break;
1878 case dwarf::DW_ATE_signed_char:
1879 if (ByteSize == 1)
1880 STK = SimpleTypeKind::SignedCharacter;
1881 break;
1882 case dwarf::DW_ATE_unsigned_char:
1883 if (ByteSize == 1)
1884 STK = SimpleTypeKind::UnsignedCharacter;
1885 break;
1886 default:
1887 break;
1888 }
1889
1890 // Apply some fixups based on the source-level type name.
1891 // Include some amount of canonicalization from an old naming scheme Clang
1892 // used to use for integer types (in an outdated effort to be compatible with
1893 // GCC's debug info/GDB's behavior, which has since been addressed).
1894 if (STK == SimpleTypeKind::Int32 &&
1895 (Ty->getName() == "long int" || Ty->getName() == "long"))
1896 STK = SimpleTypeKind::Int32Long;
1897 if (STK == SimpleTypeKind::UInt32 && (Ty->getName() == "long unsigned int" ||
1898 Ty->getName() == "unsigned long"))
1899 STK = SimpleTypeKind::UInt32Long;
1900 if (STK == SimpleTypeKind::UInt16Short &&
1901 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1902 STK = SimpleTypeKind::WideCharacter;
1903 if ((STK == SimpleTypeKind::SignedCharacter ||
1904 STK == SimpleTypeKind::UnsignedCharacter) &&
1905 Ty->getName() == "char")
1906 STK = SimpleTypeKind::NarrowCharacter;
1907
1908 return TypeIndex(STK);
1909}
1910
1911TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1912 PointerOptions PO) {
1913 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1914
1915 // Pointers to simple types without any options can use SimpleTypeMode, rather
1916 // than having a dedicated pointer type record.
1917 if (PointeeTI.isSimple() && PO == PointerOptions::None &&
1918 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1919 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1920 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1921 ? SimpleTypeMode::NearPointer64
1922 : SimpleTypeMode::NearPointer32;
1923 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1924 }
1925
1926 PointerKind PK =
1927 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1928 PointerMode PM = PointerMode::Pointer;
1929 switch (Ty->getTag()) {
1930 default: llvm_unreachable("not a pointer tag type");
1931 case dwarf::DW_TAG_pointer_type:
1932 PM = PointerMode::Pointer;
1933 break;
1934 case dwarf::DW_TAG_reference_type:
1935 PM = PointerMode::LValueReference;
1936 break;
1937 case dwarf::DW_TAG_rvalue_reference_type:
1938 PM = PointerMode::RValueReference;
1939 break;
1940 }
1941
1942 if (Ty->isObjectPointer())
1943 PO |= PointerOptions::Const;
1944
1945 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1946 return TypeTable.writeLeafType(PR);
1947}
1948
1950translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1951 // SizeInBytes being zero generally implies that the member pointer type was
1952 // incomplete, which can happen if it is part of a function prototype. In this
1953 // case, use the unknown model instead of the general model.
1954 if (IsPMF) {
1955 switch (Flags & DINode::FlagPtrToMemberRep) {
1956 case 0:
1957 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1959 case DINode::FlagSingleInheritance:
1961 case DINode::FlagMultipleInheritance:
1963 case DINode::FlagVirtualInheritance:
1965 }
1966 } else {
1967 switch (Flags & DINode::FlagPtrToMemberRep) {
1968 case 0:
1969 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1971 case DINode::FlagSingleInheritance:
1973 case DINode::FlagMultipleInheritance:
1975 case DINode::FlagVirtualInheritance:
1977 }
1978 }
1979 llvm_unreachable("invalid ptr to member representation");
1980}
1981
1982TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1983 PointerOptions PO) {
1984 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1985 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1986 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1987 TypeIndex PointeeTI =
1988 getTypeIndex(Ty->getBaseType(), IsPMF ? Ty->getClassType() : nullptr);
1989 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1990 : PointerKind::Near32;
1991 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1992 : PointerMode::PointerToDataMember;
1993
1994 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1995 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1996 MemberPointerInfo MPI(
1997 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1998 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1999 return TypeTable.writeLeafType(PR);
2000}
2001
2002/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
2003/// have a translation, use the NearC convention.
2004static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
2005 switch (DwarfCC) {
2006 case dwarf::DW_CC_normal: return CallingConvention::NearC;
2007 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
2008 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
2009 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
2010 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
2011 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
2012 }
2014}
2015
2016TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
2017 ModifierOptions Mods = ModifierOptions::None;
2018 PointerOptions PO = PointerOptions::None;
2019 bool IsModifier = true;
2020 const DIType *BaseTy = Ty;
2021 while (IsModifier && BaseTy) {
2022 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
2023 switch (BaseTy->getTag()) {
2024 case dwarf::DW_TAG_const_type:
2025 Mods |= ModifierOptions::Const;
2026 PO |= PointerOptions::Const;
2027 break;
2028 case dwarf::DW_TAG_volatile_type:
2029 Mods |= ModifierOptions::Volatile;
2030 PO |= PointerOptions::Volatile;
2031 break;
2032 case dwarf::DW_TAG_restrict_type:
2033 // Only pointer types be marked with __restrict. There is no known flag
2034 // for __restrict in LF_MODIFIER records.
2035 PO |= PointerOptions::Restrict;
2036 break;
2037 default:
2038 IsModifier = false;
2039 break;
2040 }
2041 if (IsModifier)
2042 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType();
2043 }
2044
2045 // Check if the inner type will use an LF_POINTER record. If so, the
2046 // qualifiers will go in the LF_POINTER record. This comes up for types like
2047 // 'int *const' and 'int *__restrict', not the more common cases like 'const
2048 // char *'.
2049 if (BaseTy) {
2050 switch (BaseTy->getTag()) {
2051 case dwarf::DW_TAG_pointer_type:
2052 case dwarf::DW_TAG_reference_type:
2053 case dwarf::DW_TAG_rvalue_reference_type:
2054 return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
2055 case dwarf::DW_TAG_ptr_to_member_type:
2056 return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
2057 default:
2058 break;
2059 }
2060 }
2061
2062 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
2063
2064 // Return the base type index if there aren't any modifiers. For example, the
2065 // metadata could contain restrict wrappers around non-pointer types.
2066 if (Mods == ModifierOptions::None)
2067 return ModifiedTI;
2068
2069 ModifierRecord MR(ModifiedTI, Mods);
2070 return TypeTable.writeLeafType(MR);
2071}
2072
2073TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
2074 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
2075 for (const DIType *ArgType : Ty->getTypeArray())
2076 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType));
2077
2078 // MSVC uses type none for variadic argument.
2079 if (ReturnAndArgTypeIndices.size() > 1 &&
2080 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
2081 ReturnAndArgTypeIndices.back() = TypeIndex::None();
2082 }
2083 TypeIndex ReturnTypeIndex = TypeIndex::Void();
2084 ArrayRef<TypeIndex> ArgTypeIndices = {};
2085 if (!ReturnAndArgTypeIndices.empty()) {
2086 auto ReturnAndArgTypesRef = ArrayRef(ReturnAndArgTypeIndices);
2087 ReturnTypeIndex = ReturnAndArgTypesRef.consume_front();
2088 ArgTypeIndices = ReturnAndArgTypesRef;
2089 }
2090
2091 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
2092 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
2093
2095
2097 ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
2098 ArgListIndex);
2099 return TypeTable.writeLeafType(Procedure);
2100}
2101
2102TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
2103 const DIType *ClassTy,
2104 int ThisAdjustment,
2105 bool IsStaticMethod,
2106 FunctionOptions FO) {
2107 // Lower the containing class type.
2108 TypeIndex ClassType = getTypeIndex(ClassTy);
2109
2110 DITypeArray ReturnAndArgs = Ty->getTypeArray();
2111
2112 unsigned Index = 0;
2113 SmallVector<TypeIndex, 8> ArgTypeIndices;
2114 TypeIndex ReturnTypeIndex = TypeIndex::Void();
2115 if (ReturnAndArgs.size() > Index) {
2116 ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
2117 }
2118
2119 // If the first argument is a pointer type and this isn't a static method,
2120 // treat it as the special 'this' parameter, which is encoded separately from
2121 // the arguments.
2122 TypeIndex ThisTypeIndex;
2123 if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
2124 if (const DIDerivedType *PtrTy =
2125 dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
2126 if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
2127 ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
2128 Index++;
2129 }
2130 }
2131 }
2132
2133 while (Index < ReturnAndArgs.size())
2134 ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
2135
2136 // MSVC uses type none for variadic argument.
2137 if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
2138 ArgTypeIndices.back() = TypeIndex::None();
2139
2140 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
2141 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
2142
2144
2145 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
2146 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
2147 return TypeTable.writeLeafType(MFR);
2148}
2149
2150TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
2151 unsigned VSlotCount =
2152 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
2153 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
2154
2155 VFTableShapeRecord VFTSR(Slots);
2156 return TypeTable.writeLeafType(VFTSR);
2157}
2158
2159static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
2160 switch (Flags & DINode::FlagAccessibility) {
2161 case DINode::FlagPrivate: return MemberAccess::Private;
2162 case DINode::FlagPublic: return MemberAccess::Public;
2163 case DINode::FlagProtected: return MemberAccess::Protected;
2164 case 0:
2165 // If there was no explicit access control, provide the default for the tag.
2166 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
2168 }
2169 llvm_unreachable("access flags are exclusive");
2170}
2171
2173 if (SP->isArtificial())
2175
2176 // FIXME: Handle other MethodOptions.
2177
2178 return MethodOptions::None;
2179}
2180
2182 bool Introduced) {
2183 if (SP->getFlags() & DINode::FlagStaticMember)
2184 return MethodKind::Static;
2185
2186 switch (SP->getVirtuality()) {
2187 case dwarf::DW_VIRTUALITY_none:
2188 break;
2189 case dwarf::DW_VIRTUALITY_virtual:
2191 case dwarf::DW_VIRTUALITY_pure_virtual:
2192 return Introduced ? MethodKind::PureIntroducingVirtual
2194 default:
2195 llvm_unreachable("unhandled virtuality case");
2196 }
2197
2198 return MethodKind::Vanilla;
2199}
2200
2202 switch (Ty->getTag()) {
2203 case dwarf::DW_TAG_class_type:
2204 return TypeRecordKind::Class;
2205 case dwarf::DW_TAG_structure_type:
2206 return TypeRecordKind::Struct;
2207 default:
2208 llvm_unreachable("unexpected tag");
2209 }
2210}
2211
2212/// Return ClassOptions that should be present on both the forward declaration
2213/// and the defintion of a tag type.
2216
2217 // MSVC always sets this flag, even for local types. Clang doesn't always
2218 // appear to give every type a linkage name, which may be problematic for us.
2219 // FIXME: Investigate the consequences of not following them here.
2220 if (!Ty->getIdentifier().empty())
2222
2223 // Put the Nested flag on a type if it appears immediately inside a tag type.
2224 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
2225 // here. That flag is only set on definitions, and not forward declarations.
2226 const DIScope *ImmediateScope = Ty->getScope();
2227 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
2229
2230 // Put the Scoped flag on function-local types. MSVC puts this flag for enum
2231 // type only when it has an immediate function scope. Clang never puts enums
2232 // inside DILexicalBlock scopes. Enum types, as generated by clang, are
2233 // always in function, class, or file scopes.
2234 if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
2235 if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
2237 } else {
2238 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
2239 Scope = Scope->getScope()) {
2240 if (isa<DISubprogram>(Scope)) {
2242 break;
2243 }
2244 }
2245 }
2246
2247 return CO;
2248}
2249
2250void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
2251 switch (Ty->getTag()) {
2252 case dwarf::DW_TAG_class_type:
2253 case dwarf::DW_TAG_structure_type:
2254 case dwarf::DW_TAG_union_type:
2255 case dwarf::DW_TAG_enumeration_type:
2256 break;
2257 default:
2258 return;
2259 }
2260
2261 if (const auto *File = Ty->getFile()) {
2262 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
2263 TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
2264
2265 UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
2266 TypeTable.writeLeafType(USLR);
2267 }
2268}
2269
2270TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
2272 TypeIndex FTI;
2273 unsigned EnumeratorCount = 0;
2274
2275 if (Ty->isForwardDecl()) {
2276 CO |= ClassOptions::ForwardReference;
2277 } else {
2278 ContinuationRecordBuilder ContinuationBuilder;
2279 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2280 for (const DINode *Element : Ty->getElements()) {
2281 // We assume that the frontend provides all members in source declaration
2282 // order, which is what MSVC does.
2283 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
2284 // FIXME: Is it correct to always emit these as unsigned here?
2285 EnumeratorRecord ER(MemberAccess::Public,
2286 APSInt(Enumerator->getValue(), true),
2287 Enumerator->getName());
2288 ContinuationBuilder.writeMemberType(ER);
2289 EnumeratorCount++;
2290 }
2291 }
2292 FTI = TypeTable.insertRecord(ContinuationBuilder);
2293 }
2294
2295 std::string FullName = getFullyQualifiedName(Ty);
2296
2297 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2298 getTypeIndex(Ty->getBaseType()));
2299 TypeIndex EnumTI = TypeTable.writeLeafType(ER);
2300
2301 addUDTSrcLine(Ty, EnumTI);
2302
2303 return EnumTI;
2304}
2305
2306//===----------------------------------------------------------------------===//
2307// ClassInfo
2308//===----------------------------------------------------------------------===//
2309
2315 // [MemberInfo]
2316 using MemberList = std::vector<MemberInfo>;
2317
2319 // MethodName -> MethodsList
2321
2322 /// Base classes.
2323 std::vector<const DIDerivedType *> Inheritance;
2324
2325 /// Direct members.
2327 // Direct overloaded methods gathered by name.
2329
2331
2332 std::vector<const DIType *> NestedTypes;
2333};
2334
2335void CodeViewDebug::clear() {
2336 assert(CurFn == nullptr);
2337 FileIdMap.clear();
2338 FnDebugInfo.clear();
2339 FileToFilepathMap.clear();
2340 LocalUDTs.clear();
2341 GlobalUDTs.clear();
2342 TypeIndices.clear();
2343 CompleteTypeIndices.clear();
2344 ScopeGlobals.clear();
2345 CVGlobalVariableOffsets.clear();
2346}
2347
2348void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2349 const DIDerivedType *DDTy) {
2350 if (!DDTy->getName().empty()) {
2351 Info.Members.push_back({DDTy, 0});
2352
2353 // Collect static const data members with values.
2354 if ((DDTy->getFlags() & DINode::FlagStaticMember) ==
2355 DINode::FlagStaticMember) {
2356 if (DDTy->getConstant() && (isa<ConstantInt>(DDTy->getConstant()) ||
2357 isa<ConstantFP>(DDTy->getConstant())))
2358 StaticConstMembers.push_back(DDTy);
2359 }
2360
2361 return;
2362 }
2363
2364 // An unnamed member may represent a nested struct or union. Attempt to
2365 // interpret the unnamed member as a DICompositeType possibly wrapped in
2366 // qualifier types. Add all the indirect fields to the current record if that
2367 // succeeds, and drop the member if that fails.
2368 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
2369 uint64_t Offset = DDTy->getOffsetInBits();
2370 const DIType *Ty = DDTy->getBaseType();
2371 bool FullyResolved = false;
2372 while (!FullyResolved) {
2373 switch (Ty->getTag()) {
2374 case dwarf::DW_TAG_const_type:
2375 case dwarf::DW_TAG_volatile_type:
2376 // FIXME: we should apply the qualifier types to the indirect fields
2377 // rather than dropping them.
2378 Ty = cast<DIDerivedType>(Ty)->getBaseType();
2379 break;
2380 default:
2381 FullyResolved = true;
2382 break;
2383 }
2384 }
2385
2386 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2387 if (!DCTy)
2388 return;
2389
2390 ClassInfo NestedInfo = collectClassInfo(DCTy);
2391 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
2392 Info.Members.push_back(
2393 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
2394}
2395
2396ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2397 ClassInfo Info;
2398 // Add elements to structure type.
2399 DINodeArray Elements = Ty->getElements();
2400 for (auto *Element : Elements) {
2401 // We assume that the frontend provides all members in source declaration
2402 // order, which is what MSVC does.
2403 if (!Element)
2404 continue;
2405 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
2406 Info.Methods[SP->getRawName()].push_back(SP);
2407 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
2408 if (DDTy->getTag() == dwarf::DW_TAG_member) {
2409 collectMemberInfo(Info, DDTy);
2410 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2411 Info.Inheritance.push_back(DDTy);
2412 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2413 DDTy->getName() == "__vtbl_ptr_type") {
2414 Info.VShapeTI = getTypeIndex(DDTy);
2415 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2416 Info.NestedTypes.push_back(DDTy);
2417 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2418 // Ignore friend members. It appears that MSVC emitted info about
2419 // friends in the past, but modern versions do not.
2420 }
2421 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
2422 Info.NestedTypes.push_back(Composite);
2423 }
2424 // Skip other unrecognized kinds of elements.
2425 }
2426 return Info;
2427}
2428
2430 // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2431 // if a complete type should be emitted instead of a forward reference.
2432 return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2433 !Ty->isForwardDecl();
2434}
2435
2436TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
2437 // Emit the complete type for unnamed structs. C++ classes with methods
2438 // which have a circular reference back to the class type are expected to
2439 // be named by the front-end and should not be "unnamed". C unnamed
2440 // structs should not have circular references.
2442 // If this unnamed complete type is already in the process of being defined
2443 // then the description of the type is malformed and cannot be emitted
2444 // into CodeView correctly so report a fatal error.
2445 auto I = CompleteTypeIndices.find(Ty);
2446 if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2447 report_fatal_error("cannot debug circular reference to unnamed type");
2448 return getCompleteTypeIndex(Ty);
2449 }
2450
2451 // First, construct the forward decl. Don't look into Ty to compute the
2452 // forward decl options, since it might not be available in all TUs.
2454 ClassOptions CO =
2455 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2456 std::string FullName = getFullyQualifiedName(Ty);
2457 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2458 FullName, Ty->getIdentifier());
2459 TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
2460 if (!Ty->isForwardDecl())
2461 DeferredCompleteTypes.push_back(Ty);
2462 return FwdDeclTI;
2463}
2464
2465TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2466 // Construct the field list and complete type record.
2469 TypeIndex FieldTI;
2470 TypeIndex VShapeTI;
2471 unsigned FieldCount;
2473 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2474 lowerRecordFieldList(Ty);
2475
2477 CO |= ClassOptions::ContainsNestedClass;
2478
2479 // MSVC appears to set this flag by searching any destructor or method with
2480 // FunctionOptions::Constructor among the emitted members. Clang AST has all
2481 // the members, however special member functions are not yet emitted into
2482 // debug information. For now checking a class's non-triviality seems enough.
2483 // FIXME: not true for a nested unnamed struct.
2484 if (isNonTrivial(Ty))
2485 CO |= ClassOptions::HasConstructorOrDestructor;
2486
2487 std::string FullName = getFullyQualifiedName(Ty);
2488
2489 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2490
2491 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2492 SizeInBytes, FullName, Ty->getIdentifier());
2493 TypeIndex ClassTI = TypeTable.writeLeafType(CR);
2494
2495 addUDTSrcLine(Ty, ClassTI);
2496
2497 addToUDTs(Ty);
2498
2499 return ClassTI;
2500}
2501
2502TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
2503 // Emit the complete type for unnamed unions.
2505 return getCompleteTypeIndex(Ty);
2506
2507 ClassOptions CO =
2508 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2509 std::string FullName = getFullyQualifiedName(Ty);
2510 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
2511 TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
2512 if (!Ty->isForwardDecl())
2513 DeferredCompleteTypes.push_back(Ty);
2514 return FwdDeclTI;
2515}
2516
2517TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
2518 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
2519 TypeIndex FieldTI;
2520 unsigned FieldCount;
2522 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2523 lowerRecordFieldList(Ty);
2524
2526 CO |= ClassOptions::ContainsNestedClass;
2527
2528 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2529 std::string FullName = getFullyQualifiedName(Ty);
2530
2531 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2532 Ty->getIdentifier());
2533 TypeIndex UnionTI = TypeTable.writeLeafType(UR);
2534
2535 addUDTSrcLine(Ty, UnionTI);
2536
2537 addToUDTs(Ty);
2538
2539 return UnionTI;
2540}
2541
2542std::tuple<TypeIndex, TypeIndex, unsigned, bool>
2543CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2544 // Manually count members. MSVC appears to count everything that generates a
2545 // field list record. Each individual overload in a method overload group
2546 // contributes to this count, even though the overload group is a single field
2547 // list record.
2548 unsigned MemberCount = 0;
2549 ClassInfo Info = collectClassInfo(Ty);
2550 ContinuationRecordBuilder ContinuationBuilder;
2551 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2552
2553 // Create base classes.
2554 for (const DIDerivedType *I : Info.Inheritance) {
2555 if (I->getFlags() & DINode::FlagVirtual) {
2556 // Virtual base.
2557 unsigned VBPtrOffset = I->getVBPtrOffset();
2558 // FIXME: Despite the accessor name, the offset is really in bytes.
2559 unsigned VBTableIndex = I->getOffsetInBits() / 4;
2560 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2561 ? TypeRecordKind::IndirectVirtualBaseClass
2562 : TypeRecordKind::VirtualBaseClass;
2563 VirtualBaseClassRecord VBCR(
2564 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
2565 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
2566 VBTableIndex);
2567
2568 ContinuationBuilder.writeMemberType(VBCR);
2569 MemberCount++;
2570 } else {
2571 assert(I->getOffsetInBits() % 8 == 0 &&
2572 "bases must be on byte boundaries");
2573 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2574 getTypeIndex(I->getBaseType()),
2575 I->getOffsetInBits() / 8);
2576 ContinuationBuilder.writeMemberType(BCR);
2577 MemberCount++;
2578 }
2579 }
2580
2581 // Create members.
2582 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2583 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2584 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
2585 StringRef MemberName = Member->getName();
2587 translateAccessFlags(Ty->getTag(), Member->getFlags());
2588
2589 if (Member->isStaticMember()) {
2590 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
2591 ContinuationBuilder.writeMemberType(SDMR);
2592 MemberCount++;
2593 continue;
2594 }
2595
2596 // Virtual function pointer member.
2597 if ((Member->getFlags() & DINode::FlagArtificial) &&
2598 Member->getName().starts_with("_vptr$")) {
2599 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
2600 ContinuationBuilder.writeMemberType(VFPR);
2601 MemberCount++;
2602 continue;
2603 }
2604
2605 // Data member.
2606 uint64_t MemberOffsetInBits =
2607 Member->getOffsetInBits() + MemberInfo.BaseOffset;
2608 if (Member->isBitField()) {
2609 uint64_t StartBitOffset = MemberOffsetInBits;
2610 if (const auto *CI =
2611 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
2612 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
2613 }
2614 StartBitOffset -= MemberOffsetInBits;
2615 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2616 StartBitOffset);
2617 MemberBaseType = TypeTable.writeLeafType(BFR);
2618 }
2619 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
2620 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2621 MemberName);
2622 ContinuationBuilder.writeMemberType(DMR);
2623 MemberCount++;
2624 }
2625
2626 // Create methods
2627 for (auto &MethodItr : Info.Methods) {
2628 StringRef Name = MethodItr.first->getString();
2629
2630 std::vector<OneMethodRecord> Methods;
2631 for (const DISubprogram *SP : MethodItr.second) {
2632 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2633 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
2634
2635 unsigned VFTableOffset = -1;
2636 if (Introduced)
2637 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2638
2639 Methods.push_back(OneMethodRecord(
2640 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2641 translateMethodKindFlags(SP, Introduced),
2642 translateMethodOptionFlags(SP), VFTableOffset, Name));
2643 MemberCount++;
2644 }
2645 assert(!Methods.empty() && "Empty methods map entry");
2646 if (Methods.size() == 1)
2647 ContinuationBuilder.writeMemberType(Methods[0]);
2648 else {
2649 // FIXME: Make this use its own ContinuationBuilder so that
2650 // MethodOverloadList can be split correctly.
2651 MethodOverloadListRecord MOLR(Methods);
2652 TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2653
2654 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
2655 ContinuationBuilder.writeMemberType(OMR);
2656 }
2657 }
2658
2659 // Create nested classes.
2660 for (const DIType *Nested : Info.NestedTypes) {
2661 NestedTypeRecord R(getTypeIndex(Nested), Nested->getName());
2662 ContinuationBuilder.writeMemberType(R);
2663 MemberCount++;
2664 }
2665
2666 TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
2667 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
2668 !Info.NestedTypes.empty());
2669}
2670
2671TypeIndex CodeViewDebug::getVBPTypeIndex() {
2672 if (!VBPType.getIndex()) {
2673 // Make a 'const int *' type.
2674 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
2675 TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
2676
2677 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2678 : PointerKind::Near32;
2679 PointerMode PM = PointerMode::Pointer;
2680 PointerOptions PO = PointerOptions::None;
2681 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2682 VBPType = TypeTable.writeLeafType(PR);
2683 }
2684
2685 return VBPType;
2686}
2687
2688TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
2689 // The null DIType is the void type. Don't try to hash it.
2690 if (!Ty)
2691 return TypeIndex::Void();
2692
2693 // Check if we've already translated this type. Don't try to do a
2694 // get-or-create style insertion that caches the hash lookup across the
2695 // lowerType call. It will update the TypeIndices map.
2696 auto I = TypeIndices.find({Ty, ClassTy});
2697 if (I != TypeIndices.end())
2698 return I->second;
2699
2700 TypeLoweringScope S(*this);
2701 TypeIndex TI = lowerType(Ty, ClassTy);
2702 return recordTypeIndexForDINode(Ty, TI, ClassTy);
2703}
2704
2706CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
2707 const DISubroutineType *SubroutineTy) {
2708 assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
2709 "this type must be a pointer type");
2710
2711 PointerOptions Options = PointerOptions::None;
2712 if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
2713 Options = PointerOptions::LValueRefThisPointer;
2714 else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
2715 Options = PointerOptions::RValueRefThisPointer;
2716
2717 // Check if we've already translated this type. If there is no ref qualifier
2718 // on the function then we look up this pointer type with no associated class
2719 // so that the TypeIndex for the this pointer can be shared with the type
2720 // index for other pointers to this class type. If there is a ref qualifier
2721 // then we lookup the pointer using the subroutine as the parent type.
2722 auto I = TypeIndices.find({PtrTy, SubroutineTy});
2723 if (I != TypeIndices.end())
2724 return I->second;
2725
2726 TypeLoweringScope S(*this);
2727 TypeIndex TI = lowerTypePointer(PtrTy, Options);
2728 return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
2729}
2730
2731TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
2732 // The null DIType is the void type. Don't try to hash it.
2733 if (!Ty)
2734 return TypeIndex::Void();
2735
2736 // Look through typedefs when getting the complete type index. Call
2737 // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
2738 // emitted only once.
2739 if (Ty->getTag() == dwarf::DW_TAG_typedef)
2740 (void)getTypeIndex(Ty);
2741 while (Ty->getTag() == dwarf::DW_TAG_typedef)
2742 Ty = cast<DIDerivedType>(Ty)->getBaseType();
2743
2744 // If this is a non-record type, the complete type index is the same as the
2745 // normal type index. Just call getTypeIndex.
2746 switch (Ty->getTag()) {
2747 case dwarf::DW_TAG_class_type:
2748 case dwarf::DW_TAG_structure_type:
2749 case dwarf::DW_TAG_union_type:
2750 break;
2751 default:
2752 return getTypeIndex(Ty);
2753 }
2754
2755 const auto *CTy = cast<DICompositeType>(Ty);
2756
2757 TypeLoweringScope S(*this);
2758
2759 // Make sure the forward declaration is emitted first. It's unclear if this
2760 // is necessary, but MSVC does it, and we should follow suit until we can show
2761 // otherwise.
2762 // We only emit a forward declaration for named types.
2763 if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2764 TypeIndex FwdDeclTI = getTypeIndex(CTy);
2765
2766 // Just use the forward decl if we don't have complete type info. This
2767 // might happen if the frontend is using modules and expects the complete
2768 // definition to be emitted elsewhere.
2769 if (CTy->isForwardDecl())
2770 return FwdDeclTI;
2771 }
2772
2773 // Check if we've already translated the complete record type.
2774 // Insert the type with a null TypeIndex to signify that the type is currently
2775 // being lowered.
2776 auto InsertResult = CompleteTypeIndices.try_emplace(CTy);
2777 if (!InsertResult.second)
2778 return InsertResult.first->second;
2779
2780 TypeIndex TI;
2781 switch (CTy->getTag()) {
2782 case dwarf::DW_TAG_class_type:
2783 case dwarf::DW_TAG_structure_type:
2784 TI = lowerCompleteTypeClass(CTy);
2785 break;
2786 case dwarf::DW_TAG_union_type:
2787 TI = lowerCompleteTypeUnion(CTy);
2788 break;
2789 default:
2790 llvm_unreachable("not a record");
2791 }
2792
2793 // Update the type index associated with this CompositeType. This cannot
2794 // use the 'InsertResult' iterator above because it is potentially
2795 // invalidated by map insertions which can occur while lowering the class
2796 // type above.
2797 CompleteTypeIndices[CTy] = TI;
2798 return TI;
2799}
2800
2801/// Emit all the deferred complete record types. Try to do this in FIFO order,
2802/// and do this until fixpoint, as each complete record type typically
2803/// references
2804/// many other record types.
2805void CodeViewDebug::emitDeferredCompleteTypes() {
2807 while (!DeferredCompleteTypes.empty()) {
2808 std::swap(DeferredCompleteTypes, TypesToEmit);
2809 for (const DICompositeType *RecordTy : TypesToEmit)
2810 getCompleteTypeIndex(RecordTy);
2811 TypesToEmit.clear();
2812 }
2813}
2814
2815void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2816 ArrayRef<LocalVariable> Locals) {
2817 // Get the sorted list of parameters and emit them first.
2819 for (const LocalVariable &L : Locals)
2820 if (L.DIVar->isParameter())
2821 Params.push_back(&L);
2822 llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2823 return L->DIVar->getArg() < R->DIVar->getArg();
2824 });
2825 for (const LocalVariable *L : Params)
2826 emitLocalVariable(FI, *L);
2827
2828 // Next emit all non-parameters in the order that we found them.
2829 for (const LocalVariable &L : Locals) {
2830 if (!L.DIVar->isParameter()) {
2831 if (L.ConstantValue) {
2832 // If ConstantValue is set we will emit it as a S_CONSTANT instead of a
2833 // S_LOCAL in order to be able to represent it at all.
2834 const DIType *Ty = L.DIVar->getType();
2835 APSInt Val(*L.ConstantValue);
2836 emitConstantSymbolRecord(Ty, Val, std::string(L.DIVar->getName()));
2837 } else {
2838 emitLocalVariable(FI, L);
2839 }
2840 }
2841 }
2842}
2843
2844void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2845 const LocalVariable &Var) {
2846 // LocalSym record, see SymbolRecord.h for more info.
2847 MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
2848
2849 LocalSymFlags Flags = LocalSymFlags::None;
2850 if (Var.DIVar->isParameter())
2851 Flags |= LocalSymFlags::IsParameter;
2852 if (Var.DefRanges.empty())
2853 Flags |= LocalSymFlags::IsOptimizedOut;
2854
2855 OS.AddComment("TypeIndex");
2856 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
2857 OS.emitInt32(TI.getIndex());
2858 OS.AddComment("Flags");
2859 OS.emitInt16(static_cast<uint16_t>(Flags));
2860 // Truncate the name so we won't overflow the record length field.
2861 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
2862 endSymbolRecord(LocalEnd);
2863
2864 // Calculate the on disk prefix of the appropriate def range record. The
2865 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2866 // should be big enough to hold all forms without memory allocation.
2867 SmallString<20> BytePrefix;
2868 for (const auto &Pair : Var.DefRanges) {
2869 LocalVarDef DefRange = Pair.first;
2870 const auto &Ranges = Pair.second;
2871 BytePrefix.clear();
2872 if (DefRange.InMemory) {
2873 int Offset = DefRange.DataOffset;
2874 unsigned Reg = DefRange.CVRegister;
2875
2876 // 32-bit x86 call sequences often use PUSH instructions, which disrupt
2877 // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
2878 // instead. In frames without stack realignment, $T0 will be the CFA.
2879 if (RegisterId(Reg) == RegisterId::ESP) {
2880 Reg = unsigned(RegisterId::VFRAME);
2881 Offset += FI.OffsetAdjustment;
2882 }
2883
2885
2886 if (DefRange.DerefOffset != LocalVarDef::NoDeref) {
2887 uint16_t RegRelFlags = 0;
2888 if (DefRange.IsSubfield) {
2890 (DefRange.StructOffset
2892 }
2893 DefRangeRegisterRelIndirHeader DRHdr;
2894 DRHdr.Register = Reg;
2895 DRHdr.Flags = RegRelFlags;
2896 DRHdr.BasePointerOffset = Offset;
2897 DRHdr.OffsetInUdt = DefRange.DerefOffset;
2898 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2899 } else if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2900 (bool(Flags & LocalSymFlags::IsParameter)
2901 ? (EncFP == FI.EncodedParamFramePtrReg)
2902 : (EncFP == FI.EncodedLocalFramePtrReg))) {
2903 // If we can use the chosen frame pointer for the frame and this isn't a
2904 // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2905 // Otherwise, use S_DEFRANGE_REGISTER_REL.
2906 DefRangeFramePointerRelHeader DRHdr;
2907 DRHdr.Offset = Offset;
2908 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2909 } else {
2910 uint16_t RegRelFlags = 0;
2911 if (DefRange.IsSubfield) {
2913 (DefRange.StructOffset
2915 }
2916 DefRangeRegisterRelHeader DRHdr;
2917 DRHdr.Register = Reg;
2918 DRHdr.Flags = RegRelFlags;
2919 DRHdr.BasePointerOffset = Offset;
2920 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2921 }
2922 } else {
2923 assert(DefRange.DataOffset == 0 &&
2924 DefRange.DerefOffset == LocalVarDef::NoDeref &&
2925 "unexpected offset into register");
2926 if (DefRange.IsSubfield) {
2927 DefRangeSubfieldRegisterHeader DRHdr;
2928 DRHdr.Register = DefRange.CVRegister;
2929 DRHdr.MayHaveNoName = 0;
2930 DRHdr.OffsetInParent = DefRange.StructOffset;
2931 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2932 } else {
2933 DefRangeRegisterHeader DRHdr;
2934 DRHdr.Register = DefRange.CVRegister;
2935 DRHdr.MayHaveNoName = 0;
2936 OS.emitCVDefRangeDirective(Ranges, DRHdr);
2937 }
2938 }
2939 }
2940}
2941
2942void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2943 const FunctionInfo& FI) {
2944 for (LexicalBlock *Block : Blocks)
2945 emitLexicalBlock(*Block, FI);
2946}
2947
2948/// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2949/// lexical block scope.
2950void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2951 const FunctionInfo& FI) {
2952 MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
2953 OS.AddComment("PtrParent");
2954 OS.emitInt32(0); // PtrParent
2955 OS.AddComment("PtrEnd");
2956 OS.emitInt32(0); // PtrEnd
2957 OS.AddComment("Code size");
2958 OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size
2959 OS.AddComment("Function section relative address");
2960 OS.emitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset
2961 OS.AddComment("Function section index");
2962 OS.emitCOFFSectionIndex(FI.Begin); // Func Symbol
2963 OS.AddComment("Lexical block name");
2964 emitNullTerminatedSymbolName(OS, Block.Name); // Name
2965 endSymbolRecord(RecordEnd);
2966
2967 // Emit variables local to this lexical block.
2968 emitLocalVariableList(FI, Block.Locals);
2969 emitGlobalVariableList(Block.Globals);
2970
2971 // Emit lexical blocks contained within this block.
2972 emitLexicalBlockList(Block.Children, FI);
2973
2974 // Close the lexical block scope.
2975 emitEndSymbolRecord(SymbolKind::S_END);
2976}
2977
2978/// Convenience routine for collecting lexical block information for a list
2979/// of lexical scopes.
2980void CodeViewDebug::collectLexicalBlockInfo(
2985 for (LexicalScope *Scope : Scopes)
2986 collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
2987}
2988
2989/// Populate the lexical blocks and local variable lists of the parent with
2990/// information about the specified lexical scope.
2991void CodeViewDebug::collectLexicalBlockInfo(
2992 LexicalScope &Scope,
2993 SmallVectorImpl<LexicalBlock *> &ParentBlocks,
2994 SmallVectorImpl<LocalVariable> &ParentLocals,
2995 SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
2996 if (Scope.isAbstractScope())
2997 return;
2998
2999 // Gather information about the lexical scope including local variables,
3000 // global variables, and address ranges.
3001 bool IgnoreScope = false;
3002 auto LI = ScopeVariables.find(&Scope);
3003 SmallVectorImpl<LocalVariable> *Locals =
3004 LI != ScopeVariables.end() ? &LI->second : nullptr;
3005 auto GI = ScopeGlobals.find(Scope.getScopeNode());
3006 SmallVectorImpl<CVGlobalVariable> *Globals =
3007 GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
3008 const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
3009 const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
3010
3011 // Ignore lexical scopes which do not contain variables.
3012 if (!Locals && !Globals)
3013 IgnoreScope = true;
3014
3015 // Ignore lexical scopes which are not lexical blocks.
3016 if (!DILB)
3017 IgnoreScope = true;
3018
3019 // Ignore scopes which have too many address ranges to represent in the
3020 // current CodeView format or do not have a valid address range.
3021 //
3022 // For lexical scopes with multiple address ranges you may be tempted to
3023 // construct a single range covering every instruction where the block is
3024 // live and everything in between. Unfortunately, Visual Studio only
3025 // displays variables from the first matching lexical block scope. If the
3026 // first lexical block contains exception handling code or cold code which
3027 // is moved to the bottom of the routine creating a single range covering
3028 // nearly the entire routine, then it will hide all other lexical blocks
3029 // and the variables they contain.
3030 if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
3031 IgnoreScope = true;
3032
3033 if (IgnoreScope) {
3034 // This scope can be safely ignored and eliminating it will reduce the
3035 // size of the debug information. Be sure to collect any variable and scope
3036 // information from the this scope or any of its children and collapse them
3037 // into the parent scope.
3038 if (Locals)
3039 ParentLocals.append(Locals->begin(), Locals->end());
3040 if (Globals)
3041 ParentGlobals.append(Globals->begin(), Globals->end());
3042 collectLexicalBlockInfo(Scope.getChildren(),
3043 ParentBlocks,
3044 ParentLocals,
3045 ParentGlobals);
3046 return;
3047 }
3048
3049 // Create a new CodeView lexical block for this lexical scope. If we've
3050 // seen this DILexicalBlock before then the scope tree is malformed and
3051 // we can handle this gracefully by not processing it a second time.
3052 auto BlockInsertion = CurFn->LexicalBlocks.try_emplace(DILB);
3053 if (!BlockInsertion.second)
3054 return;
3055
3056 // Create a lexical block containing the variables and collect the
3057 // lexical block information for the children.
3058 const InsnRange &Range = Ranges.front();
3059 assert(Range.first && Range.second);
3060 LexicalBlock &Block = BlockInsertion.first->second;
3061 Block.Begin = getLabelBeforeInsn(Range.first);
3062 Block.End = getLabelAfterInsn(Range.second);
3063 assert(Block.Begin && "missing label for scope begin");
3064 assert(Block.End && "missing label for scope end");
3065 Block.Name = DILB->getName();
3066 if (Locals)
3067 Block.Locals = std::move(*Locals);
3068 if (Globals)
3069 Block.Globals = std::move(*Globals);
3070 ParentBlocks.push_back(&Block);
3071 collectLexicalBlockInfo(Scope.getChildren(),
3072 Block.Children,
3073 Block.Locals,
3074 Block.Globals);
3075}
3076
3078 const Function &GV = MF->getFunction();
3079 assert(FnDebugInfo.count(&GV));
3080 assert(CurFn == FnDebugInfo[&GV].get());
3081
3082 collectVariableInfo(GV.getSubprogram());
3083
3084 // Build the lexical block structure to emit for this routine.
3085 if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
3086 collectLexicalBlockInfo(*CFS,
3087 CurFn->ChildBlocks,
3088 CurFn->Locals,
3089 CurFn->Globals);
3090
3091 // Clear the scope and variable information from the map which will not be
3092 // valid after we have finished processing this routine. This also prepares
3093 // the map for the subsequent routine.
3094 ScopeVariables.clear();
3095
3096 // Don't emit anything if we don't have any line tables.
3097 // Thunks are compiler-generated and probably won't have source correlation.
3098 if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
3099 FnDebugInfo.erase(&GV);
3100 CurFn = nullptr;
3101 return;
3102 }
3103
3104 // Find heap alloc sites and add to list.
3105 for (const auto &MBB : *MF) {
3106 for (const auto &MI : MBB) {
3107 if (MDNode *MD = MI.getHeapAllocMarker()) {
3108 CurFn->HeapAllocSites.push_back(std::make_tuple(getLabelBeforeInsn(&MI),
3110 dyn_cast<DIType>(MD)));
3111 }
3112 }
3113 }
3114
3115 bool isThumb = MMI->getModule()->getTargetTriple().getArch() ==
3117 collectDebugInfoForJumpTables(MF, isThumb);
3118
3119 CurFn->Annotations = MF->getCodeViewAnnotations();
3120
3121 CurFn->End = Asm->getFunctionEnd();
3122
3123 CurFn = nullptr;
3124}
3125
3126// Usable locations are valid with non-zero line numbers. A line number of zero
3127// corresponds to optimized code that doesn't have a distinct source location.
3128// In this case, we try to use the previous or next source location depending on
3129// the context.
3131 return DL && DL.getLine() != 0;
3132}
3133
3136
3137 // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
3138 if (!Asm || !CurFn || MI->isDebugInstr() ||
3139 MI->getFlag(MachineInstr::FrameSetup))
3140 return;
3141
3142 // If the first instruction of a new MBB has no location, find the first
3143 // instruction with a location and use that.
3144 DebugLoc DL = MI->getDebugLoc();
3145 if (!isUsableDebugLoc(DL) && MI->getParent() != PrevInstBB) {
3146 for (const auto &NextMI : *MI->getParent()) {
3147 if (NextMI.isDebugInstr())
3148 continue;
3149 DL = NextMI.getDebugLoc();
3150 if (isUsableDebugLoc(DL))
3151 break;
3152 }
3153 // FIXME: Handle the case where the BB has no valid locations. This would
3154 // probably require doing a real dataflow analysis.
3155 }
3156 PrevInstBB = MI->getParent();
3157
3158 // If we still don't have a debug location, don't record a location.
3159 if (!isUsableDebugLoc(DL))
3160 return;
3161
3162 maybeRecordLocation(DL, Asm->MF);
3163}
3164
3165MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
3166 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
3167 *EndLabel = MMI->getContext().createTempSymbol();
3168 OS.emitInt32(unsigned(Kind));
3169 OS.AddComment("Subsection size");
3170 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
3171 OS.emitLabel(BeginLabel);
3172 return EndLabel;
3173}
3174
3175void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
3176 OS.emitLabel(EndLabel);
3177 // Every subsection must be aligned to a 4-byte boundary.
3179}
3180
3182 for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
3183 if (EE.Value == SymKind)
3184 return EE.Name;
3185 return "";
3186}
3187
3188MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
3189 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
3190 *EndLabel = MMI->getContext().createTempSymbol();
3191 OS.AddComment("Record length");
3192 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
3193 OS.emitLabel(BeginLabel);
3194 if (OS.isVerboseAsm())
3195 OS.AddComment("Record kind: " + getSymbolName(SymKind));
3196 OS.emitInt16(unsigned(SymKind));
3197 return EndLabel;
3198}
3199
3200void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
3201 // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
3202 // an extra copy of every symbol record in LLD. This increases object file
3203 // size by less than 1% in the clang build, and is compatible with the Visual
3204 // C++ linker.
3205 OS.emitValueToAlignment(Align(4));
3206 OS.emitLabel(SymEnd);
3207}
3208
3209void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
3210 OS.AddComment("Record length");
3211 OS.emitInt16(2);
3212 if (OS.isVerboseAsm())
3213 OS.AddComment("Record kind: " + getSymbolName(EndKind));
3214 OS.emitInt16(uint16_t(EndKind)); // Record Kind
3215}
3216
3217void CodeViewDebug::emitDebugInfoForUDTs(
3218 const std::vector<std::pair<std::string, const DIType *>> &UDTs) {
3219#ifndef NDEBUG
3220 size_t OriginalSize = UDTs.size();
3221#endif
3222 for (const auto &UDT : UDTs) {
3223 const DIType *T = UDT.second;
3225 MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
3226 OS.AddComment("Type");
3227 OS.emitInt32(getCompleteTypeIndex(T).getIndex());
3228 assert(OriginalSize == UDTs.size() &&
3229 "getCompleteTypeIndex found new UDTs!");
3231 endSymbolRecord(UDTRecordEnd);
3232 }
3233}
3234
3235void CodeViewDebug::collectGlobalVariableInfo() {
3236 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
3237 GlobalMap;
3238 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
3240 GV.getDebugInfo(GVEs);
3241 for (const auto *GVE : GVEs)
3242 GlobalMap[GVE] = &GV;
3243 }
3244
3245 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3246 for (const MDNode *Node : CUs->operands()) {
3247 const auto *CU = cast<DICompileUnit>(Node);
3248 for (const auto *GVE : CU->getGlobalVariables()) {
3249 const DIGlobalVariable *DIGV = GVE->getVariable();
3250 const DIExpression *DIE = GVE->getExpression();
3251 // Don't emit string literals in CodeView, as the only useful parts are
3252 // generally the filename and line number, which isn't possible to output
3253 // in CodeView. String literals should be the only unnamed GlobalVariable
3254 // with debug info.
3255 if (DIGV->getName().empty()) continue;
3256
3257 if ((DIE->getNumElements() == 2) &&
3258 (DIE->getElement(0) == dwarf::DW_OP_plus_uconst))
3259 // Record the constant offset for the variable.
3260 //
3261 // A Fortran common block uses this idiom to encode the offset
3262 // of a variable from the common block's starting address.
3263 CVGlobalVariableOffsets.insert(
3264 std::make_pair(DIGV, DIE->getElement(1)));
3265
3266 // Emit constant global variables in a global symbol section.
3267 if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) {
3268 CVGlobalVariable CVGV = {DIGV, DIE};
3269 GlobalVariables.emplace_back(std::move(CVGV));
3270 }
3271
3272 const auto *GV = GlobalMap.lookup(GVE);
3273 if (!GV || GV->isDeclarationForLinker())
3274 continue;
3275
3276 DIScope *Scope = DIGV->getScope();
3277 SmallVector<CVGlobalVariable, 1> *VariableList;
3278 if (Scope && isa<DILocalScope>(Scope)) {
3279 // Locate a global variable list for this scope, creating one if
3280 // necessary.
3281 auto Insertion = ScopeGlobals.insert(
3282 {Scope, std::unique_ptr<GlobalVariableList>()});
3283 if (Insertion.second)
3284 Insertion.first->second = std::make_unique<GlobalVariableList>();
3285 VariableList = Insertion.first->second.get();
3286 } else if (GV->hasComdat())
3287 // Emit this global variable into a COMDAT section.
3288 VariableList = &ComdatVariables;
3289 else
3290 // Emit this global variable in a single global symbol section.
3291 VariableList = &GlobalVariables;
3292 CVGlobalVariable CVGV = {DIGV, GV};
3293 VariableList->emplace_back(std::move(CVGV));
3294 }
3295 }
3296}
3297
3298void CodeViewDebug::collectDebugInfoForGlobals() {
3299 for (const CVGlobalVariable &CVGV : GlobalVariables) {
3300 const DIGlobalVariable *DIGV = CVGV.DIGV;
3301 const DIScope *Scope = DIGV->getScope();
3302 getCompleteTypeIndex(DIGV->getType());
3303 getFullyQualifiedName(Scope, DIGV->getName());
3304 }
3305
3306 for (const CVGlobalVariable &CVGV : ComdatVariables) {
3307 const DIGlobalVariable *DIGV = CVGV.DIGV;
3308 const DIScope *Scope = DIGV->getScope();
3309 getCompleteTypeIndex(DIGV->getType());
3310 getFullyQualifiedName(Scope, DIGV->getName());
3311 }
3312}
3313
3314void CodeViewDebug::emitDebugInfoForGlobals() {
3315 // First, emit all globals that are not in a comdat in a single symbol
3316 // substream. MSVC doesn't like it if the substream is empty, so only open
3317 // it if we have at least one global to emit.
3318 switchToDebugSectionForSymbol(nullptr);
3319 if (!GlobalVariables.empty() || !StaticConstMembers.empty()) {
3320 OS.AddComment("Symbol subsection for globals");
3321 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3322 emitGlobalVariableList(GlobalVariables);
3323 emitStaticConstMemberList();
3324 endCVSubsection(EndLabel);
3325 }
3326
3327 // Second, emit each global that is in a comdat into its own .debug$S
3328 // section along with its own symbol substream.
3329 for (const CVGlobalVariable &CVGV : ComdatVariables) {
3330 const GlobalVariable *GV = cast<const GlobalVariable *>(CVGV.GVInfo);
3331 MCSymbol *GVSym = Asm->getSymbol(GV);
3332 OS.AddComment("Symbol subsection for " +
3334 switchToDebugSectionForSymbol(GVSym);
3335 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3336 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3337 emitDebugInfoForGlobal(CVGV);
3338 endCVSubsection(EndLabel);
3339 }
3340}
3341
3342void CodeViewDebug::emitDebugInfoForRetainedTypes() {
3343 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3344 for (const MDNode *Node : CUs->operands()) {
3345 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
3346 if (DIType *RT = dyn_cast<DIType>(Ty)) {
3347 getTypeIndex(RT);
3348 // FIXME: Add to global/local DTU list.
3349 }
3350 }
3351 }
3352}
3353
3354// Emit each global variable in the specified array.
3355void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
3356 for (const CVGlobalVariable &CVGV : Globals) {
3357 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3358 emitDebugInfoForGlobal(CVGV);
3359 }
3360}
3361
3362void CodeViewDebug::emitConstantSymbolRecord(const DIType *DTy, APSInt &Value,
3363 const std::string &QualifiedName) {
3364 MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
3365 OS.AddComment("Type");
3366 OS.emitInt32(getTypeIndex(DTy).getIndex());
3367
3368 OS.AddComment("Value");
3369
3370 // Encoded integers shouldn't need more than 10 bytes.
3371 uint8_t Data[10];
3372 BinaryStreamWriter Writer(Data, llvm::endianness::little);
3373 CodeViewRecordIO IO(Writer);
3374 cantFail(IO.mapEncodedInteger(Value));
3375 StringRef SRef((char *)Data, Writer.getOffset());
3376 OS.emitBinaryData(SRef);
3377
3378 OS.AddComment("Name");
3379 emitNullTerminatedSymbolName(OS, QualifiedName);
3380 endSymbolRecord(SConstantEnd);
3381}
3382
3383void CodeViewDebug::emitStaticConstMemberList() {
3384 for (const DIDerivedType *DTy : StaticConstMembers) {
3385 const DIScope *Scope = DTy->getScope();
3386
3387 APSInt Value;
3388 if (const ConstantInt *CI =
3389 dyn_cast_or_null<ConstantInt>(DTy->getConstant()))
3390 Value = APSInt(CI->getValue(),
3391 DebugHandlerBase::isUnsignedDIType(DTy->getBaseType()));
3392 else if (const ConstantFP *CFP =
3393 dyn_cast_or_null<ConstantFP>(DTy->getConstant()))
3394 Value = APSInt(CFP->getValueAPF().bitcastToAPInt(), true);
3395 else
3396 llvm_unreachable("cannot emit a constant without a value");
3397
3398 emitConstantSymbolRecord(DTy->getBaseType(), Value,
3399 getFullyQualifiedName(Scope, DTy->getName()));
3400 }
3401}
3402
3403static bool isFloatDIType(const DIType *Ty) {
3404 if (isa<DICompositeType>(Ty))
3405 return false;
3406
3407 if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
3408 dwarf::Tag T = (dwarf::Tag)Ty->getTag();
3409 if (T == dwarf::DW_TAG_pointer_type ||
3410 T == dwarf::DW_TAG_ptr_to_member_type ||
3411 T == dwarf::DW_TAG_reference_type ||
3412 T == dwarf::DW_TAG_rvalue_reference_type)
3413 return false;
3414 assert(DTy->getBaseType() && "Expected valid base type");
3415 return isFloatDIType(DTy->getBaseType());
3416 }
3417
3418 auto *BTy = cast<DIBasicType>(Ty);
3419 return (BTy->getEncoding() == dwarf::DW_ATE_float);
3420}
3421
3422void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
3423 const DIGlobalVariable *DIGV = CVGV.DIGV;
3424
3425 const DIScope *Scope = DIGV->getScope();
3426 // For static data members, get the scope from the declaration.
3427 if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
3429 Scope = MemberDecl->getScope();
3430 // For static local variables and Fortran, the scoping portion is elided
3431 // in its name so that we can reference the variable in the command line
3432 // of the VS debugger.
3433 std::string QualifiedName =
3434 (moduleIsInFortran() || (Scope && isa<DILocalScope>(Scope)))
3435 ? std::string(DIGV->getName())
3436 : getFullyQualifiedName(Scope, DIGV->getName());
3437
3438 if (const GlobalVariable *GV =
3440 // DataSym record, see SymbolRecord.h for more info. Thread local data
3441 // happens to have the same format as global data.
3442 MCSymbol *GVSym = Asm->getSymbol(GV);
3443 SymbolKind DataSym = GV->isThreadLocal()
3444 ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
3445 : SymbolKind::S_GTHREAD32)
3446 : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
3447 : SymbolKind::S_GDATA32);
3448 MCSymbol *DataEnd = beginSymbolRecord(DataSym);
3449 OS.AddComment("Type");
3450 OS.emitInt32(getCompleteTypeIndex(DIGV->getType()).getIndex());
3451 OS.AddComment("DataOffset");
3452
3453 // Use the offset seen while collecting info on globals.
3454 uint64_t Offset = CVGlobalVariableOffsets.lookup(DIGV);
3455 OS.emitCOFFSecRel32(GVSym, Offset);
3456
3457 OS.AddComment("Segment");
3458 OS.emitCOFFSectionIndex(GVSym);
3459 OS.AddComment("Name");
3460 const unsigned LengthOfDataRecord = 12;
3461 emitNullTerminatedSymbolName(OS, QualifiedName, LengthOfDataRecord);
3462 endSymbolRecord(DataEnd);
3463 } else {
3464 const DIExpression *DIE = cast<const DIExpression *>(CVGV.GVInfo);
3465 assert(DIE->isConstant() &&
3466 "Global constant variables must contain a constant expression.");
3467
3468 // Use unsigned for floats.
3469 bool isUnsigned = isFloatDIType(DIGV->getType())
3470 ? true
3471 : DebugHandlerBase::isUnsignedDIType(DIGV->getType());
3472 APSInt Value(APInt(/*BitWidth=*/64, DIE->getElement(1)), isUnsigned);
3473 emitConstantSymbolRecord(DIGV->getType(), Value, QualifiedName);
3474 }
3475}
3476
3478 const MachineFunction *MF, bool isThumb,
3479 const std::function<void(const MachineJumpTableInfo &, const MachineInstr &,
3480 int64_t)> &Callback) {
3481 auto JTI = MF->getJumpTableInfo();
3482 if (JTI && !JTI->isEmpty()) {
3483#ifndef NDEBUG
3484 auto UsedJTs = llvm::SmallBitVector(JTI->getJumpTables().size());
3485#endif
3486 for (const auto &MBB : *MF) {
3487 // Search for indirect branches...
3488 const auto LastMI = MBB.getFirstTerminator();
3489 if (LastMI != MBB.end() && LastMI->isIndirectBranch()) {
3490 if (isThumb) {
3491 // ... that directly use jump table operands.
3492 // NOTE: ARM uses pattern matching to lower its BR_JT SDNode to
3493 // machine instructions, hence inserting a JUMP_TABLE_DEBUG_INFO node
3494 // interferes with this process *but* the resulting pseudo-instruction
3495 // uses a Jump Table operand, so extract the jump table index directly
3496 // from that.
3497 for (const auto &MO : LastMI->operands()) {
3498 if (MO.isJTI()) {
3499 unsigned Index = MO.getIndex();
3500#ifndef NDEBUG
3501 UsedJTs.set(Index);
3502#endif
3503 Callback(*JTI, *LastMI, Index);
3504 break;
3505 }
3506 }
3507 } else {
3508 // ... that have jump table debug info.
3509 // NOTE: The debug info is inserted as a JUMP_TABLE_DEBUG_INFO node
3510 // when lowering the BR_JT SDNode to an indirect branch.
3511 for (auto I = MBB.instr_rbegin(), E = MBB.instr_rend(); I != E; ++I) {
3512 if (I->isJumpTableDebugInfo()) {
3513 unsigned Index = I->getOperand(0).getImm();
3514#ifndef NDEBUG
3515 UsedJTs.set(Index);
3516#endif
3517 Callback(*JTI, *LastMI, Index);
3518 break;
3519 }
3520 }
3521 }
3522 }
3523 }
3524#ifndef NDEBUG
3525 assert(UsedJTs.all() &&
3526 "Some of jump tables were not used in a debug info instruction");
3527#endif
3528 }
3529}
3530
3531void CodeViewDebug::discoverJumpTableBranches(const MachineFunction *MF,
3532 bool isThumb) {
3534 MF, isThumb,
3535 [this](const MachineJumpTableInfo &, const MachineInstr &BranchMI,
3536 int64_t) { requestLabelBeforeInsn(&BranchMI); });
3537}
3538
3539void CodeViewDebug::collectDebugInfoForJumpTables(const MachineFunction *MF,
3540 bool isThumb) {
3542 MF, isThumb,
3543 [this, MF](const MachineJumpTableInfo &JTI, const MachineInstr &BranchMI,
3544 int64_t JumpTableIndex) {
3545 // For label-difference jump tables, find the base expression.
3546 // Otherwise the jump table uses an absolute address (so no base
3547 // is required).
3548 const MCSymbol *Base;
3549 uint64_t BaseOffset = 0;
3550 const MCSymbol *Branch = getLabelBeforeInsn(&BranchMI);
3551 JumpTableEntrySize EntrySize;
3552 switch (JTI.getEntryKind()) {
3557 "EK_Custom32, EK_GPRel32BlockAddress, and "
3558 "EK_GPRel64BlockAddress should never be emitted for COFF");
3560 // Each entry is an absolute address.
3561 EntrySize = JumpTableEntrySize::Pointer;
3562 Base = nullptr;
3563 break;
3567 // Ask the AsmPrinter.
3568 std::tie(Base, BaseOffset, Branch, EntrySize) =
3569 Asm->getCodeViewJumpTableInfo(JumpTableIndex, &BranchMI, Branch);
3570 break;
3571 }
3572
3573 const MachineJumpTableEntry &JTE = JTI.getJumpTables()[JumpTableIndex];
3574 JumpTableInfo CVJTI{EntrySize,
3575 Base,
3576 BaseOffset,
3577 Branch,
3578 MF->getJTISymbol(JumpTableIndex, MMI->getContext()),
3579 JTE.MBBs.size(),
3580 {}};
3581 for (const auto &MBB : JTE.MBBs)
3582 CVJTI.Cases.push_back(MBB->getSymbol());
3583 CurFn->JumpTables.push_back(std::move(CVJTI));
3584 });
3585}
3586
3587void CodeViewDebug::emitDebugInfoForJumpTables(const FunctionInfo &FI) {
3588 // Emit S_LABEL32 records for each jump target
3589 for (const auto &JumpTable : FI.JumpTables) {
3590 for (const auto &CaseSym : JumpTable.Cases) {
3591 MCSymbol *LabelEnd = beginSymbolRecord(SymbolKind::S_LABEL32);
3592 OS.AddComment("Offset and segment");
3593 OS.emitCOFFSecRel32(CaseSym, 0);
3594 OS.AddComment("Flags");
3595 OS.emitInt8(0);
3596 emitNullTerminatedSymbolName(OS, CaseSym->getName());
3597 endSymbolRecord(LabelEnd);
3598 }
3599 }
3600
3601 for (const auto &JumpTable : FI.JumpTables) {
3602 MCSymbol *JumpTableEnd = beginSymbolRecord(SymbolKind::S_ARMSWITCHTABLE);
3603 if (JumpTable.Base) {
3604 OS.AddComment("Base offset");
3605 OS.emitCOFFSecRel32(JumpTable.Base, JumpTable.BaseOffset);
3606 OS.AddComment("Base section index");
3607 OS.emitCOFFSectionIndex(JumpTable.Base);
3608 } else {
3609 OS.AddComment("Base offset");
3610 OS.emitInt32(0);
3611 OS.AddComment("Base section index");
3612 OS.emitInt16(0);
3613 }
3614 OS.AddComment("Switch type");
3615 OS.emitInt16(static_cast<uint16_t>(JumpTable.EntrySize));
3616 OS.AddComment("Branch offset");
3617 OS.emitCOFFSecRel32(JumpTable.Branch, /*Offset=*/0);
3618 OS.AddComment("Table offset");
3619 OS.emitCOFFSecRel32(JumpTable.Table, /*Offset=*/0);
3620 OS.AddComment("Branch section index");
3621 OS.emitCOFFSectionIndex(JumpTable.Branch);
3622 OS.AddComment("Table section index");
3623 OS.emitCOFFSectionIndex(JumpTable.Table);
3624 OS.AddComment("Entries count");
3625 OS.emitInt32(JumpTable.TableSize);
3626 endSymbolRecord(JumpTableEnd);
3627 }
3628}
3629
3630void CodeViewDebug::emitInlinees(
3631 const SmallSet<codeview::TypeIndex, 1> &Inlinees) {
3632 // Divide the list of inlinees into chunks such that each chunk fits within
3633 // one record.
3634 constexpr size_t ChunkSize =
3635 (MaxRecordLength - sizeof(SymbolKind) - sizeof(uint32_t)) /
3636 sizeof(uint32_t);
3637
3638 SmallVector<TypeIndex> SortedInlinees{Inlinees.begin(), Inlinees.end()};
3639 llvm::sort(SortedInlinees);
3640
3641 size_t CurrentIndex = 0;
3642 while (CurrentIndex < SortedInlinees.size()) {
3643 auto Symbol = beginSymbolRecord(SymbolKind::S_INLINEES);
3644 auto CurrentChunkSize =
3645 std::min(ChunkSize, SortedInlinees.size() - CurrentIndex);
3646 OS.AddComment("Count");
3647 OS.emitInt32(CurrentChunkSize);
3648
3649 const size_t CurrentChunkEnd = CurrentIndex + CurrentChunkSize;
3650 for (; CurrentIndex < CurrentChunkEnd; ++CurrentIndex) {
3651 OS.AddComment("Inlinee");
3652 OS.emitInt32(SortedInlinees[CurrentIndex].getIndex());
3653 }
3654 endSymbolRecord(Symbol);
3655 }
3656}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
static bool isThumb(const MCSubtargetInfo &STI)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static MethodKind translateMethodKindFlags(const DISubprogram *SP, bool Introduced)
static bool isUsableDebugLoc(DebugLoc DL)
static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable, StringRef S)
static CPUType mapArchToCVCPUType(Triple::ArchType Type)
static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S, unsigned MaxFixedRecordLength=0xF00)
static Version parseVersion(StringRef Name)
static MethodOptions translateMethodOptionFlags(const DISubprogram *SP)
static bool isNonTrivial(const DICompositeType *DCTy)
static std::string formatNestedName(ArrayRef< StringRef > QualifiedNameComponents, StringRef TypeName)
static ClassOptions getCommonClassOptions(const DICompositeType *Ty)
Return ClassOptions that should be present on both the forward declaration and the defintion of a tag...
static PointerToMemberRepresentation translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags)
static FunctionOptions getFunctionOptions(const DISubroutineType *Ty, const DICompositeType *ClassTy=nullptr, StringRef SPName=StringRef(""))
static StringRef removeTemplateArgs(StringRef Name)
static TypeRecordKind getRecordKind(const DICompositeType *Ty)
void forEachJumpTableBranch(const MachineFunction *MF, bool isThumb, const std::function< void(const MachineJumpTableInfo &, const MachineInstr &, int64_t)> &Callback)
static CallingConvention dwarfCCToCodeView(unsigned DwarfCC)
Given a DWARF calling convention, get the CodeView equivalent.
static SourceLanguage MapDWARFLanguageToCVLang(dwarf::SourceLanguageName DWLName)
static bool isFloatDIType(const DIType *Ty)
static void addLocIfNotPresent(SmallVectorImpl< const DILocation * > &Locs, const DILocation *Loc)
static bool shouldEmitUdt(const DIType *T)
static StringRef getPrettyScopeName(const DIScope *Scope)
static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty)
static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Resource Access
dxil translate DXIL Translate Metadata
This file contains constants used for implementing Dwarf debug support.
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file contains the declarations for metadata subclasses.
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
static constexpr StringLiteral Filename
#define P(N)
static StringRef getName(Value *V)
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file contains some templates that are useful if you are working with the STL at all.
This file implements the SmallBitVector class.
This file defines the SmallString class.
This file describes how to lower LLVM code to machine code.
static const uint32_t IV[8]
Definition blake3_impl.h:83
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:91
CodeViewDebug(AsmPrinter *AP)
void beginModule(Module *M) override
bool moduleIsInFortran()
Check if the current module is in Fortran.
void endFunctionImpl(const MachineFunction *) override
Gather post-function debug information.
void endModule() override
Emit the COFF section that holds the line table information.
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
void beginFunctionImpl(const MachineFunction *MF) override
Gather pre-function debug information.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
Basic type, like 'int' or 'float'.
unsigned getEncoding() const
StringRef getIdentifier() const
DINodeArray getElements() const
DIType * getBaseType() const
LLVM_ABI DIType * getClassType() const
Get casted version of extra data.
LLVM_ABI Constant * getConstant() const
unsigned getNumElements() const
uint64_t getElement(unsigned I) const
static LLVM_ABI bool extractLeadingOffset(ArrayRef< uint64_t > Ops, int64_t &OffsetInBytes, SmallVectorImpl< uint64_t > &RemainingOps)
LLVM_ABI std::optional< SignedOrUnsignedConstant > isConstant() const
Determine whether this represents a constant value, if so.
Metadata * getRawStaticDataMemberDeclaration() const
DILocalScope * getScope() const
Get the local scope for this variable.
Tagged DWARF-like metadata node.
LLVM_ABI dwarf::Tag getTag() const
Base class for scope-like contexts.
StringRef getFilename() const
LLVM_ABI StringRef getName() const
DIFile * getFile() const
StringRef getDirectory() const
LLVM_ABI DIScope * getScope() const
Wrapper structure that holds a language name and its version.
uint16_t getName() const
Returns a versioned or unversioned language name.
String type, Fortran CHARACTER(n)
Subprogram description. Uses SubclassData1.
Type array for a subprogram.
DITypeArray getTypeArray() const
Base class for types.
uint64_t getOffsetInBits() const
bool isObjectPointer() const
DIFlags getFlags() const
StringRef getName() const
bool isForwardDecl() const
uint64_t getSizeInBits() const
unsigned getLine() const
DIScope * getScope() const
DIScope * getScope() const
DIType * getType() const
StringRef getName() const
static const EntryIndex NoEntry
Special value to indicate that an entry is valid until the end of the function.
static bool isUnsignedDIType(const DIType *Ty)
Return true if type encoding is unsigned.
AsmPrinter * Asm
Target of debug info emission.
MCSymbol * getLabelBeforeInsn(const MachineInstr *MI)
Return Label preceding the instruction.
MachineModuleInfo * MMI
Collected machine module information.
DebugLoc PrevInstLoc
Previous instruction's location information.
MCSymbol * getLabelAfterInsn(const MachineInstr *MI)
Return Label immediately following the instruction.
void beginInstruction(const MachineInstr *MI) override
Process beginning of an instruction.
const MachineBasicBlock * PrevInstBB
void requestLabelAfterInsn(const MachineInstr *MI)
Ensure that a label will be emitted after MI.
DbgValueHistoryMap DbgValues
History of DBG_VALUE and clobber instructions for each user variable.
void requestLabelBeforeInsn(const MachineInstr *MI)
Ensure that a label will be emitted before MI.
const MachineInstr * PrologEndLoc
This location indicates end of function prologue and beginning of function body.
static uint64_t getBaseTypeSize(const DIType *Ty)
If this type is derived from a base type then return base type size.
A debug info location.
Definition DebugLoc.h:123
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:205
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:174
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:714
bool hasStackProtectorFnAttr() const
Returns true if the function has ssp, sspstrong, or sspreq fn attrs.
Definition Function.cpp:835
DISubprogram * getSubprogram() const
Get the attached subprogram.
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition Function.h:905
Constant * getPersonalityFn() const
Get the personality function associated with this function.
bool hasProfileData(bool IncludeSynthetic=false) const
Return true if the function is annotated with profile data.
Definition Function.h:336
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:708
Function::iterator insert(Function::iterator Position, BasicBlock *BB)
Insert BB in the basic block list at Position.
Definition Function.h:755
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:728
bool hasComdat() const
bool hasLocalLinkage() const
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
bool isDeclarationForLinker() const
This class is used to track scope information.
LLVM_ABI MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
MCSymbol * getCOMDATSymbol() const
Streaming machine code generation interface.
Definition MCStreamer.h:222
virtual void AddComment(const Twine &T, bool EOL=true)
Add a textual comment.
Definition MCStreamer.h:394
virtual void emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo, unsigned Size)
Emit the absolute difference between two symbols.
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
virtual void emitValueToAlignment(Align Alignment, int64_t Fill=0, uint8_t FillLen=1, unsigned MaxBytesToEmit=0)
Emit some number of copies of Value until the byte alignment ByteAlignment is reached.
void emitInt32(uint64_t Value)
Definition MCStreamer.h:757
virtual void emitBytes(StringRef Data)
Emit the bytes in Data into the output.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition MCSymbol.h:251
Metadata node.
Definition Metadata.h:1080
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1442
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1450
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
int64_t getOffsetAdjustment() const
Return the correction for frame offsets.
unsigned getCVBytesOfCalleeSavedRegisters() const
Returns how many bytes of callee-saved registers the target pushed in the prologue.
bool hasStackProtectorIndex() const
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
bool hasInlineAsm() const
Returns true if the function contains any inline assembly.
bool exposesReturnsTwice() const
exposesReturnsTwice - Returns true if the function calls setjmp or any other similar functions with a...
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCSymbol * getJTISymbol(unsigned JTI, MCContext &Ctx, bool isLinkerPrivate=false) const
getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
auto getInStackSlotVariableDbgInfo()
Returns the collection of variables for which we have debug info and that have been assigned a stack ...
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
ArrayRef< std::pair< MCSymbol *, MDNode * > > getCodeViewAnnotations() const
Representation of each machine instruction.
bool isDebugValue() const
MachineOperand & getDebugOperand(unsigned Index)
@ EK_GPRel32BlockAddress
EK_GPRel32BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
@ EK_Inline
EK_Inline - Jump table entries are emitted inline at their point of use.
@ EK_LabelDifference32
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table.
@ EK_Custom32
EK_Custom32 - Each entry is a 32-bit value that is custom lowered by the TargetLowering::LowerCustomJ...
@ EK_LabelDifference64
EK_LabelDifference64 - Each entry is the address of the block minus the address of the jump table.
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.: .word LBB123.
@ EK_GPRel64BlockAddress
EK_GPRel64BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
const std::vector< MachineJumpTableEntry > & getJumpTables() const
const MCContext & getContext() const
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
A tuple of MDNodes.
Definition Metadata.h:1760
iterator_range< op_iterator > operands()
Definition Metadata.h:1856
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
const_iterator begin() const
Definition SmallSet.h:216
const_iterator end() const
Definition SmallSet.h:222
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:40
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:39
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
char back() const
back - Get the last character in the string.
Definition StringRef.h:152
StringRef take_front(size_t N=1) const
Return a StringRef equal to 'this' but with only the first N elements remaining.
Definition StringRef.h:600
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
virtual StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const
getFrameIndexReference - This method should return the base register and offset used to reference a f...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
@ UnknownArch
Definition Triple.h:50
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
@ CurrentDirectory
Absolute CWD path.
Definition TypeRecord.h:678
@ SourceFile
Path to main source file, relative or absolute.
Definition TypeRecord.h:680
@ BuildTool
Absolute compiler path.
Definition TypeRecord.h:679
@ CommandLine
Full canonical command line (maybe -cc1)
Definition TypeRecord.h:682
@ TypeServerPDB
Absolute path of type server PDB (/Fd)
Definition TypeRecord.h:681
LLVM_ABI void begin(ContinuationRecordKind RecordKind)
A 32-bit type reference.
Definition TypeIndex.h:97
SimpleTypeKind getSimpleKind() const
Definition TypeIndex.h:137
static TypeIndex None()
Definition TypeIndex.h:149
SimpleTypeMode getSimpleMode() const
Definition TypeIndex.h:142
static const uint32_t FirstNonSimpleIndex
Definition TypeIndex.h:99
static LLVM_ABI StringRef simpleTypeName(TypeIndex TI)
Definition TypeIndex.cpp:71
static TypeIndex Void()
Definition TypeIndex.h:150
uint32_t getIndex() const
Definition TypeIndex.h:112
static TypeIndex NullptrT()
Definition TypeIndex.h:158
static TypeIndex Int32()
Definition TypeIndex.h:183
void addCallbackToPipeline(TypeVisitorCallbacks &Callbacks)
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:180
IteratorT begin() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
@ DEBUG_HASHES_SECTION_MAGIC
Definition COFF.h:840
@ DEBUG_SECTION_MAGIC
Definition COFF.h:839
@ Entry
Definition COFF.h:862
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
PointerMode
Equivalent to CV_ptrmode_e.
Definition CodeView.h:335
ProcSymFlags
Corresponds to the CV_PROCFLAGS bitfield.
Definition CodeView.h:415
PointerOptions
Equivalent to misc lfPointerAttr bitfields.
Definition CodeView.h:344
LocalSymFlags
Corresponds to CV_LVARFLAGS bitfield.
Definition CodeView.h:388
MethodKind
Part of member attribute flags. (CV_methodprop_e)
Definition CodeView.h:252
CVRecord< TypeLeafKind > CVType
Definition CVRecord.h:64
PointerKind
Equivalent to CV_ptrtype_e.
Definition CodeView.h:318
CPUType
These values correspond to the CV_CPU_TYPE_e enumeration, and are documented here: https://msdn....
Definition CodeView.h:76
PointerToMemberRepresentation
Equivalent to CV_pmtype_e.
Definition CodeView.h:358
CallingConvention
These values correspond to the CV_call_e enumeration, and are documented at the following locations: ...
Definition CodeView.h:156
MethodOptions
Equivalent to CV_fldattr_t bitfield.
Definition CodeView.h:263
LLVM_ABI ArrayRef< EnumEntry< SymbolKind > > getSymbolTypeNames()
MemberAccess
Source-level access specifier. (CV_access_e)
Definition CodeView.h:244
ThunkOrdinal
These values correspond to the THUNK_ORDINAL enumeration.
Definition CodeView.h:536
EncodedFramePtrReg
Two-bit value indicating which register is the designated frame pointer register.
Definition CodeView.h:523
TypeRecordKind
Distinguishes individual records in .debug$T or .debug$P section or PDB type stream.
Definition CodeView.h:27
SymbolKind
Duplicate copy of the above enum, but using the official CV names.
Definition CodeView.h:48
ModifierOptions
Equivalent to CV_modifier_t.
Definition CodeView.h:283
LLVM_ABI StringRef getSymbolName(CVSymbol Sym)
LLVM_ABI EncodedFramePtrReg encodeFramePtrReg(RegisterId Reg, CPUType CPU)
LLVM_ABI Error visitTypeRecord(CVType &Record, TypeIndex Index, TypeVisitorCallbacks &Callbacks, VisitorDataSource Source=VDS_BytesPresent)
SourceLanguage
These values correspond to the CV_CFL_LANG enumeration in the Microsoft Debug Interface Access SDK,...
Definition CodeView.h:146
SourceLanguageName
Definition Dwarf.h:223
std::optional< std::pair< SourceLanguageName, uint32_t > > toDW_LNAME(SourceLanguage language)
Convert a DWARF 5 DW_LANG to a DWARF 6 pair of language name and version.
Definition Dwarf.h:372
ElementType
The element type of an SRV or UAV resource.
Definition DXILABI.h:68
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:683
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition Path.cpp:672
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:532
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition Error.cpp:61
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
std::string fromHex(StringRef Input)
Convert hexadecimal string Input to its binary representation. The return string is half the size of ...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
std::tuple< uint64_t, uint32_t > InlineSite
LLVM_GET_TYPE_NAME_CONSTEXPR StringRef getTypeName()
We provide a function which tries to compute the (demangled) name of a type statically.
Definition TypeName.h:40
std::pair< const MachineInstr *, const MachineInstr * > InsnRange
This is used to track range of instructions with identical lexical scope.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
FunctionAddr VTableAddr uintptr_t uintptr_t Version
Definition InstrProf.h:334
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Success
The lock was released successfully.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:221
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1910
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
const DIDerivedType * MemberTypeNode
std::vector< MemberInfo > MemberList
MemberList Members
Direct members.
std::vector< const DIType * > NestedTypes
MapVector< MDString *, MethodsList > MethodsMap
std::vector< const DIDerivedType * > Inheritance
Base classes.
TinyPtrVector< const DISubprogram * > MethodsList
int InMemory
Indicates that variable data is stored in memory relative to the specified register.
uint32_t CVRegister
Register containing the data or the register base of the memory location containing the data.
static constexpr int32_t NoDeref
Value for DerefOffset indicating this is not an indirect load.
static std::optional< DbgVariableLocation > extractFromMachineInstruction(const MachineInstr &Instruction)
Extract a VariableLocation from a MachineInstr.
std::vector< MachineBasicBlock * > MBBs
MBBs - The vector of basic blocks from which to create the jump table.
little32_t OffsetInUdt
Offset to add after dereferencing Register + BasePointerOffset.