#include "CodeViewDebug.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/BinaryFormat/COFF.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/LexicalScopes.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/TargetFrameLowering.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
#include "llvm/DebugInfo/CodeView/CodeViewRecordIO.h"
#include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
#include "llvm/DebugInfo/CodeView/EnumTables.h"
#include "llvm/DebugInfo/CodeView/Line.h"
#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
#include "llvm/DebugInfo/CodeView/TypeRecord.h"
#include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
#include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSectionCOFF.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/BinaryStreamWriter.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/SMLoc.h"
#include "llvm/Support/ScopedPrinter.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstddef>
#include <iterator>
#include <limits>
using namespace llvm;
using namespace llvm::codeview;
namespace {
class CVMCAdapter : public CodeViewRecordStreamer {
public:
CVMCAdapter(MCStreamer &OS, TypeCollection &TypeTable)
: OS(&OS), TypeTable(TypeTable) {}
void emitBytes(StringRef Data) override { OS->emitBytes(Data); }
void emitIntValue(uint64_t Value, unsigned Size) override {
OS->emitIntValueInHex(Value, Size);
}
void emitBinaryData(StringRef Data) override { OS->emitBinaryData(Data); }
void AddComment(const Twine &T) override { OS->AddComment(T); }
void AddRawComment(const Twine &T) override { OS->emitRawComment(T); }
bool isVerboseAsm() override { return OS->isVerboseAsm(); }
std::string getTypeName(TypeIndex TI) override {
std::string TypeName;
if (!TI.isNoneType()) {
if (TI.isSimple())
TypeName = std::string(TypeIndex::simpleTypeName(TI));
else
TypeName = std::string(TypeTable.getTypeName(TI));
}
return TypeName;
}
private:
MCStreamer *OS = nullptr;
TypeCollection &TypeTable;
};
}
static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
switch (Type) {
case Triple::ArchType::x86:
return CPUType::Pentium3;
case Triple::ArchType::x86_64:
return CPUType::X64;
case Triple::ArchType::thumb:
return CPUType::ARMNT;
case Triple::ArchType::aarch64:
return CPUType::ARM64;
default:
report_fatal_error("target architecture doesn't map to a CodeView CPUType");
}
}
CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
: DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {}
StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
std::string &Filepath = FileToFilepathMap[File];
if (!Filepath.empty())
return Filepath;
StringRef Dir = File->getDirectory(), Filename = File->getFilename();
if (Dir.startswith("/") || Filename.startswith("/")) {
if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
return Filename;
Filepath = std::string(Dir);
if (Dir.back() != '/')
Filepath += '/';
Filepath += Filename;
return Filepath;
}
if (Filename.find(':') == 1)
Filepath = std::string(Filename);
else
Filepath = (Dir + "\\" + Filename).str();
std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
size_t Cursor = 0;
while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
Filepath.erase(Cursor, 2);
Cursor = 0;
while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
if (Cursor == 0)
break;
size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
if (PrevSlash == std::string::npos)
break;
Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
Cursor = PrevSlash;
}
Cursor = 0;
while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
Filepath.erase(Cursor, 1);
return Filepath;
}
unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
StringRef FullPath = getFullFilepath(F);
unsigned NextId = FileIdMap.size() + 1;
auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
if (Insertion.second) {
ArrayRef<uint8_t> ChecksumAsBytes;
FileChecksumKind CSKind = FileChecksumKind::None;
if (F->getChecksum()) {
std::string Checksum = fromHex(F->getChecksum()->Value);
void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
memcpy(CKMem, Checksum.data(), Checksum.size());
ChecksumAsBytes = ArrayRef<uint8_t>(
reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
switch (F->getChecksum()->Kind) {
case DIFile::CSK_MD5:
CSKind = FileChecksumKind::MD5;
break;
case DIFile::CSK_SHA1:
CSKind = FileChecksumKind::SHA1;
break;
case DIFile::CSK_SHA256:
CSKind = FileChecksumKind::SHA256;
break;
}
}
bool Success = OS.emitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
static_cast<unsigned>(CSKind));
(void)Success;
assert(Success && ".cv_file directive failed");
}
return Insertion.first->second;
}
CodeViewDebug::InlineSite &
CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
const DISubprogram *Inlinee) {
auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
InlineSite *Site = &SiteInsertion.first->second;
if (SiteInsertion.second) {
unsigned ParentFuncId = CurFn->FuncId;
if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
ParentFuncId =
getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
.SiteFuncId;
Site->SiteFuncId = NextFuncId++;
OS.emitCVInlineSiteIdDirective(
Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Site->Inlinee = Inlinee;
InlinedSubprograms.insert(Inlinee);
getFuncIdForSubprogram(Inlinee);
}
return *Site;
}
static StringRef getPrettyScopeName(const DIScope *Scope) {
StringRef ScopeName = Scope->getName();
if (!ScopeName.empty())
return ScopeName;
switch (Scope->getTag()) {
case dwarf::DW_TAG_enumeration_type:
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_union_type:
return "<unnamed-tag>";
case dwarf::DW_TAG_namespace:
return "`anonymous namespace'";
default:
return StringRef();
}
}
const DISubprogram *CodeViewDebug::collectParentScopeNames(
const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
const DISubprogram *ClosestSubprogram = nullptr;
while (Scope != nullptr) {
if (ClosestSubprogram == nullptr)
ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
if (const auto *Ty = dyn_cast<DICompositeType>(Scope))
DeferredCompleteTypes.push_back(Ty);
StringRef ScopeName = getPrettyScopeName(Scope);
if (!ScopeName.empty())
QualifiedNameComponents.push_back(ScopeName);
Scope = Scope->getScope();
}
return ClosestSubprogram;
}
static std::string formatNestedName(ArrayRef<StringRef> QualifiedNameComponents,
StringRef TypeName) {
std::string FullyQualifiedName;
for (StringRef QualifiedNameComponent :
llvm::reverse(QualifiedNameComponents)) {
FullyQualifiedName.append(std::string(QualifiedNameComponent));
FullyQualifiedName.append("::");
}
FullyQualifiedName.append(std::string(TypeName));
return FullyQualifiedName;
}
struct CodeViewDebug::TypeLoweringScope {
TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
~TypeLoweringScope() {
if (CVD.TypeEmissionLevel == 1)
CVD.emitDeferredCompleteTypes();
--CVD.TypeEmissionLevel;
}
CodeViewDebug &CVD;
};
std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Scope,
StringRef Name) {
TypeLoweringScope S(*this);
SmallVector<StringRef, 5> QualifiedNameComponents;
collectParentScopeNames(Scope, QualifiedNameComponents);
return formatNestedName(QualifiedNameComponents, Name);
}
std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Ty) {
const DIScope *Scope = Ty->getScope();
return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
}
TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
if (!Scope || isa<DIFile>(Scope) || isa<DISubprogram>(Scope))
return TypeIndex();
assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
auto I = TypeIndices.find({Scope, nullptr});
if (I != TypeIndices.end())
return I->second;
std::string ScopeName = getFullyQualifiedName(Scope);
StringIdRecord SID(TypeIndex(), ScopeName);
auto TI = TypeTable.writeLeafType(SID);
return recordTypeIndexForDINode(Scope, TI);
}
static StringRef removeTemplateArgs(StringRef Name) {
if (Name.empty() || Name.back() != '>')
return Name;
int OpenBrackets = 0;
for (int i = Name.size() - 1; i >= 0; --i) {
if (Name[i] == '>')
++OpenBrackets;
else if (Name[i] == '<') {
--OpenBrackets;
if (OpenBrackets == 0)
return Name.substr(0, i);
}
}
return Name;
}
TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
assert(SP);
auto I = TypeIndices.find({SP, nullptr});
if (I != TypeIndices.end())
return I->second;
StringRef DisplayName = removeTemplateArgs(SP->getName());
const DIScope *Scope = SP->getScope();
TypeIndex TI;
if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
TypeIndex ClassType = getTypeIndex(Class);
MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
DisplayName);
TI = TypeTable.writeLeafType(MFuncId);
} else {
TypeIndex ParentScope = getScopeIndex(Scope);
FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
TI = TypeTable.writeLeafType(FuncId);
}
return recordTypeIndexForDINode(SP, TI);
}
static bool isNonTrivial(const DICompositeType *DCTy) {
return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
}
static FunctionOptions
getFunctionOptions(const DISubroutineType *Ty,
const DICompositeType *ClassTy = nullptr,
StringRef SPName = StringRef("")) {
FunctionOptions FO = FunctionOptions::None;
const DIType *ReturnTy = nullptr;
if (auto TypeArray = Ty->getTypeArray()) {
if (TypeArray.size())
ReturnTy = TypeArray[0];
}
if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy))
if (isNonTrivial(ReturnDCTy) || ClassTy)
FO |= FunctionOptions::CxxReturnUdt;
if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) {
FO |= FunctionOptions::Constructor;
}
return FO;
}
TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
const DICompositeType *Class) {
if (SP->getDeclaration())
SP = SP->getDeclaration();
assert(!SP->getDeclaration() && "should use declaration as key");
auto I = TypeIndices.find({SP, Class});
if (I != TypeIndices.end())
return I->second;
TypeLoweringScope S(*this);
const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
TypeIndex TI = lowerTypeMemberFunction(
SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
return recordTypeIndexForDINode(SP, TI, Class);
}
TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
TypeIndex TI,
const DIType *ClassTy) {
auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
(void)InsertResult;
assert(InsertResult.second && "DINode was already assigned a type index");
return TI;
}
unsigned CodeViewDebug::getPointerSizeInBytes() {
return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
}
void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
const LexicalScope *LS) {
if (const DILocation *InlinedAt = LS->getInlinedAt()) {
const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
Site.InlinedLocals.emplace_back(Var);
} else {
ScopeVariables[LS].emplace_back(Var);
}
}
static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
const DILocation *Loc) {
if (!llvm::is_contained(Locs, Loc))
Locs.push_back(Loc);
}
void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
const MachineFunction *MF) {
if (!DL || DL == PrevInstLoc)
return;
const DIScope *Scope = DL->getScope();
if (!Scope)
return;
LineInfo LI(DL.getLine(), DL.getLine(), true);
if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
LI.isNeverStepInto())
return;
ColumnInfo CI(DL.getCol(), 0);
if (CI.getStartColumn() != DL.getCol())
return;
if (!CurFn->HaveLineInfo)
CurFn->HaveLineInfo = true;
unsigned FileId = 0;
if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
FileId = CurFn->LastFileId;
else
FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
PrevInstLoc = DL;
unsigned FuncId = CurFn->FuncId;
if (const DILocation *SiteLoc = DL->getInlinedAt()) {
const DILocation *Loc = DL.get();
FuncId =
getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
bool FirstLoc = true;
while ((SiteLoc = Loc->getInlinedAt())) {
InlineSite &Site =
getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
if (!FirstLoc)
addLocIfNotPresent(Site.ChildSites, Loc);
FirstLoc = false;
Loc = SiteLoc;
}
addLocIfNotPresent(CurFn->ChildSites, Loc);
}
OS.emitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
false, false,
DL->getFilename(), SMLoc());
}
void CodeViewDebug::emitCodeViewMagicVersion() {
OS.emitValueToAlignment(4);
OS.AddComment("Debug section magic");
OS.emitInt32(COFF::DEBUG_SECTION_MAGIC);
}
static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
switch (DWLang) {
case dwarf::DW_LANG_C:
case dwarf::DW_LANG_C89:
case dwarf::DW_LANG_C99:
case dwarf::DW_LANG_C11:
case dwarf::DW_LANG_ObjC:
return SourceLanguage::C;
case dwarf::DW_LANG_C_plus_plus:
case dwarf::DW_LANG_C_plus_plus_03:
case dwarf::DW_LANG_C_plus_plus_11:
case dwarf::DW_LANG_C_plus_plus_14:
return SourceLanguage::Cpp;
case dwarf::DW_LANG_Fortran77:
case dwarf::DW_LANG_Fortran90:
case dwarf::DW_LANG_Fortran95:
case dwarf::DW_LANG_Fortran03:
case dwarf::DW_LANG_Fortran08:
return SourceLanguage::Fortran;
case dwarf::DW_LANG_Pascal83:
return SourceLanguage::Pascal;
case dwarf::DW_LANG_Cobol74:
case dwarf::DW_LANG_Cobol85:
return SourceLanguage::Cobol;
case dwarf::DW_LANG_Java:
return SourceLanguage::Java;
case dwarf::DW_LANG_D:
return SourceLanguage::D;
case dwarf::DW_LANG_Swift:
return SourceLanguage::Swift;
case dwarf::DW_LANG_Rust:
return SourceLanguage::Rust;
default:
return SourceLanguage::Masm;
}
}
void CodeViewDebug::beginModule(Module *M) {
if (!MMI->hasDebugInfo() ||
!Asm->getObjFileLowering().getCOFFDebugSymbolsSection()) {
Asm = nullptr;
return;
}
TheCPU = mapArchToCVCPUType(Triple(M->getTargetTriple()).getArch());
const MDNode *Node = *M->debug_compile_units_begin();
const auto *CU = cast<DICompileUnit>(Node);
CurrentSourceLanguage = MapDWLangToCVLang(CU->getSourceLanguage());
collectGlobalVariableInfo();
ConstantInt *GH =
mdconst::extract_or_null<ConstantInt>(M->getModuleFlag("CodeViewGHash"));
EmitDebugGlobalHashes = GH && !GH->isZero();
}
void CodeViewDebug::endModule() {
if (!Asm || !MMI->hasDebugInfo())
return;
switchToDebugSectionForSymbol(nullptr);
MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
emitObjName();
emitCompilerInformation();
endCVSubsection(CompilerInfo);
emitInlineeLinesSubsection();
for (auto &P : FnDebugInfo)
if (!P.first->isDeclarationForLinker())
emitDebugInfoForFunction(P.first, *P.second);
collectDebugInfoForGlobals();
emitDebugInfoForRetainedTypes();
setCurrentSubprogram(nullptr);
emitDebugInfoForGlobals();
switchToDebugSectionForSymbol(nullptr);
if (!GlobalUDTs.empty()) {
MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
emitDebugInfoForUDTs(GlobalUDTs);
endCVSubsection(SymbolsEnd);
}
OS.AddComment("File index to string table offset subsection");
OS.emitCVFileChecksumsDirective();
OS.AddComment("String table");
OS.emitCVStringTableDirective();
emitBuildInfo();
emitTypeInformation();
if (EmitDebugGlobalHashes)
emitTypeGlobalHashes();
clear();
}
static void
emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
unsigned MaxFixedRecordLength = 0xF00) {
SmallString<32> NullTerminatedString(
S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
NullTerminatedString.push_back('\0');
OS.emitBytes(NullTerminatedString);
}
void CodeViewDebug::emitTypeInformation() {
if (TypeTable.empty())
return;
OS.switchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
emitCodeViewMagicVersion();
TypeTableCollection Table(TypeTable.records());
TypeVisitorCallbackPipeline Pipeline;
CVMCAdapter CVMCOS(OS, Table);
TypeRecordMapping typeMapping(CVMCOS);
Pipeline.addCallbackToPipeline(typeMapping);
Optional<TypeIndex> B = Table.getFirst();
while (B) {
CVType Record = Table.getType(*B);
Error E = codeview::visitTypeRecord(Record, *B, Pipeline);
if (E) {
logAllUnhandledErrors(std::move(E), errs(), "error: ");
llvm_unreachable("produced malformed type record");
}
B = Table.getNext(*B);
}
}
void CodeViewDebug::emitTypeGlobalHashes() {
if (TypeTable.empty())
return;
OS.switchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
OS.emitValueToAlignment(4);
OS.AddComment("Magic");
OS.emitInt32(COFF::DEBUG_HASHES_SECTION_MAGIC);
OS.AddComment("Section Version");
OS.emitInt16(0);
OS.AddComment("Hash Algorithm");
OS.emitInt16(uint16_t(GlobalTypeHashAlg::SHA1_8));
TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
for (const auto &GHR : TypeTable.hashes()) {
if (OS.isVerboseAsm()) {
SmallString<32> Comment;
raw_svector_ostream CommentOS(Comment);
CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
OS.AddComment(Comment);
++TI;
}
assert(GHR.Hash.size() == 8);
StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
GHR.Hash.size());
OS.emitBinaryData(S);
}
}
void CodeViewDebug::emitObjName() {
MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_OBJNAME);
StringRef PathRef(Asm->TM.Options.ObjectFilenameForDebug);
llvm::SmallString<256> PathStore(PathRef);
if (PathRef.empty() || PathRef == "-") {
PathRef = {};
} else {
llvm::sys::path::remove_dots(PathStore, true);
PathRef = PathStore;
}
OS.AddComment("Signature");
OS.emitIntValue(0, 4);
OS.AddComment("Object name");
emitNullTerminatedSymbolName(OS, PathRef);
endSymbolRecord(CompilerEnd);
}
namespace {
struct Version {
int Part[4];
};
}
static Version parseVersion(StringRef Name) {
Version V = {{0}};
int N = 0;
for (const char C : Name) {
if (isdigit(C)) {
V.Part[N] *= 10;
V.Part[N] += C - '0';
V.Part[N] =
std::min<int>(V.Part[N], std::numeric_limits<uint16_t>::max());
} else if (C == '.') {
++N;
if (N >= 4)
return V;
} else if (N > 0)
return V;
}
return V;
}
void CodeViewDebug::emitCompilerInformation() {
MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
uint32_t Flags = 0;
Flags = CurrentSourceLanguage;
if (MMI->getModule()->getProfileSummary( false) != nullptr) {
Flags |= static_cast<uint32_t>(CompileSym3Flags::PGO);
}
using ArchType = llvm::Triple::ArchType;
ArchType Arch = Triple(MMI->getModule()->getTargetTriple()).getArch();
if (Asm->TM.Options.Hotpatch || Arch == ArchType::thumb ||
Arch == ArchType::aarch64) {
Flags |= static_cast<uint32_t>(CompileSym3Flags::HotPatch);
}
OS.AddComment("Flags and language");
OS.emitInt32(Flags);
OS.AddComment("CPUType");
OS.emitInt16(static_cast<uint64_t>(TheCPU));
NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
const MDNode *Node = *CUs->operands().begin();
const auto *CU = cast<DICompileUnit>(Node);
StringRef CompilerVersion = CU->getProducer();
Version FrontVer = parseVersion(CompilerVersion);
OS.AddComment("Frontend version");
for (int N : FrontVer.Part) {
OS.emitInt16(N);
}
int Major = 1000 * LLVM_VERSION_MAJOR +
10 * LLVM_VERSION_MINOR +
LLVM_VERSION_PATCH;
Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
Version BackVer = {{ Major, 0, 0, 0 }};
OS.AddComment("Backend version");
for (int N : BackVer.Part)
OS.emitInt16(N);
OS.AddComment("Null-terminated compiler version string");
emitNullTerminatedSymbolName(OS, CompilerVersion);
endSymbolRecord(CompilerEnd);
}
static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
StringRef S) {
StringIdRecord SIR(TypeIndex(0x0), S);
return TypeTable.writeLeafType(SIR);
}
static std::string flattenCommandLine(ArrayRef<std::string> Args,
StringRef MainFilename) {
std::string FlatCmdLine;
raw_string_ostream OS(FlatCmdLine);
bool PrintedOneArg = false;
if (!StringRef(Args[0]).contains("-cc1")) {
llvm::sys::printArg(OS, "-cc1", true);
PrintedOneArg = true;
}
for (unsigned i = 0; i < Args.size(); i++) {
StringRef Arg = Args[i];
if (Arg.empty())
continue;
if (Arg == "-main-file-name" || Arg == "-o") {
i++; continue;
}
if (Arg.startswith("-object-file-name") || Arg == MainFilename)
continue;
if (PrintedOneArg)
OS << " ";
llvm::sys::printArg(OS, Arg, true);
PrintedOneArg = true;
}
OS.flush();
return FlatCmdLine;
}
void CodeViewDebug::emitBuildInfo() {
TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
const MDNode *Node = *CUs->operands().begin(); const auto *CU = cast<DICompileUnit>(Node);
const DIFile *MainSourceFile = CU->getFile();
BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
BuildInfoArgs[BuildInfoRecord::SourceFile] =
getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
BuildInfoArgs[BuildInfoRecord::TypeServerPDB] =
getStringIdTypeIdx(TypeTable, "");
if (Asm->TM.Options.MCOptions.Argv0 != nullptr) {
BuildInfoArgs[BuildInfoRecord::BuildTool] =
getStringIdTypeIdx(TypeTable, Asm->TM.Options.MCOptions.Argv0);
BuildInfoArgs[BuildInfoRecord::CommandLine] = getStringIdTypeIdx(
TypeTable, flattenCommandLine(Asm->TM.Options.MCOptions.CommandLineArgs,
MainSourceFile->getFilename()));
}
BuildInfoRecord BIR(BuildInfoArgs);
TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
OS.AddComment("LF_BUILDINFO index");
OS.emitInt32(BuildInfoIndex.getIndex());
endSymbolRecord(BIEnd);
endCVSubsection(BISubsecEnd);
}
void CodeViewDebug::emitInlineeLinesSubsection() {
if (InlinedSubprograms.empty())
return;
OS.AddComment("Inlinee lines subsection");
MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
OS.AddComment("Inlinee lines signature");
OS.emitInt32(unsigned(InlineeLinesSignature::Normal));
for (const DISubprogram *SP : InlinedSubprograms) {
assert(TypeIndices.count({SP, nullptr}));
TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
OS.addBlankLine();
unsigned FileId = maybeRecordFile(SP->getFile());
OS.AddComment("Inlined function " + SP->getName() + " starts at " +
SP->getFilename() + Twine(':') + Twine(SP->getLine()));
OS.addBlankLine();
OS.AddComment("Type index of inlined function");
OS.emitInt32(InlineeIdx.getIndex());
OS.AddComment("Offset into filechecksum table");
OS.emitCVFileChecksumOffsetDirective(FileId);
OS.AddComment("Starting line number");
OS.emitInt32(SP->getLine());
}
endCVSubsection(InlineEnd);
}
void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
const DILocation *InlinedAt,
const InlineSite &Site) {
assert(TypeIndices.count({Site.Inlinee, nullptr}));
TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
OS.AddComment("PtrParent");
OS.emitInt32(0);
OS.AddComment("PtrEnd");
OS.emitInt32(0);
OS.AddComment("Inlinee type index");
OS.emitInt32(InlineeIdx.getIndex());
unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
unsigned StartLineNum = Site.Inlinee->getLine();
OS.emitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
FI.Begin, FI.End);
endSymbolRecord(InlineEnd);
emitLocalVariableList(FI, Site.InlinedLocals);
for (const DILocation *ChildSite : Site.ChildSites) {
auto I = FI.InlineSites.find(ChildSite);
assert(I != FI.InlineSites.end() &&
"child site not in function inline site map");
emitInlinedCallSite(FI, ChildSite, I->second);
}
emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
}
void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
MCSectionCOFF *GVSec =
GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
OS.switchSection(DebugSec);
if (ComdatDebugSections.insert(DebugSec).second)
emitCodeViewMagicVersion();
}
void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
FunctionInfo &FI,
const MCSymbol *Fn) {
std::string FuncName =
std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
const ThunkOrdinal ordinal = ThunkOrdinal::Standard;
OS.AddComment("Symbol subsection for " + Twine(FuncName));
MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
OS.AddComment("PtrParent");
OS.emitInt32(0);
OS.AddComment("PtrEnd");
OS.emitInt32(0);
OS.AddComment("PtrNext");
OS.emitInt32(0);
OS.AddComment("Thunk section relative address");
OS.emitCOFFSecRel32(Fn, 0);
OS.AddComment("Thunk section index");
OS.emitCOFFSectionIndex(Fn);
OS.AddComment("Code size");
OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
OS.AddComment("Ordinal");
OS.emitInt8(unsigned(ordinal));
OS.AddComment("Function name");
emitNullTerminatedSymbolName(OS, FuncName);
endSymbolRecord(ThunkRecordEnd);
emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
endCVSubsection(SymbolsEnd);
}
void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
FunctionInfo &FI) {
const MCSymbol *Fn = Asm->getSymbol(GV);
assert(Fn);
switchToDebugSectionForSymbol(Fn);
std::string FuncName;
auto *SP = GV->getSubprogram();
assert(SP);
setCurrentSubprogram(SP);
if (SP->isThunk()) {
emitDebugInfoForThunk(GV, FI, Fn);
return;
}
if (!SP->getName().empty())
FuncName = getFullyQualifiedName(SP->getScope(), SP->getName());
if (FuncName.empty())
FuncName = std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
OS.emitCVFPOData(Fn);
OS.AddComment("Symbol subsection for " + Twine(FuncName));
MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
{
SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
: SymbolKind::S_GPROC32_ID;
MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
OS.AddComment("PtrParent");
OS.emitInt32(0);
OS.AddComment("PtrEnd");
OS.emitInt32(0);
OS.AddComment("PtrNext");
OS.emitInt32(0);
OS.AddComment("Code size");
OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
OS.AddComment("Offset after prologue");
OS.emitInt32(0);
OS.AddComment("Offset before epilogue");
OS.emitInt32(0);
OS.AddComment("Function type index");
OS.emitInt32(getFuncIdForSubprogram(GV->getSubprogram()).getIndex());
OS.AddComment("Function section relative address");
OS.emitCOFFSecRel32(Fn, 0);
OS.AddComment("Function section index");
OS.emitCOFFSectionIndex(Fn);
OS.AddComment("Flags");
OS.emitInt8(0);
OS.AddComment("Function name");
emitNullTerminatedSymbolName(OS, FuncName);
endSymbolRecord(ProcRecordEnd);
MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
OS.AddComment("FrameSize");
OS.emitInt32(FI.FrameSize - FI.CSRSize);
OS.AddComment("Padding");
OS.emitInt32(0);
OS.AddComment("Offset of padding");
OS.emitInt32(0);
OS.AddComment("Bytes of callee saved registers");
OS.emitInt32(FI.CSRSize);
OS.AddComment("Exception handler offset");
OS.emitInt32(0);
OS.AddComment("Exception handler section");
OS.emitInt16(0);
OS.AddComment("Flags (defines frame register)");
OS.emitInt32(uint32_t(FI.FrameProcOpts));
endSymbolRecord(FrameProcEnd);
emitLocalVariableList(FI, FI.Locals);
emitGlobalVariableList(FI.Globals);
emitLexicalBlockList(FI.ChildBlocks, FI);
for (const DILocation *InlinedAt : FI.ChildSites) {
auto I = FI.InlineSites.find(InlinedAt);
assert(I != FI.InlineSites.end() &&
"child site not in function inline site map");
emitInlinedCallSite(FI, InlinedAt, I->second);
}
for (auto Annot : FI.Annotations) {
MCSymbol *Label = Annot.first;
MDTuple *Strs = cast<MDTuple>(Annot.second);
MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
OS.emitCOFFSecRel32(Label, 0);
OS.emitCOFFSectionIndex(Label);
OS.emitInt16(Strs->getNumOperands());
for (Metadata *MD : Strs->operands()) {
StringRef Str = cast<MDString>(MD)->getString();
assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
OS.emitBytes(StringRef(Str.data(), Str.size() + 1));
}
endSymbolRecord(AnnotEnd);
}
for (auto HeapAllocSite : FI.HeapAllocSites) {
const MCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
const MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
const DIType *DITy = std::get<2>(HeapAllocSite);
MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
OS.AddComment("Call site offset");
OS.emitCOFFSecRel32(BeginLabel, 0);
OS.AddComment("Call site section index");
OS.emitCOFFSectionIndex(BeginLabel);
OS.AddComment("Call instruction length");
OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
OS.AddComment("Type index");
OS.emitInt32(getCompleteTypeIndex(DITy).getIndex());
endSymbolRecord(HeapAllocEnd);
}
if (SP != nullptr)
emitDebugInfoForUDTs(LocalUDTs);
emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
}
endCVSubsection(SymbolsEnd);
OS.emitCVLinetableDirective(FI.FuncId, Fn, FI.End);
}
CodeViewDebug::LocalVarDef
CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
LocalVarDef DR;
DR.InMemory = -1;
DR.DataOffset = Offset;
assert(DR.DataOffset == Offset && "truncation");
DR.IsSubfield = 0;
DR.StructOffset = 0;
DR.CVRegister = CVRegister;
return DR;
}
void CodeViewDebug::collectVariableInfoFromMFTable(
DenseSet<InlinedEntity> &Processed) {
const MachineFunction &MF = *Asm->MF;
const TargetSubtargetInfo &TSI = MF.getSubtarget();
const TargetFrameLowering *TFI = TSI.getFrameLowering();
const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
if (!VI.Var)
continue;
assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
"Expected inlined-at fields to agree");
Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
if (!Scope)
continue;
int64_t ExprOffset = 0;
bool Deref = false;
if (VI.Expr) {
if (VI.Expr->getNumElements() == 1 &&
VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref)
Deref = true;
else if (!VI.Expr->extractIfOffset(ExprOffset))
continue;
}
Register FrameReg;
StackOffset FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
assert(!FrameOffset.getScalable() &&
"Frame offsets with a scalable component are not supported");
LocalVarDef DefRange =
createDefRangeMem(CVReg, FrameOffset.getFixed() + ExprOffset);
LocalVariable Var;
Var.DIVar = VI.Var;
for (const InsnRange &Range : Scope->getRanges()) {
const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
const MCSymbol *End = getLabelAfterInsn(Range.second);
End = End ? End : Asm->getFunctionEnd();
Var.DefRanges[DefRange].emplace_back(Begin, End);
}
if (Deref)
Var.UseReferenceType = true;
recordLocalVariable(std::move(Var), Scope);
}
}
static bool canUseReferenceType(const DbgVariableLocation &Loc) {
return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
}
static bool needsReferenceType(const DbgVariableLocation &Loc) {
return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
}
void CodeViewDebug::calculateRanges(
LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) {
const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) {
const auto &Entry = *I;
if (!Entry.isDbgValue())
continue;
const MachineInstr *DVInst = Entry.getInstr();
assert(DVInst->isDebugValue() && "Invalid History entry");
Optional<DbgVariableLocation> Location =
DbgVariableLocation::extractFromMachineInstruction(*DVInst);
if (!Location)
continue;
if (Var.UseReferenceType) {
if (canUseReferenceType(*Location))
Location->LoadChain.pop_back();
else
continue;
} else if (needsReferenceType(*Location)) {
Var.UseReferenceType = true;
Var.DefRanges.clear();
calculateRanges(Var, Entries);
return;
}
if (Location->Register == 0 || Location->LoadChain.size() > 1)
continue;
LocalVarDef DR;
DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
DR.InMemory = !Location->LoadChain.empty();
DR.DataOffset =
!Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
if (Location->FragmentInfo) {
DR.IsSubfield = true;
DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
} else {
DR.IsSubfield = false;
DR.StructOffset = 0;
}
const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr());
const MCSymbol *End;
if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
auto &EndingEntry = Entries[Entry.getEndIndex()];
End = EndingEntry.isDbgValue()
? getLabelBeforeInsn(EndingEntry.getInstr())
: getLabelAfterInsn(EndingEntry.getInstr());
} else
End = Asm->getFunctionEnd();
SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
Var.DefRanges[DR];
if (!R.empty() && R.back().second == Begin)
R.back().second = End;
else
R.emplace_back(Begin, End);
}
}
void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
DenseSet<InlinedEntity> Processed;
collectVariableInfoFromMFTable(Processed);
for (const auto &I : DbgValues) {
InlinedEntity IV = I.first;
if (Processed.count(IV))
continue;
const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
const DILocation *InlinedAt = IV.second;
const auto &Entries = I.second;
LexicalScope *Scope = nullptr;
if (InlinedAt)
Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
else
Scope = LScopes.findLexicalScope(DIVar->getScope());
if (!Scope)
continue;
LocalVariable Var;
Var.DIVar = DIVar;
calculateRanges(Var, Entries);
recordLocalVariable(std::move(Var), Scope);
}
}
void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
const TargetSubtargetInfo &TSI = MF->getSubtarget();
const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
const MachineFrameInfo &MFI = MF->getFrameInfo();
const Function &GV = MF->getFunction();
auto Insertion = FnDebugInfo.insert({&GV, std::make_unique<FunctionInfo>()});
assert(Insertion.second && "function already has info");
CurFn = Insertion.first->second.get();
CurFn->FuncId = NextFuncId++;
CurFn->Begin = Asm->getFunctionBegin();
CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
CurFn->FrameSize = MFI.getStackSize();
CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
CurFn->HasStackRealignment = TRI->hasStackRealignment(*MF);
CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; if (CurFn->FrameSize > 0) {
if (!TSI.getFrameLowering()->hasFP(*MF)) {
CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
} else {
CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
if (CurFn->HasStackRealignment) {
CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
} else {
CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
}
}
}
FrameProcedureOptions FPO = FrameProcedureOptions::None;
if (MFI.hasVarSizedObjects())
FPO |= FrameProcedureOptions::HasAlloca;
if (MF->exposesReturnsTwice())
FPO |= FrameProcedureOptions::HasSetJmp;
if (MF->hasInlineAsm())
FPO |= FrameProcedureOptions::HasInlineAssembly;
if (GV.hasPersonalityFn()) {
if (isAsynchronousEHPersonality(
classifyEHPersonality(GV.getPersonalityFn())))
FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
else
FPO |= FrameProcedureOptions::HasExceptionHandling;
}
if (GV.hasFnAttribute(Attribute::InlineHint))
FPO |= FrameProcedureOptions::MarkedInline;
if (GV.hasFnAttribute(Attribute::Naked))
FPO |= FrameProcedureOptions::Naked;
if (MFI.hasStackProtectorIndex())
FPO |= FrameProcedureOptions::SecurityChecks;
FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
if (Asm->TM.getOptLevel() != CodeGenOpt::None &&
!GV.hasOptSize() && !GV.hasOptNone())
FPO |= FrameProcedureOptions::OptimizedForSpeed;
if (GV.hasProfileData()) {
FPO |= FrameProcedureOptions::ValidProfileCounts;
FPO |= FrameProcedureOptions::ProfileGuidedOptimization;
}
CurFn->FrameProcOpts = FPO;
OS.emitCVFuncIdDirective(CurFn->FuncId);
DebugLoc PrologEndLoc;
bool EmptyPrologue = true;
for (const auto &MBB : *MF) {
for (const auto &MI : MBB) {
if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
MI.getDebugLoc()) {
PrologEndLoc = MI.getDebugLoc();
break;
} else if (!MI.isMetaInstruction()) {
EmptyPrologue = false;
}
}
}
if (PrologEndLoc && !EmptyPrologue) {
DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
maybeRecordLocation(FnStartDL, MF);
}
for (const auto &MBB : *MF) {
for (const auto &MI : MBB) {
if (MI.getHeapAllocMarker()) {
requestLabelBeforeInsn(&MI);
requestLabelAfterInsn(&MI);
}
}
}
}
static bool shouldEmitUdt(const DIType *T) {
if (!T)
return false;
if (T->getTag() == dwarf::DW_TAG_typedef) {
if (DIScope *Scope = T->getScope()) {
switch (Scope->getTag()) {
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_union_type:
return false;
default:
;
}
}
}
while (true) {
if (!T || T->isForwardDecl())
return false;
const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
if (!DT)
return true;
T = DT->getBaseType();
}
return true;
}
void CodeViewDebug::addToUDTs(const DIType *Ty) {
if (Ty->getName().empty())
return;
if (!shouldEmitUdt(Ty))
return;
SmallVector<StringRef, 5> ParentScopeNames;
const DISubprogram *ClosestSubprogram =
collectParentScopeNames(Ty->getScope(), ParentScopeNames);
std::string FullyQualifiedName =
formatNestedName(ParentScopeNames, getPrettyScopeName(Ty));
if (ClosestSubprogram == nullptr) {
GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
} else if (ClosestSubprogram == CurrentSubprogram) {
LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
}
}
TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
switch (Ty->getTag()) {
case dwarf::DW_TAG_array_type:
return lowerTypeArray(cast<DICompositeType>(Ty));
case dwarf::DW_TAG_typedef:
return lowerTypeAlias(cast<DIDerivedType>(Ty));
case dwarf::DW_TAG_base_type:
return lowerTypeBasic(cast<DIBasicType>(Ty));
case dwarf::DW_TAG_pointer_type:
if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
LLVM_FALLTHROUGH;
case dwarf::DW_TAG_reference_type:
case dwarf::DW_TAG_rvalue_reference_type:
return lowerTypePointer(cast<DIDerivedType>(Ty));
case dwarf::DW_TAG_ptr_to_member_type:
return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
case dwarf::DW_TAG_restrict_type:
case dwarf::DW_TAG_const_type:
case dwarf::DW_TAG_volatile_type:
return lowerTypeModifier(cast<DIDerivedType>(Ty));
case dwarf::DW_TAG_subroutine_type:
if (ClassTy) {
return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
0,
false);
}
return lowerTypeFunction(cast<DISubroutineType>(Ty));
case dwarf::DW_TAG_enumeration_type:
return lowerTypeEnum(cast<DICompositeType>(Ty));
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_structure_type:
return lowerTypeClass(cast<DICompositeType>(Ty));
case dwarf::DW_TAG_union_type:
return lowerTypeUnion(cast<DICompositeType>(Ty));
case dwarf::DW_TAG_string_type:
return lowerTypeString(cast<DIStringType>(Ty));
case dwarf::DW_TAG_unspecified_type:
if (Ty->getName() == "decltype(nullptr)")
return TypeIndex::NullptrT();
return TypeIndex::None();
default:
return TypeIndex();
}
}
TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
StringRef TypeName = Ty->getName();
addToUDTs(Ty);
if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
TypeName == "HRESULT")
return TypeIndex(SimpleTypeKind::HResult);
if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
TypeName == "wchar_t")
return TypeIndex(SimpleTypeKind::WideCharacter);
return UnderlyingTypeIndex;
}
TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
const DIType *ElementType = Ty->getBaseType();
TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
TypeIndex IndexType = getPointerSizeInBytes() == 8
? TypeIndex(SimpleTypeKind::UInt64Quad)
: TypeIndex(SimpleTypeKind::UInt32Long);
uint64_t ElementSize = getBaseTypeSize(ElementType) / 8;
DINodeArray Elements = Ty->getElements();
for (int i = Elements.size() - 1; i >= 0; --i) {
const DINode *Element = Elements[i];
assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
const DISubrange *Subrange = cast<DISubrange>(Element);
int64_t Count = -1;
if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt *>())
Count = CI->getSExtValue();
else if (auto *UI = Subrange->getUpperBound().dyn_cast<ConstantInt *>()) {
int64_t Lowerbound = (moduleIsInFortran()) ? 1 : 0;
auto *LI = Subrange->getLowerBound().dyn_cast<ConstantInt *>();
Lowerbound = (LI) ? LI->getSExtValue() : Lowerbound;
Count = UI->getSExtValue() - Lowerbound + 1;
}
if (Count == -1)
Count = 0;
ElementSize *= Count;
uint64_t ArraySize =
(i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
StringRef Name = (i == 0) ? Ty->getName() : "";
ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
ElementTypeIndex = TypeTable.writeLeafType(AR);
}
return ElementTypeIndex;
}
TypeIndex CodeViewDebug::lowerTypeString(const DIStringType *Ty) {
TypeIndex CharType = TypeIndex(SimpleTypeKind::NarrowCharacter);
uint64_t ArraySize = Ty->getSizeInBits() >> 3;
StringRef Name = Ty->getName();
TypeIndex IndexType = getPointerSizeInBytes() == 8
? TypeIndex(SimpleTypeKind::UInt64Quad)
: TypeIndex(SimpleTypeKind::UInt32Long);
ArrayRecord AR(CharType, IndexType, ArraySize, Name);
return TypeTable.writeLeafType(AR);
}
TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
TypeIndex Index;
dwarf::TypeKind Kind;
uint32_t ByteSize;
Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
ByteSize = Ty->getSizeInBits() / 8;
SimpleTypeKind STK = SimpleTypeKind::None;
switch (Kind) {
case dwarf::DW_ATE_address:
break;
case dwarf::DW_ATE_boolean:
switch (ByteSize) {
case 1: STK = SimpleTypeKind::Boolean8; break;
case 2: STK = SimpleTypeKind::Boolean16; break;
case 4: STK = SimpleTypeKind::Boolean32; break;
case 8: STK = SimpleTypeKind::Boolean64; break;
case 16: STK = SimpleTypeKind::Boolean128; break;
}
break;
case dwarf::DW_ATE_complex_float:
switch (ByteSize) {
case 2: STK = SimpleTypeKind::Complex16; break;
case 4: STK = SimpleTypeKind::Complex32; break;
case 8: STK = SimpleTypeKind::Complex64; break;
case 10: STK = SimpleTypeKind::Complex80; break;
case 16: STK = SimpleTypeKind::Complex128; break;
}
break;
case dwarf::DW_ATE_float:
switch (ByteSize) {
case 2: STK = SimpleTypeKind::Float16; break;
case 4: STK = SimpleTypeKind::Float32; break;
case 6: STK = SimpleTypeKind::Float48; break;
case 8: STK = SimpleTypeKind::Float64; break;
case 10: STK = SimpleTypeKind::Float80; break;
case 16: STK = SimpleTypeKind::Float128; break;
}
break;
case dwarf::DW_ATE_signed:
switch (ByteSize) {
case 1: STK = SimpleTypeKind::SignedCharacter; break;
case 2: STK = SimpleTypeKind::Int16Short; break;
case 4: STK = SimpleTypeKind::Int32; break;
case 8: STK = SimpleTypeKind::Int64Quad; break;
case 16: STK = SimpleTypeKind::Int128Oct; break;
}
break;
case dwarf::DW_ATE_unsigned:
switch (ByteSize) {
case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
case 2: STK = SimpleTypeKind::UInt16Short; break;
case 4: STK = SimpleTypeKind::UInt32; break;
case 8: STK = SimpleTypeKind::UInt64Quad; break;
case 16: STK = SimpleTypeKind::UInt128Oct; break;
}
break;
case dwarf::DW_ATE_UTF:
switch (ByteSize) {
case 1: STK = SimpleTypeKind::Character8; break;
case 2: STK = SimpleTypeKind::Character16; break;
case 4: STK = SimpleTypeKind::Character32; break;
}
break;
case dwarf::DW_ATE_signed_char:
if (ByteSize == 1)
STK = SimpleTypeKind::SignedCharacter;
break;
case dwarf::DW_ATE_unsigned_char:
if (ByteSize == 1)
STK = SimpleTypeKind::UnsignedCharacter;
break;
default:
break;
}
if (STK == SimpleTypeKind::Int32 &&
(Ty->getName() == "long int" || Ty->getName() == "long"))
STK = SimpleTypeKind::Int32Long;
if (STK == SimpleTypeKind::UInt32 && (Ty->getName() == "long unsigned int" ||
Ty->getName() == "unsigned long"))
STK = SimpleTypeKind::UInt32Long;
if (STK == SimpleTypeKind::UInt16Short &&
(Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
STK = SimpleTypeKind::WideCharacter;
if ((STK == SimpleTypeKind::SignedCharacter ||
STK == SimpleTypeKind::UnsignedCharacter) &&
Ty->getName() == "char")
STK = SimpleTypeKind::NarrowCharacter;
return TypeIndex(STK);
}
TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
PointerOptions PO) {
TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
if (PointeeTI.isSimple() && PO == PointerOptions::None &&
PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
Ty->getTag() == dwarf::DW_TAG_pointer_type) {
SimpleTypeMode Mode = Ty->getSizeInBits() == 64
? SimpleTypeMode::NearPointer64
: SimpleTypeMode::NearPointer32;
return TypeIndex(PointeeTI.getSimpleKind(), Mode);
}
PointerKind PK =
Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
PointerMode PM = PointerMode::Pointer;
switch (Ty->getTag()) {
default: llvm_unreachable("not a pointer tag type");
case dwarf::DW_TAG_pointer_type:
PM = PointerMode::Pointer;
break;
case dwarf::DW_TAG_reference_type:
PM = PointerMode::LValueReference;
break;
case dwarf::DW_TAG_rvalue_reference_type:
PM = PointerMode::RValueReference;
break;
}
if (Ty->isObjectPointer())
PO |= PointerOptions::Const;
PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
return TypeTable.writeLeafType(PR);
}
static PointerToMemberRepresentation
translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
if (IsPMF) {
switch (Flags & DINode::FlagPtrToMemberRep) {
case 0:
return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
: PointerToMemberRepresentation::GeneralFunction;
case DINode::FlagSingleInheritance:
return PointerToMemberRepresentation::SingleInheritanceFunction;
case DINode::FlagMultipleInheritance:
return PointerToMemberRepresentation::MultipleInheritanceFunction;
case DINode::FlagVirtualInheritance:
return PointerToMemberRepresentation::VirtualInheritanceFunction;
}
} else {
switch (Flags & DINode::FlagPtrToMemberRep) {
case 0:
return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
: PointerToMemberRepresentation::GeneralData;
case DINode::FlagSingleInheritance:
return PointerToMemberRepresentation::SingleInheritanceData;
case DINode::FlagMultipleInheritance:
return PointerToMemberRepresentation::MultipleInheritanceData;
case DINode::FlagVirtualInheritance:
return PointerToMemberRepresentation::VirtualInheritanceData;
}
}
llvm_unreachable("invalid ptr to member representation");
}
TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
PointerOptions PO) {
assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
TypeIndex PointeeTI =
getTypeIndex(Ty->getBaseType(), IsPMF ? Ty->getClassType() : nullptr);
PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
: PointerKind::Near32;
PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
: PointerMode::PointerToDataMember;
assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
MemberPointerInfo MPI(
ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
return TypeTable.writeLeafType(PR);
}
static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
switch (DwarfCC) {
case dwarf::DW_CC_normal: return CallingConvention::NearC;
case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
}
return CallingConvention::NearC;
}
TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
ModifierOptions Mods = ModifierOptions::None;
PointerOptions PO = PointerOptions::None;
bool IsModifier = true;
const DIType *BaseTy = Ty;
while (IsModifier && BaseTy) {
switch (BaseTy->getTag()) {
case dwarf::DW_TAG_const_type:
Mods |= ModifierOptions::Const;
PO |= PointerOptions::Const;
break;
case dwarf::DW_TAG_volatile_type:
Mods |= ModifierOptions::Volatile;
PO |= PointerOptions::Volatile;
break;
case dwarf::DW_TAG_restrict_type:
PO |= PointerOptions::Restrict;
break;
default:
IsModifier = false;
break;
}
if (IsModifier)
BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType();
}
if (BaseTy) {
switch (BaseTy->getTag()) {
case dwarf::DW_TAG_pointer_type:
case dwarf::DW_TAG_reference_type:
case dwarf::DW_TAG_rvalue_reference_type:
return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
case dwarf::DW_TAG_ptr_to_member_type:
return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
default:
break;
}
}
TypeIndex ModifiedTI = getTypeIndex(BaseTy);
if (Mods == ModifierOptions::None)
return ModifiedTI;
ModifierRecord MR(ModifiedTI, Mods);
return TypeTable.writeLeafType(MR);
}
TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
for (const DIType *ArgType : Ty->getTypeArray())
ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType));
if (ReturnAndArgTypeIndices.size() > 1 &&
ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
ReturnAndArgTypeIndices.back() = TypeIndex::None();
}
TypeIndex ReturnTypeIndex = TypeIndex::Void();
ArrayRef<TypeIndex> ArgTypeIndices = None;
if (!ReturnAndArgTypeIndices.empty()) {
auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
ReturnTypeIndex = ReturnAndArgTypesRef.front();
ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
}
ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
FunctionOptions FO = getFunctionOptions(Ty);
ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
ArgListIndex);
return TypeTable.writeLeafType(Procedure);
}
TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
const DIType *ClassTy,
int ThisAdjustment,
bool IsStaticMethod,
FunctionOptions FO) {
TypeIndex ClassType = getTypeIndex(ClassTy);
DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
unsigned Index = 0;
SmallVector<TypeIndex, 8> ArgTypeIndices;
TypeIndex ReturnTypeIndex = TypeIndex::Void();
if (ReturnAndArgs.size() > Index) {
ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
}
TypeIndex ThisTypeIndex;
if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
if (const DIDerivedType *PtrTy =
dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
Index++;
}
}
}
while (Index < ReturnAndArgs.size())
ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
ArgTypeIndices.back() = TypeIndex::None();
ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
return TypeTable.writeLeafType(MFR);
}
TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
unsigned VSlotCount =
Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
VFTableShapeRecord VFTSR(Slots);
return TypeTable.writeLeafType(VFTSR);
}
static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
switch (Flags & DINode::FlagAccessibility) {
case DINode::FlagPrivate: return MemberAccess::Private;
case DINode::FlagPublic: return MemberAccess::Public;
case DINode::FlagProtected: return MemberAccess::Protected;
case 0:
return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
: MemberAccess::Public;
}
llvm_unreachable("access flags are exclusive");
}
static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
if (SP->isArtificial())
return MethodOptions::CompilerGenerated;
return MethodOptions::None;
}
static MethodKind translateMethodKindFlags(const DISubprogram *SP,
bool Introduced) {
if (SP->getFlags() & DINode::FlagStaticMember)
return MethodKind::Static;
switch (SP->getVirtuality()) {
case dwarf::DW_VIRTUALITY_none:
break;
case dwarf::DW_VIRTUALITY_virtual:
return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
case dwarf::DW_VIRTUALITY_pure_virtual:
return Introduced ? MethodKind::PureIntroducingVirtual
: MethodKind::PureVirtual;
default:
llvm_unreachable("unhandled virtuality case");
}
return MethodKind::Vanilla;
}
static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
switch (Ty->getTag()) {
case dwarf::DW_TAG_class_type:
return TypeRecordKind::Class;
case dwarf::DW_TAG_structure_type:
return TypeRecordKind::Struct;
default:
llvm_unreachable("unexpected tag");
}
}
static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
ClassOptions CO = ClassOptions::None;
if (!Ty->getIdentifier().empty())
CO |= ClassOptions::HasUniqueName;
const DIScope *ImmediateScope = Ty->getScope();
if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
CO |= ClassOptions::Nested;
if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
CO |= ClassOptions::Scoped;
} else {
for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
Scope = Scope->getScope()) {
if (isa<DISubprogram>(Scope)) {
CO |= ClassOptions::Scoped;
break;
}
}
}
return CO;
}
void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
switch (Ty->getTag()) {
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_union_type:
case dwarf::DW_TAG_enumeration_type:
break;
default:
return;
}
if (const auto *File = Ty->getFile()) {
StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
TypeTable.writeLeafType(USLR);
}
}
TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
ClassOptions CO = getCommonClassOptions(Ty);
TypeIndex FTI;
unsigned EnumeratorCount = 0;
if (Ty->isForwardDecl()) {
CO |= ClassOptions::ForwardReference;
} else {
ContinuationRecordBuilder ContinuationBuilder;
ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
for (const DINode *Element : Ty->getElements()) {
if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
EnumeratorRecord ER(MemberAccess::Public,
APSInt(Enumerator->getValue(), true),
Enumerator->getName());
ContinuationBuilder.writeMemberType(ER);
EnumeratorCount++;
}
}
FTI = TypeTable.insertRecord(ContinuationBuilder);
}
std::string FullName = getFullyQualifiedName(Ty);
EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
getTypeIndex(Ty->getBaseType()));
TypeIndex EnumTI = TypeTable.writeLeafType(ER);
addUDTSrcLine(Ty, EnumTI);
return EnumTI;
}
struct llvm::ClassInfo {
struct MemberInfo {
const DIDerivedType *MemberTypeNode;
uint64_t BaseOffset;
};
using MemberList = std::vector<MemberInfo>;
using MethodsList = TinyPtrVector<const DISubprogram *>;
using MethodsMap = MapVector<MDString *, MethodsList>;
std::vector<const DIDerivedType *> Inheritance;
MemberList Members;
MethodsMap Methods;
TypeIndex VShapeTI;
std::vector<const DIType *> NestedTypes;
};
void CodeViewDebug::clear() {
assert(CurFn == nullptr);
FileIdMap.clear();
FnDebugInfo.clear();
FileToFilepathMap.clear();
LocalUDTs.clear();
GlobalUDTs.clear();
TypeIndices.clear();
CompleteTypeIndices.clear();
ScopeGlobals.clear();
CVGlobalVariableOffsets.clear();
}
void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
const DIDerivedType *DDTy) {
if (!DDTy->getName().empty()) {
Info.Members.push_back({DDTy, 0});
if ((DDTy->getFlags() & DINode::FlagStaticMember) ==
DINode::FlagStaticMember) {
if (DDTy->getConstant() && (isa<ConstantInt>(DDTy->getConstant()) ||
isa<ConstantFP>(DDTy->getConstant())))
StaticConstMembers.push_back(DDTy);
}
return;
}
assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
uint64_t Offset = DDTy->getOffsetInBits();
const DIType *Ty = DDTy->getBaseType();
bool FullyResolved = false;
while (!FullyResolved) {
switch (Ty->getTag()) {
case dwarf::DW_TAG_const_type:
case dwarf::DW_TAG_volatile_type:
Ty = cast<DIDerivedType>(Ty)->getBaseType();
break;
default:
FullyResolved = true;
break;
}
}
const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
if (!DCTy)
return;
ClassInfo NestedInfo = collectClassInfo(DCTy);
for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Info.Members.push_back(
{IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
}
ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
ClassInfo Info;
DINodeArray Elements = Ty->getElements();
for (auto *Element : Elements) {
if (!Element)
continue;
if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Info.Methods[SP->getRawName()].push_back(SP);
} else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
if (DDTy->getTag() == dwarf::DW_TAG_member) {
collectMemberInfo(Info, DDTy);
} else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
Info.Inheritance.push_back(DDTy);
} else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
DDTy->getName() == "__vtbl_ptr_type") {
Info.VShapeTI = getTypeIndex(DDTy);
} else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
Info.NestedTypes.push_back(DDTy);
} else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
}
} else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
Info.NestedTypes.push_back(Composite);
}
}
return Info;
}
static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
return Ty->getName().empty() && Ty->getIdentifier().empty() &&
!Ty->isForwardDecl();
}
TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
if (shouldAlwaysEmitCompleteClassType(Ty)) {
auto I = CompleteTypeIndices.find(Ty);
if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
report_fatal_error("cannot debug circular reference to unnamed type");
return getCompleteTypeIndex(Ty);
}
TypeRecordKind Kind = getRecordKind(Ty);
ClassOptions CO =
ClassOptions::ForwardReference | getCommonClassOptions(Ty);
std::string FullName = getFullyQualifiedName(Ty);
ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
FullName, Ty->getIdentifier());
TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
if (!Ty->isForwardDecl())
DeferredCompleteTypes.push_back(Ty);
return FwdDeclTI;
}
TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
TypeRecordKind Kind = getRecordKind(Ty);
ClassOptions CO = getCommonClassOptions(Ty);
TypeIndex FieldTI;
TypeIndex VShapeTI;
unsigned FieldCount;
bool ContainsNestedClass;
std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
lowerRecordFieldList(Ty);
if (ContainsNestedClass)
CO |= ClassOptions::ContainsNestedClass;
if (isNonTrivial(Ty))
CO |= ClassOptions::HasConstructorOrDestructor;
std::string FullName = getFullyQualifiedName(Ty);
uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
SizeInBytes, FullName, Ty->getIdentifier());
TypeIndex ClassTI = TypeTable.writeLeafType(CR);
addUDTSrcLine(Ty, ClassTI);
addToUDTs(Ty);
return ClassTI;
}
TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
if (shouldAlwaysEmitCompleteClassType(Ty))
return getCompleteTypeIndex(Ty);
ClassOptions CO =
ClassOptions::ForwardReference | getCommonClassOptions(Ty);
std::string FullName = getFullyQualifiedName(Ty);
UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
if (!Ty->isForwardDecl())
DeferredCompleteTypes.push_back(Ty);
return FwdDeclTI;
}
TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
TypeIndex FieldTI;
unsigned FieldCount;
bool ContainsNestedClass;
std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
lowerRecordFieldList(Ty);
if (ContainsNestedClass)
CO |= ClassOptions::ContainsNestedClass;
uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
std::string FullName = getFullyQualifiedName(Ty);
UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
Ty->getIdentifier());
TypeIndex UnionTI = TypeTable.writeLeafType(UR);
addUDTSrcLine(Ty, UnionTI);
addToUDTs(Ty);
return UnionTI;
}
std::tuple<TypeIndex, TypeIndex, unsigned, bool>
CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
unsigned MemberCount = 0;
ClassInfo Info = collectClassInfo(Ty);
ContinuationRecordBuilder ContinuationBuilder;
ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
for (const DIDerivedType *I : Info.Inheritance) {
if (I->getFlags() & DINode::FlagVirtual) {
unsigned VBPtrOffset = I->getVBPtrOffset();
unsigned VBTableIndex = I->getOffsetInBits() / 4;
auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
? TypeRecordKind::IndirectVirtualBaseClass
: TypeRecordKind::VirtualBaseClass;
VirtualBaseClassRecord VBCR(
RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
VBTableIndex);
ContinuationBuilder.writeMemberType(VBCR);
MemberCount++;
} else {
assert(I->getOffsetInBits() % 8 == 0 &&
"bases must be on byte boundaries");
BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
getTypeIndex(I->getBaseType()),
I->getOffsetInBits() / 8);
ContinuationBuilder.writeMemberType(BCR);
MemberCount++;
}
}
for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
const DIDerivedType *Member = MemberInfo.MemberTypeNode;
TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
StringRef MemberName = Member->getName();
MemberAccess Access =
translateAccessFlags(Ty->getTag(), Member->getFlags());
if (Member->isStaticMember()) {
StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
ContinuationBuilder.writeMemberType(SDMR);
MemberCount++;
continue;
}
if ((Member->getFlags() & DINode::FlagArtificial) &&
Member->getName().startswith("_vptr$")) {
VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
ContinuationBuilder.writeMemberType(VFPR);
MemberCount++;
continue;
}
uint64_t MemberOffsetInBits =
Member->getOffsetInBits() + MemberInfo.BaseOffset;
if (Member->isBitField()) {
uint64_t StartBitOffset = MemberOffsetInBits;
if (const auto *CI =
dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
}
StartBitOffset -= MemberOffsetInBits;
BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
StartBitOffset);
MemberBaseType = TypeTable.writeLeafType(BFR);
}
uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
MemberName);
ContinuationBuilder.writeMemberType(DMR);
MemberCount++;
}
for (auto &MethodItr : Info.Methods) {
StringRef Name = MethodItr.first->getString();
std::vector<OneMethodRecord> Methods;
for (const DISubprogram *SP : MethodItr.second) {
TypeIndex MethodType = getMemberFunctionType(SP, Ty);
bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
unsigned VFTableOffset = -1;
if (Introduced)
VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
Methods.push_back(OneMethodRecord(
MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
translateMethodKindFlags(SP, Introduced),
translateMethodOptionFlags(SP), VFTableOffset, Name));
MemberCount++;
}
assert(!Methods.empty() && "Empty methods map entry");
if (Methods.size() == 1)
ContinuationBuilder.writeMemberType(Methods[0]);
else {
MethodOverloadListRecord MOLR(Methods);
TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
ContinuationBuilder.writeMemberType(OMR);
}
}
for (const DIType *Nested : Info.NestedTypes) {
NestedTypeRecord R(getTypeIndex(Nested), Nested->getName());
ContinuationBuilder.writeMemberType(R);
MemberCount++;
}
TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
!Info.NestedTypes.empty());
}
TypeIndex CodeViewDebug::getVBPTypeIndex() {
if (!VBPType.getIndex()) {
ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
: PointerKind::Near32;
PointerMode PM = PointerMode::Pointer;
PointerOptions PO = PointerOptions::None;
PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
VBPType = TypeTable.writeLeafType(PR);
}
return VBPType;
}
TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
if (!Ty)
return TypeIndex::Void();
auto I = TypeIndices.find({Ty, ClassTy});
if (I != TypeIndices.end())
return I->second;
TypeLoweringScope S(*this);
TypeIndex TI = lowerType(Ty, ClassTy);
return recordTypeIndexForDINode(Ty, TI, ClassTy);
}
codeview::TypeIndex
CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
const DISubroutineType *SubroutineTy) {
assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
"this type must be a pointer type");
PointerOptions Options = PointerOptions::None;
if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
Options = PointerOptions::LValueRefThisPointer;
else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
Options = PointerOptions::RValueRefThisPointer;
auto I = TypeIndices.find({PtrTy, SubroutineTy});
if (I != TypeIndices.end())
return I->second;
TypeLoweringScope S(*this);
TypeIndex TI = lowerTypePointer(PtrTy, Options);
return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
}
TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) {
PointerRecord PR(getTypeIndex(Ty),
getPointerSizeInBytes() == 8 ? PointerKind::Near64
: PointerKind::Near32,
PointerMode::LValueReference, PointerOptions::None,
Ty->getSizeInBits() / 8);
return TypeTable.writeLeafType(PR);
}
TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
if (!Ty)
return TypeIndex::Void();
if (Ty->getTag() == dwarf::DW_TAG_typedef)
(void)getTypeIndex(Ty);
while (Ty->getTag() == dwarf::DW_TAG_typedef)
Ty = cast<DIDerivedType>(Ty)->getBaseType();
switch (Ty->getTag()) {
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_union_type:
break;
default:
return getTypeIndex(Ty);
}
const auto *CTy = cast<DICompositeType>(Ty);
TypeLoweringScope S(*this);
if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
TypeIndex FwdDeclTI = getTypeIndex(CTy);
if (CTy->isForwardDecl())
return FwdDeclTI;
}
auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
if (!InsertResult.second)
return InsertResult.first->second;
TypeIndex TI;
switch (CTy->getTag()) {
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_structure_type:
TI = lowerCompleteTypeClass(CTy);
break;
case dwarf::DW_TAG_union_type:
TI = lowerCompleteTypeUnion(CTy);
break;
default:
llvm_unreachable("not a record");
}
CompleteTypeIndices[CTy] = TI;
return TI;
}
void CodeViewDebug::emitDeferredCompleteTypes() {
SmallVector<const DICompositeType *, 4> TypesToEmit;
while (!DeferredCompleteTypes.empty()) {
std::swap(DeferredCompleteTypes, TypesToEmit);
for (const DICompositeType *RecordTy : TypesToEmit)
getCompleteTypeIndex(RecordTy);
TypesToEmit.clear();
}
}
void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
ArrayRef<LocalVariable> Locals) {
SmallVector<const LocalVariable *, 6> Params;
for (const LocalVariable &L : Locals)
if (L.DIVar->isParameter())
Params.push_back(&L);
llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
return L->DIVar->getArg() < R->DIVar->getArg();
});
for (const LocalVariable *L : Params)
emitLocalVariable(FI, *L);
for (const LocalVariable &L : Locals)
if (!L.DIVar->isParameter())
emitLocalVariable(FI, L);
}
void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
const LocalVariable &Var) {
MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
LocalSymFlags Flags = LocalSymFlags::None;
if (Var.DIVar->isParameter())
Flags |= LocalSymFlags::IsParameter;
if (Var.DefRanges.empty())
Flags |= LocalSymFlags::IsOptimizedOut;
OS.AddComment("TypeIndex");
TypeIndex TI = Var.UseReferenceType
? getTypeIndexForReferenceTo(Var.DIVar->getType())
: getCompleteTypeIndex(Var.DIVar->getType());
OS.emitInt32(TI.getIndex());
OS.AddComment("Flags");
OS.emitInt16(static_cast<uint16_t>(Flags));
emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
endSymbolRecord(LocalEnd);
SmallString<20> BytePrefix;
for (const auto &Pair : Var.DefRanges) {
LocalVarDef DefRange = Pair.first;
const auto &Ranges = Pair.second;
BytePrefix.clear();
if (DefRange.InMemory) {
int Offset = DefRange.DataOffset;
unsigned Reg = DefRange.CVRegister;
if (RegisterId(Reg) == RegisterId::ESP) {
Reg = unsigned(RegisterId::VFRAME);
Offset += FI.OffsetAdjustment;
}
EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
(bool(Flags & LocalSymFlags::IsParameter)
? (EncFP == FI.EncodedParamFramePtrReg)
: (EncFP == FI.EncodedLocalFramePtrReg))) {
DefRangeFramePointerRelHeader DRHdr;
DRHdr.Offset = Offset;
OS.emitCVDefRangeDirective(Ranges, DRHdr);
} else {
uint16_t RegRelFlags = 0;
if (DefRange.IsSubfield) {
RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
(DefRange.StructOffset
<< DefRangeRegisterRelSym::OffsetInParentShift);
}
DefRangeRegisterRelHeader DRHdr;
DRHdr.Register = Reg;
DRHdr.Flags = RegRelFlags;
DRHdr.BasePointerOffset = Offset;
OS.emitCVDefRangeDirective(Ranges, DRHdr);
}
} else {
assert(DefRange.DataOffset == 0 && "unexpected offset into register");
if (DefRange.IsSubfield) {
DefRangeSubfieldRegisterHeader DRHdr;
DRHdr.Register = DefRange.CVRegister;
DRHdr.MayHaveNoName = 0;
DRHdr.OffsetInParent = DefRange.StructOffset;
OS.emitCVDefRangeDirective(Ranges, DRHdr);
} else {
DefRangeRegisterHeader DRHdr;
DRHdr.Register = DefRange.CVRegister;
DRHdr.MayHaveNoName = 0;
OS.emitCVDefRangeDirective(Ranges, DRHdr);
}
}
}
}
void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
const FunctionInfo& FI) {
for (LexicalBlock *Block : Blocks)
emitLexicalBlock(*Block, FI);
}
void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
const FunctionInfo& FI) {
MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
OS.AddComment("PtrParent");
OS.emitInt32(0); OS.AddComment("PtrEnd");
OS.emitInt32(0); OS.AddComment("Code size");
OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); OS.AddComment("Function section relative address");
OS.emitCOFFSecRel32(Block.Begin, 0); OS.AddComment("Function section index");
OS.emitCOFFSectionIndex(FI.Begin); OS.AddComment("Lexical block name");
emitNullTerminatedSymbolName(OS, Block.Name); endSymbolRecord(RecordEnd);
emitLocalVariableList(FI, Block.Locals);
emitGlobalVariableList(Block.Globals);
emitLexicalBlockList(Block.Children, FI);
emitEndSymbolRecord(SymbolKind::S_END);
}
void CodeViewDebug::collectLexicalBlockInfo(
SmallVectorImpl<LexicalScope *> &Scopes,
SmallVectorImpl<LexicalBlock *> &Blocks,
SmallVectorImpl<LocalVariable> &Locals,
SmallVectorImpl<CVGlobalVariable> &Globals) {
for (LexicalScope *Scope : Scopes)
collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
}
void CodeViewDebug::collectLexicalBlockInfo(
LexicalScope &Scope,
SmallVectorImpl<LexicalBlock *> &ParentBlocks,
SmallVectorImpl<LocalVariable> &ParentLocals,
SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
if (Scope.isAbstractScope())
return;
bool IgnoreScope = false;
auto LI = ScopeVariables.find(&Scope);
SmallVectorImpl<LocalVariable> *Locals =
LI != ScopeVariables.end() ? &LI->second : nullptr;
auto GI = ScopeGlobals.find(Scope.getScopeNode());
SmallVectorImpl<CVGlobalVariable> *Globals =
GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
if (!Locals && !Globals)
IgnoreScope = true;
if (!DILB)
IgnoreScope = true;
if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
IgnoreScope = true;
if (IgnoreScope) {
if (Locals)
ParentLocals.append(Locals->begin(), Locals->end());
if (Globals)
ParentGlobals.append(Globals->begin(), Globals->end());
collectLexicalBlockInfo(Scope.getChildren(),
ParentBlocks,
ParentLocals,
ParentGlobals);
return;
}
auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
if (!BlockInsertion.second)
return;
const InsnRange &Range = Ranges.front();
assert(Range.first && Range.second);
LexicalBlock &Block = BlockInsertion.first->second;
Block.Begin = getLabelBeforeInsn(Range.first);
Block.End = getLabelAfterInsn(Range.second);
assert(Block.Begin && "missing label for scope begin");
assert(Block.End && "missing label for scope end");
Block.Name = DILB->getName();
if (Locals)
Block.Locals = std::move(*Locals);
if (Globals)
Block.Globals = std::move(*Globals);
ParentBlocks.push_back(&Block);
collectLexicalBlockInfo(Scope.getChildren(),
Block.Children,
Block.Locals,
Block.Globals);
}
void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
const Function &GV = MF->getFunction();
assert(FnDebugInfo.count(&GV));
assert(CurFn == FnDebugInfo[&GV].get());
collectVariableInfo(GV.getSubprogram());
if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
collectLexicalBlockInfo(*CFS,
CurFn->ChildBlocks,
CurFn->Locals,
CurFn->Globals);
ScopeVariables.clear();
if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
FnDebugInfo.erase(&GV);
CurFn = nullptr;
return;
}
for (const auto &MBB : *MF) {
for (const auto &MI : MBB) {
if (MDNode *MD = MI.getHeapAllocMarker()) {
CurFn->HeapAllocSites.push_back(std::make_tuple(getLabelBeforeInsn(&MI),
getLabelAfterInsn(&MI),
dyn_cast<DIType>(MD)));
}
}
}
CurFn->Annotations = MF->getCodeViewAnnotations();
CurFn->End = Asm->getFunctionEnd();
CurFn = nullptr;
}
static bool isUsableDebugLoc(DebugLoc DL) {
return DL && DL.getLine() != 0;
}
void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
DebugHandlerBase::beginInstruction(MI);
if (!Asm || !CurFn || MI->isDebugInstr() ||
MI->getFlag(MachineInstr::FrameSetup))
return;
DebugLoc DL = MI->getDebugLoc();
if (!isUsableDebugLoc(DL) && MI->getParent() != PrevInstBB) {
for (const auto &NextMI : *MI->getParent()) {
if (NextMI.isDebugInstr())
continue;
DL = NextMI.getDebugLoc();
if (isUsableDebugLoc(DL))
break;
}
}
PrevInstBB = MI->getParent();
if (!isUsableDebugLoc(DL))
return;
maybeRecordLocation(DL, Asm->MF);
}
MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
*EndLabel = MMI->getContext().createTempSymbol();
OS.emitInt32(unsigned(Kind));
OS.AddComment("Subsection size");
OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
OS.emitLabel(BeginLabel);
return EndLabel;
}
void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
OS.emitLabel(EndLabel);
OS.emitValueToAlignment(4);
}
static StringRef getSymbolName(SymbolKind SymKind) {
for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
if (EE.Value == SymKind)
return EE.Name;
return "";
}
MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
*EndLabel = MMI->getContext().createTempSymbol();
OS.AddComment("Record length");
OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
OS.emitLabel(BeginLabel);
if (OS.isVerboseAsm())
OS.AddComment("Record kind: " + getSymbolName(SymKind));
OS.emitInt16(unsigned(SymKind));
return EndLabel;
}
void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
OS.emitValueToAlignment(4);
OS.emitLabel(SymEnd);
}
void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
OS.AddComment("Record length");
OS.emitInt16(2);
if (OS.isVerboseAsm())
OS.AddComment("Record kind: " + getSymbolName(EndKind));
OS.emitInt16(uint16_t(EndKind)); }
void CodeViewDebug::emitDebugInfoForUDTs(
const std::vector<std::pair<std::string, const DIType *>> &UDTs) {
#ifndef NDEBUG
size_t OriginalSize = UDTs.size();
#endif
for (const auto &UDT : UDTs) {
const DIType *T = UDT.second;
assert(shouldEmitUdt(T));
MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
OS.AddComment("Type");
OS.emitInt32(getCompleteTypeIndex(T).getIndex());
assert(OriginalSize == UDTs.size() &&
"getCompleteTypeIndex found new UDTs!");
emitNullTerminatedSymbolName(OS, UDT.first);
endSymbolRecord(UDTRecordEnd);
}
}
void CodeViewDebug::collectGlobalVariableInfo() {
DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
GlobalMap;
for (const GlobalVariable &GV : MMI->getModule()->globals()) {
SmallVector<DIGlobalVariableExpression *, 1> GVEs;
GV.getDebugInfo(GVEs);
for (const auto *GVE : GVEs)
GlobalMap[GVE] = &GV;
}
NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
for (const MDNode *Node : CUs->operands()) {
const auto *CU = cast<DICompileUnit>(Node);
for (const auto *GVE : CU->getGlobalVariables()) {
const DIGlobalVariable *DIGV = GVE->getVariable();
const DIExpression *DIE = GVE->getExpression();
if (DIGV->getName().empty()) continue;
if ((DIE->getNumElements() == 2) &&
(DIE->getElement(0) == dwarf::DW_OP_plus_uconst))
CVGlobalVariableOffsets.insert(
std::make_pair(DIGV, DIE->getElement(1)));
if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) {
CVGlobalVariable CVGV = {DIGV, DIE};
GlobalVariables.emplace_back(std::move(CVGV));
}
const auto *GV = GlobalMap.lookup(GVE);
if (!GV || GV->isDeclarationForLinker())
continue;
DIScope *Scope = DIGV->getScope();
SmallVector<CVGlobalVariable, 1> *VariableList;
if (Scope && isa<DILocalScope>(Scope)) {
auto Insertion = ScopeGlobals.insert(
{Scope, std::unique_ptr<GlobalVariableList>()});
if (Insertion.second)
Insertion.first->second = std::make_unique<GlobalVariableList>();
VariableList = Insertion.first->second.get();
} else if (GV->hasComdat())
VariableList = &ComdatVariables;
else
VariableList = &GlobalVariables;
CVGlobalVariable CVGV = {DIGV, GV};
VariableList->emplace_back(std::move(CVGV));
}
}
}
void CodeViewDebug::collectDebugInfoForGlobals() {
for (const CVGlobalVariable &CVGV : GlobalVariables) {
const DIGlobalVariable *DIGV = CVGV.DIGV;
const DIScope *Scope = DIGV->getScope();
getCompleteTypeIndex(DIGV->getType());
getFullyQualifiedName(Scope, DIGV->getName());
}
for (const CVGlobalVariable &CVGV : ComdatVariables) {
const DIGlobalVariable *DIGV = CVGV.DIGV;
const DIScope *Scope = DIGV->getScope();
getCompleteTypeIndex(DIGV->getType());
getFullyQualifiedName(Scope, DIGV->getName());
}
}
void CodeViewDebug::emitDebugInfoForGlobals() {
switchToDebugSectionForSymbol(nullptr);
if (!GlobalVariables.empty() || !StaticConstMembers.empty()) {
OS.AddComment("Symbol subsection for globals");
MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
emitGlobalVariableList(GlobalVariables);
emitStaticConstMemberList();
endCVSubsection(EndLabel);
}
for (const CVGlobalVariable &CVGV : ComdatVariables) {
const GlobalVariable *GV = CVGV.GVInfo.get<const GlobalVariable *>();
MCSymbol *GVSym = Asm->getSymbol(GV);
OS.AddComment("Symbol subsection for " +
Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
switchToDebugSectionForSymbol(GVSym);
MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
emitDebugInfoForGlobal(CVGV);
endCVSubsection(EndLabel);
}
}
void CodeViewDebug::emitDebugInfoForRetainedTypes() {
NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
for (const MDNode *Node : CUs->operands()) {
for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
if (DIType *RT = dyn_cast<DIType>(Ty)) {
getTypeIndex(RT);
}
}
}
}
void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
for (const CVGlobalVariable &CVGV : Globals) {
emitDebugInfoForGlobal(CVGV);
}
}
void CodeViewDebug::emitConstantSymbolRecord(const DIType *DTy, APSInt &Value,
const std::string &QualifiedName) {
MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
OS.AddComment("Type");
OS.emitInt32(getTypeIndex(DTy).getIndex());
OS.AddComment("Value");
uint8_t Data[10];
BinaryStreamWriter Writer(Data, llvm::support::endianness::little);
CodeViewRecordIO IO(Writer);
cantFail(IO.mapEncodedInteger(Value));
StringRef SRef((char *)Data, Writer.getOffset());
OS.emitBinaryData(SRef);
OS.AddComment("Name");
emitNullTerminatedSymbolName(OS, QualifiedName);
endSymbolRecord(SConstantEnd);
}
void CodeViewDebug::emitStaticConstMemberList() {
for (const DIDerivedType *DTy : StaticConstMembers) {
const DIScope *Scope = DTy->getScope();
APSInt Value;
if (const ConstantInt *CI =
dyn_cast_or_null<ConstantInt>(DTy->getConstant()))
Value = APSInt(CI->getValue(),
DebugHandlerBase::isUnsignedDIType(DTy->getBaseType()));
else if (const ConstantFP *CFP =
dyn_cast_or_null<ConstantFP>(DTy->getConstant()))
Value = APSInt(CFP->getValueAPF().bitcastToAPInt(), true);
else
llvm_unreachable("cannot emit a constant without a value");
emitConstantSymbolRecord(DTy->getBaseType(), Value,
getFullyQualifiedName(Scope, DTy->getName()));
}
}
static bool isFloatDIType(const DIType *Ty) {
if (isa<DICompositeType>(Ty))
return false;
if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
dwarf::Tag T = (dwarf::Tag)Ty->getTag();
if (T == dwarf::DW_TAG_pointer_type ||
T == dwarf::DW_TAG_ptr_to_member_type ||
T == dwarf::DW_TAG_reference_type ||
T == dwarf::DW_TAG_rvalue_reference_type)
return false;
assert(DTy->getBaseType() && "Expected valid base type");
return isFloatDIType(DTy->getBaseType());
}
auto *BTy = cast<DIBasicType>(Ty);
return (BTy->getEncoding() == dwarf::DW_ATE_float);
}
void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
const DIGlobalVariable *DIGV = CVGV.DIGV;
const DIScope *Scope = DIGV->getScope();
if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
DIGV->getRawStaticDataMemberDeclaration()))
Scope = MemberDecl->getScope();
std::string QualifiedName =
(moduleIsInFortran()) ? std::string(DIGV->getName())
: getFullyQualifiedName(Scope, DIGV->getName());
if (const GlobalVariable *GV =
CVGV.GVInfo.dyn_cast<const GlobalVariable *>()) {
MCSymbol *GVSym = Asm->getSymbol(GV);
SymbolKind DataSym = GV->isThreadLocal()
? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
: SymbolKind::S_GTHREAD32)
: (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
: SymbolKind::S_GDATA32);
MCSymbol *DataEnd = beginSymbolRecord(DataSym);
OS.AddComment("Type");
OS.emitInt32(getCompleteTypeIndex(DIGV->getType()).getIndex());
OS.AddComment("DataOffset");
uint64_t Offset = 0;
if (CVGlobalVariableOffsets.find(DIGV) != CVGlobalVariableOffsets.end())
Offset = CVGlobalVariableOffsets[DIGV];
OS.emitCOFFSecRel32(GVSym, Offset);
OS.AddComment("Segment");
OS.emitCOFFSectionIndex(GVSym);
OS.AddComment("Name");
const unsigned LengthOfDataRecord = 12;
emitNullTerminatedSymbolName(OS, QualifiedName, LengthOfDataRecord);
endSymbolRecord(DataEnd);
} else {
const DIExpression *DIE = CVGV.GVInfo.get<const DIExpression *>();
assert(DIE->isConstant() &&
"Global constant variables must contain a constant expression.");
bool isUnsigned = isFloatDIType(DIGV->getType())
? true
: DebugHandlerBase::isUnsignedDIType(DIGV->getType());
APSInt Value(APInt(64, DIE->getElement(1)), isUnsigned);
emitConstantSymbolRecord(DIGV->getType(), Value, QualifiedName);
}
}