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