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