#include "CGRecordLayout.h"
#include "CGCXXABI.h"
#include "CodeGenTypes.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/RecordLayout.h"
#include "clang/Basic/CodeGenOptions.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
using namespace CodeGen;
namespace {
struct CGRecordLowering {
struct MemberInfo {
CharUnits Offset;
enum InfoKind { VFPtr, VBPtr, Field, Base, VBase, Scissor } Kind;
llvm::Type *Data;
union {
const FieldDecl *FD;
const CXXRecordDecl *RD;
};
MemberInfo(CharUnits Offset, InfoKind Kind, llvm::Type *Data,
const FieldDecl *FD = nullptr)
: Offset(Offset), Kind(Kind), Data(Data), FD(FD) {}
MemberInfo(CharUnits Offset, InfoKind Kind, llvm::Type *Data,
const CXXRecordDecl *RD)
: Offset(Offset), Kind(Kind), Data(Data), RD(RD) {}
bool operator <(const MemberInfo& a) const { return Offset < a.Offset; }
};
CGRecordLowering(CodeGenTypes &Types, const RecordDecl *D, bool Packed);
MemberInfo StorageInfo(CharUnits Offset, llvm::Type *Data) {
return MemberInfo(Offset, MemberInfo::Field, Data);
}
bool isDiscreteBitFieldABI() {
return Context.getTargetInfo().getCXXABI().isMicrosoft() ||
D->isMsStruct(Context);
}
bool isAAPCS() const {
return Context.getTargetInfo().getABI().startswith("aapcs");
}
bool isBE() const { return Context.getTargetInfo().isBigEndian(); }
bool isOverlappingVBaseABI() {
return !Context.getTargetInfo().getCXXABI().isMicrosoft();
}
llvm::Type *getIntNType(uint64_t NumBits) {
unsigned AlignedBits = llvm::alignTo(NumBits, Context.getCharWidth());
return llvm::Type::getIntNTy(Types.getLLVMContext(), AlignedBits);
}
llvm::Type *getCharType() {
return llvm::Type::getIntNTy(Types.getLLVMContext(),
Context.getCharWidth());
}
llvm::Type *getByteArrayType(CharUnits NumChars) {
assert(!NumChars.isZero() && "Empty byte arrays aren't allowed.");
llvm::Type *Type = getCharType();
return NumChars == CharUnits::One() ? Type :
(llvm::Type *)llvm::ArrayType::get(Type, NumChars.getQuantity());
}
llvm::Type *getStorageType(const FieldDecl *FD) {
llvm::Type *Type = Types.ConvertTypeForMem(FD->getType());
if (!FD->isBitField()) return Type;
if (isDiscreteBitFieldABI()) return Type;
return getIntNType(std::min(FD->getBitWidthValue(Context),
(unsigned)Context.toBits(getSize(Type))));
}
llvm::Type *getStorageType(const CXXRecordDecl *RD) {
return Types.getCGRecordLayout(RD).getBaseSubobjectLLVMType();
}
CharUnits bitsToCharUnits(uint64_t BitOffset) {
return Context.toCharUnitsFromBits(BitOffset);
}
CharUnits getSize(llvm::Type *Type) {
return CharUnits::fromQuantity(DataLayout.getTypeAllocSize(Type));
}
CharUnits getAlignment(llvm::Type *Type) {
return CharUnits::fromQuantity(DataLayout.getABITypeAlignment(Type));
}
bool isZeroInitializable(const FieldDecl *FD) {
return Types.isZeroInitializable(FD->getType());
}
bool isZeroInitializable(const RecordDecl *RD) {
return Types.isZeroInitializable(RD);
}
void appendPaddingBytes(CharUnits Size) {
if (!Size.isZero())
FieldTypes.push_back(getByteArrayType(Size));
}
uint64_t getFieldBitOffset(const FieldDecl *FD) {
return Layout.getFieldOffset(FD->getFieldIndex());
}
void setBitFieldInfo(const FieldDecl *FD, CharUnits StartOffset,
llvm::Type *StorageType);
void lower(bool NonVirtualBaseType);
void lowerUnion();
void accumulateFields();
void accumulateBitFields(RecordDecl::field_iterator Field,
RecordDecl::field_iterator FieldEnd);
void computeVolatileBitfields();
void accumulateBases();
void accumulateVPtrs();
void accumulateVBases();
bool hasOwnStorage(const CXXRecordDecl *Decl, const CXXRecordDecl *Query);
void calculateZeroInit();
void clipTailPadding();
void determinePacked(bool NVBaseType);
void insertPadding();
void fillOutputFields();
CodeGenTypes &Types;
const ASTContext &Context;
const RecordDecl *D;
const CXXRecordDecl *RD;
const ASTRecordLayout &Layout;
const llvm::DataLayout &DataLayout;
std::vector<MemberInfo> Members;
SmallVector<llvm::Type *, 16> FieldTypes;
llvm::DenseMap<const FieldDecl *, unsigned> Fields;
llvm::DenseMap<const FieldDecl *, CGBitFieldInfo> BitFields;
llvm::DenseMap<const CXXRecordDecl *, unsigned> NonVirtualBases;
llvm::DenseMap<const CXXRecordDecl *, unsigned> VirtualBases;
bool IsZeroInitializable : 1;
bool IsZeroInitializableAsBase : 1;
bool Packed : 1;
private:
CGRecordLowering(const CGRecordLowering &) = delete;
void operator =(const CGRecordLowering &) = delete;
};
}
CGRecordLowering::CGRecordLowering(CodeGenTypes &Types, const RecordDecl *D,
bool Packed)
: Types(Types), Context(Types.getContext()), D(D),
RD(dyn_cast<CXXRecordDecl>(D)),
Layout(Types.getContext().getASTRecordLayout(D)),
DataLayout(Types.getDataLayout()), IsZeroInitializable(true),
IsZeroInitializableAsBase(true), Packed(Packed) {}
void CGRecordLowering::setBitFieldInfo(
const FieldDecl *FD, CharUnits StartOffset, llvm::Type *StorageType) {
CGBitFieldInfo &Info = BitFields[FD->getCanonicalDecl()];
Info.IsSigned = FD->getType()->isSignedIntegerOrEnumerationType();
Info.Offset = (unsigned)(getFieldBitOffset(FD) - Context.toBits(StartOffset));
Info.Size = FD->getBitWidthValue(Context);
Info.StorageSize = (unsigned)DataLayout.getTypeAllocSizeInBits(StorageType);
Info.StorageOffset = StartOffset;
if (Info.Size > Info.StorageSize)
Info.Size = Info.StorageSize;
if (DataLayout.isBigEndian())
Info.Offset = Info.StorageSize - (Info.Offset + Info.Size);
Info.VolatileStorageSize = 0;
Info.VolatileOffset = 0;
Info.VolatileStorageOffset = CharUnits::Zero();
}
void CGRecordLowering::lower(bool NVBaseType) {
CharUnits Size = NVBaseType ? Layout.getNonVirtualSize() : Layout.getSize();
if (D->isUnion()) {
lowerUnion();
computeVolatileBitfields();
return;
}
accumulateFields();
if (RD) {
accumulateVPtrs();
accumulateBases();
if (Members.empty()) {
appendPaddingBytes(Size);
computeVolatileBitfields();
return;
}
if (!NVBaseType)
accumulateVBases();
}
llvm::stable_sort(Members);
Members.push_back(StorageInfo(Size, getIntNType(8)));
clipTailPadding();
determinePacked(NVBaseType);
insertPadding();
Members.pop_back();
calculateZeroInit();
fillOutputFields();
computeVolatileBitfields();
}
void CGRecordLowering::lowerUnion() {
CharUnits LayoutSize = Layout.getSize();
llvm::Type *StorageType = nullptr;
bool SeenNamedMember = false;
for (const auto *Field : D->fields()) {
if (Field->isBitField()) {
if (Field->isZeroLengthBitField(Context))
continue;
llvm::Type *FieldType = getStorageType(Field);
if (LayoutSize < getSize(FieldType))
FieldType = getByteArrayType(LayoutSize);
setBitFieldInfo(Field, CharUnits::Zero(), FieldType);
}
Fields[Field->getCanonicalDecl()] = 0;
llvm::Type *FieldType = getStorageType(Field);
if (!SeenNamedMember) {
SeenNamedMember = Field->getIdentifier();
if (!SeenNamedMember)
if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
SeenNamedMember = FieldRD->findFirstNamedDataMember();
if (SeenNamedMember && !isZeroInitializable(Field)) {
IsZeroInitializable = IsZeroInitializableAsBase = false;
StorageType = FieldType;
}
}
if (!IsZeroInitializable)
continue;
if (!StorageType ||
getAlignment(FieldType) > getAlignment(StorageType) ||
(getAlignment(FieldType) == getAlignment(StorageType) &&
getSize(FieldType) > getSize(StorageType)))
StorageType = FieldType;
}
if (!StorageType)
return appendPaddingBytes(LayoutSize);
if (LayoutSize < getSize(StorageType))
StorageType = getByteArrayType(LayoutSize);
FieldTypes.push_back(StorageType);
appendPaddingBytes(LayoutSize - getSize(StorageType));
if (LayoutSize % getAlignment(StorageType))
Packed = true;
}
void CGRecordLowering::accumulateFields() {
for (RecordDecl::field_iterator Field = D->field_begin(),
FieldEnd = D->field_end();
Field != FieldEnd;) {
if (Field->isBitField()) {
RecordDecl::field_iterator Start = Field;
for (++Field; Field != FieldEnd && Field->isBitField(); ++Field);
accumulateBitFields(Start, Field);
} else if (!Field->isZeroSize(Context)) {
Members.push_back(MemberInfo(
bitsToCharUnits(getFieldBitOffset(*Field)), MemberInfo::Field,
getStorageType(*Field), *Field));
++Field;
} else {
++Field;
}
}
}
void
CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
RecordDecl::field_iterator FieldEnd) {
RecordDecl::field_iterator Run = FieldEnd;
uint64_t StartBitOffset, Tail = 0;
if (isDiscreteBitFieldABI()) {
for (; Field != FieldEnd; ++Field) {
uint64_t BitOffset = getFieldBitOffset(*Field);
if (Field->isZeroLengthBitField(Context)) {
Run = FieldEnd;
continue;
}
llvm::Type *Type =
Types.ConvertTypeForMem(Field->getType(), true);
if (Run == FieldEnd || BitOffset >= Tail) {
Run = Field;
StartBitOffset = BitOffset;
Tail = StartBitOffset + DataLayout.getTypeAllocSizeInBits(Type);
Members.push_back(StorageInfo(bitsToCharUnits(StartBitOffset), Type));
}
Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
MemberInfo::Field, nullptr, *Field));
}
return;
}
auto IsBetterAsSingleFieldRun = [&](uint64_t OffsetInRecord,
uint64_t StartBitOffset) {
if (!Types.getCodeGenOpts().FineGrainedBitfieldAccesses)
return false;
if (OffsetInRecord < 8 || !llvm::isPowerOf2_64(OffsetInRecord) ||
!DataLayout.fitsInLegalInteger(OffsetInRecord))
return false;
if (StartBitOffset %
Context.toBits(getAlignment(getIntNType(OffsetInRecord))) !=
0)
return false;
return true;
};
bool StartFieldAsSingleRun = false;
for (;;) {
if (Run == FieldEnd) {
if (Field == FieldEnd)
break;
if (!Field->isZeroLengthBitField(Context)) {
Run = Field;
StartBitOffset = getFieldBitOffset(*Field);
Tail = StartBitOffset + Field->getBitWidthValue(Context);
StartFieldAsSingleRun = IsBetterAsSingleFieldRun(Tail - StartBitOffset,
StartBitOffset);
}
++Field;
continue;
}
if (!StartFieldAsSingleRun && Field != FieldEnd &&
!IsBetterAsSingleFieldRun(Tail - StartBitOffset, StartBitOffset) &&
(!Field->isZeroLengthBitField(Context) ||
(!Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
!Context.getTargetInfo().useBitFieldTypeAlignment())) &&
Tail == getFieldBitOffset(*Field)) {
Tail += Field->getBitWidthValue(Context);
++Field;
continue;
}
llvm::Type *Type = getIntNType(Tail - StartBitOffset);
Members.push_back(StorageInfo(bitsToCharUnits(StartBitOffset), Type));
for (; Run != Field; ++Run)
Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
MemberInfo::Field, nullptr, *Run));
Run = FieldEnd;
StartFieldAsSingleRun = false;
}
}
void CGRecordLowering::accumulateBases() {
if (Layout.isPrimaryBaseVirtual()) {
const CXXRecordDecl *BaseDecl = Layout.getPrimaryBase();
Members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::Base,
getStorageType(BaseDecl), BaseDecl));
}
for (const auto &Base : RD->bases()) {
if (Base.isVirtual())
continue;
const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
if (!BaseDecl->isEmpty() &&
!Context.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
Members.push_back(MemberInfo(Layout.getBaseClassOffset(BaseDecl),
MemberInfo::Base, getStorageType(BaseDecl), BaseDecl));
}
}
void CGRecordLowering::computeVolatileBitfields() {
if (!isAAPCS() || !Types.getCodeGenOpts().AAPCSBitfieldWidth)
return;
for (auto &I : BitFields) {
const FieldDecl *Field = I.first;
CGBitFieldInfo &Info = I.second;
llvm::Type *ResLTy = Types.ConvertTypeForMem(Field->getType());
if ((uint64_t)(Context.toBits(Layout.getAlignment())) <
ResLTy->getPrimitiveSizeInBits())
continue;
const unsigned OldOffset =
isBE() ? Info.StorageSize - (Info.Offset + Info.Size) : Info.Offset;
const unsigned AbsoluteOffset =
Context.toBits(Info.StorageOffset) + OldOffset;
const unsigned StorageSize = ResLTy->getPrimitiveSizeInBits();
if (Info.StorageSize == StorageSize && (OldOffset % StorageSize == 0))
continue;
unsigned Offset = AbsoluteOffset & (StorageSize - 1);
if (Offset + Info.Size > StorageSize)
continue;
if (isBE())
Offset = StorageSize - (Offset + Info.Size);
const CharUnits StorageOffset =
Context.toCharUnitsFromBits(AbsoluteOffset & ~(StorageSize - 1));
const CharUnits End = StorageOffset +
Context.toCharUnitsFromBits(StorageSize) -
CharUnits::One();
const ASTRecordLayout &Layout =
Context.getASTRecordLayout(Field->getParent());
const CharUnits RecordSize = Layout.getSize();
if (End >= RecordSize)
continue;
bool Conflict = false;
for (const auto *F : D->fields()) {
if (F->isBitField() && !F->isZeroLengthBitField(Context))
continue;
const CharUnits FOffset = Context.toCharUnitsFromBits(
Layout.getFieldOffset(F->getFieldIndex()));
if (F->isZeroLengthBitField(Context)) {
if (End > FOffset && StorageOffset < FOffset) {
Conflict = true;
break;
}
}
const CharUnits FEnd =
FOffset +
Context.toCharUnitsFromBits(
Types.ConvertTypeForMem(F->getType())->getPrimitiveSizeInBits()) -
CharUnits::One();
if (End < FOffset || FEnd < StorageOffset)
continue;
Conflict = true;
break;
}
if (Conflict)
continue;
Info.VolatileStorageOffset =
StorageOffset / Context.toCharUnitsFromBits(StorageSize).getQuantity();
Info.VolatileStorageSize = StorageSize;
Info.VolatileOffset = Offset;
}
}
void CGRecordLowering::accumulateVPtrs() {
if (Layout.hasOwnVFPtr())
Members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::VFPtr,
llvm::FunctionType::get(getIntNType(32), true)->
getPointerTo()->getPointerTo()));
if (Layout.hasOwnVBPtr())
Members.push_back(MemberInfo(Layout.getVBPtrOffset(), MemberInfo::VBPtr,
llvm::Type::getInt32PtrTy(Types.getLLVMContext())));
}
void CGRecordLowering::accumulateVBases() {
CharUnits ScissorOffset = Layout.getNonVirtualSize();
if (isOverlappingVBaseABI())
for (const auto &Base : RD->vbases()) {
const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
if (BaseDecl->isEmpty())
continue;
if (Context.isNearlyEmpty(BaseDecl) && !hasOwnStorage(RD, BaseDecl))
continue;
ScissorOffset = std::min(ScissorOffset,
Layout.getVBaseClassOffset(BaseDecl));
}
Members.push_back(MemberInfo(ScissorOffset, MemberInfo::Scissor, nullptr,
RD));
for (const auto &Base : RD->vbases()) {
const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
if (BaseDecl->isEmpty())
continue;
CharUnits Offset = Layout.getVBaseClassOffset(BaseDecl);
if (isOverlappingVBaseABI() &&
Context.isNearlyEmpty(BaseDecl) &&
!hasOwnStorage(RD, BaseDecl)) {
Members.push_back(MemberInfo(Offset, MemberInfo::VBase, nullptr,
BaseDecl));
continue;
}
if (Layout.getVBaseOffsetsMap().find(BaseDecl)->second.hasVtorDisp())
Members.push_back(StorageInfo(Offset - CharUnits::fromQuantity(4),
getIntNType(32)));
Members.push_back(MemberInfo(Offset, MemberInfo::VBase,
getStorageType(BaseDecl), BaseDecl));
}
}
bool CGRecordLowering::hasOwnStorage(const CXXRecordDecl *Decl,
const CXXRecordDecl *Query) {
const ASTRecordLayout &DeclLayout = Context.getASTRecordLayout(Decl);
if (DeclLayout.isPrimaryBaseVirtual() && DeclLayout.getPrimaryBase() == Query)
return false;
for (const auto &Base : Decl->bases())
if (!hasOwnStorage(Base.getType()->getAsCXXRecordDecl(), Query))
return false;
return true;
}
void CGRecordLowering::calculateZeroInit() {
for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
MemberEnd = Members.end();
IsZeroInitializableAsBase && Member != MemberEnd; ++Member) {
if (Member->Kind == MemberInfo::Field) {
if (!Member->FD || isZeroInitializable(Member->FD))
continue;
IsZeroInitializable = IsZeroInitializableAsBase = false;
} else if (Member->Kind == MemberInfo::Base ||
Member->Kind == MemberInfo::VBase) {
if (isZeroInitializable(Member->RD))
continue;
IsZeroInitializable = false;
if (Member->Kind == MemberInfo::Base)
IsZeroInitializableAsBase = false;
}
}
}
void CGRecordLowering::clipTailPadding() {
std::vector<MemberInfo>::iterator Prior = Members.begin();
CharUnits Tail = getSize(Prior->Data);
for (std::vector<MemberInfo>::iterator Member = Prior + 1,
MemberEnd = Members.end();
Member != MemberEnd; ++Member) {
if (!Member->Data && Member->Kind != MemberInfo::Scissor)
continue;
if (Member->Offset < Tail) {
assert(Prior->Kind == MemberInfo::Field &&
"Only storage fields have tail padding!");
if (!Prior->FD || Prior->FD->isBitField())
Prior->Data = getByteArrayType(bitsToCharUnits(llvm::alignTo(
cast<llvm::IntegerType>(Prior->Data)->getIntegerBitWidth(), 8)));
else {
assert(Prior->FD->hasAttr<NoUniqueAddressAttr>() &&
"should not have reused this field's tail padding");
Prior->Data = getByteArrayType(
Context.getTypeInfoDataSizeInChars(Prior->FD->getType()).Width);
}
}
if (Member->Data)
Prior = Member;
Tail = Prior->Offset + getSize(Prior->Data);
}
}
void CGRecordLowering::determinePacked(bool NVBaseType) {
if (Packed)
return;
CharUnits Alignment = CharUnits::One();
CharUnits NVAlignment = CharUnits::One();
CharUnits NVSize =
!NVBaseType && RD ? Layout.getNonVirtualSize() : CharUnits::Zero();
for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
MemberEnd = Members.end();
Member != MemberEnd; ++Member) {
if (!Member->Data)
continue;
if (Member->Offset % getAlignment(Member->Data))
Packed = true;
if (Member->Offset < NVSize)
NVAlignment = std::max(NVAlignment, getAlignment(Member->Data));
Alignment = std::max(Alignment, getAlignment(Member->Data));
}
if (Members.back().Offset % Alignment)
Packed = true;
if (NVSize % NVAlignment)
Packed = true;
if (!Packed)
Members.back().Data = getIntNType(Context.toBits(Alignment));
}
void CGRecordLowering::insertPadding() {
std::vector<std::pair<CharUnits, CharUnits> > Padding;
CharUnits Size = CharUnits::Zero();
for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
MemberEnd = Members.end();
Member != MemberEnd; ++Member) {
if (!Member->Data)
continue;
CharUnits Offset = Member->Offset;
assert(Offset >= Size);
if (Offset !=
Size.alignTo(Packed ? CharUnits::One() : getAlignment(Member->Data)))
Padding.push_back(std::make_pair(Size, Offset - Size));
Size = Offset + getSize(Member->Data);
}
if (Padding.empty())
return;
for (std::vector<std::pair<CharUnits, CharUnits> >::const_iterator
Pad = Padding.begin(), PadEnd = Padding.end();
Pad != PadEnd; ++Pad)
Members.push_back(StorageInfo(Pad->first, getByteArrayType(Pad->second)));
llvm::stable_sort(Members);
}
void CGRecordLowering::fillOutputFields() {
for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
MemberEnd = Members.end();
Member != MemberEnd; ++Member) {
if (Member->Data)
FieldTypes.push_back(Member->Data);
if (Member->Kind == MemberInfo::Field) {
if (Member->FD)
Fields[Member->FD->getCanonicalDecl()] = FieldTypes.size() - 1;
if (!Member->Data)
setBitFieldInfo(Member->FD, Member->Offset, FieldTypes.back());
} else if (Member->Kind == MemberInfo::Base)
NonVirtualBases[Member->RD] = FieldTypes.size() - 1;
else if (Member->Kind == MemberInfo::VBase)
VirtualBases[Member->RD] = FieldTypes.size() - 1;
}
}
CGBitFieldInfo CGBitFieldInfo::MakeInfo(CodeGenTypes &Types,
const FieldDecl *FD,
uint64_t Offset, uint64_t Size,
uint64_t StorageSize,
CharUnits StorageOffset) {
llvm::Type *Ty = Types.ConvertTypeForMem(FD->getType());
CharUnits TypeSizeInBytes =
CharUnits::fromQuantity(Types.getDataLayout().getTypeAllocSize(Ty));
uint64_t TypeSizeInBits = Types.getContext().toBits(TypeSizeInBytes);
bool IsSigned = FD->getType()->isSignedIntegerOrEnumerationType();
if (Size > TypeSizeInBits) {
Size = TypeSizeInBits;
}
if (Types.getDataLayout().isBigEndian()) {
Offset = StorageSize - (Offset + Size);
}
return CGBitFieldInfo(Offset, Size, IsSigned, StorageSize, StorageOffset);
}
std::unique_ptr<CGRecordLayout>
CodeGenTypes::ComputeRecordLayout(const RecordDecl *D, llvm::StructType *Ty) {
CGRecordLowering Builder(*this, D, false);
Builder.lower(false);
llvm::StructType *BaseTy = nullptr;
if (isa<CXXRecordDecl>(D) && !D->isUnion() && !D->hasAttr<FinalAttr>()) {
BaseTy = Ty;
if (Builder.Layout.getNonVirtualSize() != Builder.Layout.getSize()) {
CGRecordLowering BaseBuilder(*this, D, Builder.Packed);
BaseBuilder.lower(true);
BaseTy = llvm::StructType::create(
getLLVMContext(), BaseBuilder.FieldTypes, "", BaseBuilder.Packed);
addRecordTypeName(D, BaseTy, ".base");
assert(Builder.Packed == BaseBuilder.Packed &&
"Non-virtual and complete types must agree on packedness");
}
}
Ty->setBody(Builder.FieldTypes, Builder.Packed);
auto RL = std::make_unique<CGRecordLayout>(
Ty, BaseTy, (bool)Builder.IsZeroInitializable,
(bool)Builder.IsZeroInitializableAsBase);
RL->NonVirtualBases.swap(Builder.NonVirtualBases);
RL->CompleteObjectVirtualBases.swap(Builder.VirtualBases);
RL->FieldInfo.swap(Builder.Fields);
RL->BitFields.swap(Builder.BitFields);
if (getContext().getLangOpts().DumpRecordLayouts) {
llvm::outs() << "\n*** Dumping IRgen Record Layout\n";
llvm::outs() << "Record: ";
D->dump(llvm::outs());
llvm::outs() << "\nLayout: ";
RL->print(llvm::outs());
}
#ifndef NDEBUG
const ASTRecordLayout &Layout = getContext().getASTRecordLayout(D);
uint64_t TypeSizeInBits = getContext().toBits(Layout.getSize());
assert(TypeSizeInBits == getDataLayout().getTypeAllocSizeInBits(Ty) &&
"Type size mismatch!");
if (BaseTy) {
CharUnits NonVirtualSize = Layout.getNonVirtualSize();
uint64_t AlignedNonVirtualTypeSizeInBits =
getContext().toBits(NonVirtualSize);
assert(AlignedNonVirtualTypeSizeInBits ==
getDataLayout().getTypeAllocSizeInBits(BaseTy) &&
"Type size mismatch!");
}
llvm::StructType *ST = RL->getLLVMType();
const llvm::StructLayout *SL = getDataLayout().getStructLayout(ST);
const ASTRecordLayout &AST_RL = getContext().getASTRecordLayout(D);
RecordDecl::field_iterator it = D->field_begin();
for (unsigned i = 0, e = AST_RL.getFieldCount(); i != e; ++i, ++it) {
const FieldDecl *FD = *it;
if (FD->isZeroSize(getContext()))
continue;
if (!FD->isBitField()) {
unsigned FieldNo = RL->getLLVMFieldNo(FD);
assert(AST_RL.getFieldOffset(i) == SL->getElementOffsetInBits(FieldNo) &&
"Invalid field offset!");
continue;
}
if (!FD->getDeclName())
continue;
const CGBitFieldInfo &Info = RL->getBitFieldInfo(FD);
llvm::Type *ElementTy = ST->getTypeAtIndex(RL->getLLVMFieldNo(FD));
if (D->isUnion()) {
if (getDataLayout().isBigEndian())
assert(static_cast<unsigned>(Info.Offset + Info.Size) ==
Info.StorageSize &&
"Big endian union bitfield does not end at the back");
else
assert(Info.Offset == 0 &&
"Little endian union bitfield with a non-zero offset");
assert(Info.StorageSize <= SL->getSizeInBits() &&
"Union not large enough for bitfield storage");
} else {
assert((Info.StorageSize ==
getDataLayout().getTypeAllocSizeInBits(ElementTy) ||
Info.VolatileStorageSize ==
getDataLayout().getTypeAllocSizeInBits(ElementTy)) &&
"Storage size does not match the element type size");
}
assert(Info.Size > 0 && "Empty bitfield!");
assert(static_cast<unsigned>(Info.Offset) + Info.Size <= Info.StorageSize &&
"Bitfield outside of its allocated storage");
}
#endif
return RL;
}
void CGRecordLayout::print(raw_ostream &OS) const {
OS << "<CGRecordLayout\n";
OS << " LLVMType:" << *CompleteObjectType << "\n";
if (BaseSubobjectType)
OS << " NonVirtualBaseLLVMType:" << *BaseSubobjectType << "\n";
OS << " IsZeroInitializable:" << IsZeroInitializable << "\n";
OS << " BitFields:[\n";
std::vector<std::pair<unsigned, const CGBitFieldInfo*> > BFIs;
for (llvm::DenseMap<const FieldDecl*, CGBitFieldInfo>::const_iterator
it = BitFields.begin(), ie = BitFields.end();
it != ie; ++it) {
const RecordDecl *RD = it->first->getParent();
unsigned Index = 0;
for (RecordDecl::field_iterator
it2 = RD->field_begin(); *it2 != it->first; ++it2)
++Index;
BFIs.push_back(std::make_pair(Index, &it->second));
}
llvm::array_pod_sort(BFIs.begin(), BFIs.end());
for (unsigned i = 0, e = BFIs.size(); i != e; ++i) {
OS.indent(4);
BFIs[i].second->print(OS);
OS << "\n";
}
OS << "]>\n";
}
LLVM_DUMP_METHOD void CGRecordLayout::dump() const {
print(llvm::errs());
}
void CGBitFieldInfo::print(raw_ostream &OS) const {
OS << "<CGBitFieldInfo"
<< " Offset:" << Offset << " Size:" << Size << " IsSigned:" << IsSigned
<< " StorageSize:" << StorageSize
<< " StorageOffset:" << StorageOffset.getQuantity()
<< " VolatileOffset:" << VolatileOffset
<< " VolatileStorageSize:" << VolatileStorageSize
<< " VolatileStorageOffset:" << VolatileStorageOffset.getQuantity() << ">";
}
LLVM_DUMP_METHOD void CGBitFieldInfo::dump() const {
print(llvm::errs());
}