#include "clang/CodeGen/SwiftCallingConv.h"
#include "ABIInfo.h"
#include "CodeGenModule.h"
#include "TargetInfo.h"
#include "clang/Basic/TargetInfo.h"
using namespace clang;
using namespace CodeGen;
using namespace swiftcall;
static const SwiftABIInfo &getSwiftABIInfo(CodeGenModule &CGM) {
return cast<SwiftABIInfo>(CGM.getTargetCodeGenInfo().getABIInfo());
}
static bool isPowerOf2(unsigned n) {
return n == (n & -n);
}
static llvm::Type *getCommonType(llvm::Type *first, llvm::Type *second) {
assert(first != second);
if (first->isIntegerTy()) {
if (second->isPointerTy()) return first;
} else if (first->isPointerTy()) {
if (second->isIntegerTy()) return second;
if (second->isPointerTy()) return first;
} else if (auto firstVecTy = dyn_cast<llvm::VectorType>(first)) {
if (auto secondVecTy = dyn_cast<llvm::VectorType>(second)) {
if (auto commonTy = getCommonType(firstVecTy->getElementType(),
secondVecTy->getElementType())) {
return (commonTy == firstVecTy->getElementType() ? first : second);
}
}
}
return nullptr;
}
static CharUnits getTypeStoreSize(CodeGenModule &CGM, llvm::Type *type) {
return CharUnits::fromQuantity(CGM.getDataLayout().getTypeStoreSize(type));
}
static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type) {
return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(type));
}
void SwiftAggLowering::addTypedData(QualType type, CharUnits begin) {
if (auto recType = type->getAs<RecordType>()) {
addTypedData(recType->getDecl(), begin);
} else if (type->isArrayType()) {
auto arrayType = CGM.getContext().getAsConstantArrayType(type);
if (!arrayType) return;
QualType eltType = arrayType->getElementType();
auto eltSize = CGM.getContext().getTypeSizeInChars(eltType);
for (uint64_t i = 0, e = arrayType->getSize().getZExtValue(); i != e; ++i) {
addTypedData(eltType, begin + i * eltSize);
}
} else if (auto complexType = type->getAs<ComplexType>()) {
auto eltType = complexType->getElementType();
auto eltSize = CGM.getContext().getTypeSizeInChars(eltType);
auto eltLLVMType = CGM.getTypes().ConvertType(eltType);
addTypedData(eltLLVMType, begin, begin + eltSize);
addTypedData(eltLLVMType, begin + eltSize, begin + 2 * eltSize);
} else if (type->getAs<MemberPointerType>()) {
addOpaqueData(begin, begin + CGM.getContext().getTypeSizeInChars(type));
} else if (const auto *atomicType = type->getAs<AtomicType>()) {
auto valueType = atomicType->getValueType();
auto atomicSize = CGM.getContext().getTypeSizeInChars(atomicType);
auto valueSize = CGM.getContext().getTypeSizeInChars(valueType);
addTypedData(atomicType->getValueType(), begin);
auto atomicPadding = atomicSize - valueSize;
if (atomicPadding > CharUnits::Zero())
addOpaqueData(begin + valueSize, begin + atomicSize);
} else {
auto *llvmType = CGM.getTypes().ConvertType(type);
addTypedData(llvmType, begin);
}
}
void SwiftAggLowering::addTypedData(const RecordDecl *record, CharUnits begin) {
addTypedData(record, begin, CGM.getContext().getASTRecordLayout(record));
}
void SwiftAggLowering::addTypedData(const RecordDecl *record, CharUnits begin,
const ASTRecordLayout &layout) {
if (record->isUnion()) {
for (auto field : record->fields()) {
if (field->isBitField()) {
addBitFieldData(field, begin, 0);
} else {
addTypedData(field->getType(), begin);
}
}
return;
}
auto cxxRecord = dyn_cast<CXXRecordDecl>(record);
if (cxxRecord) {
if (layout.hasOwnVFPtr()) {
addTypedData(CGM.Int8PtrTy, begin);
}
for (auto &baseSpecifier : cxxRecord->bases()) {
if (baseSpecifier.isVirtual()) continue;
auto baseRecord = baseSpecifier.getType()->getAsCXXRecordDecl();
addTypedData(baseRecord, begin + layout.getBaseClassOffset(baseRecord));
}
if (layout.hasOwnVBPtr()) {
addTypedData(CGM.Int8PtrTy, begin + layout.getVBPtrOffset());
}
}
for (auto field : record->fields()) {
auto fieldOffsetInBits = layout.getFieldOffset(field->getFieldIndex());
if (field->isBitField()) {
addBitFieldData(field, begin, fieldOffsetInBits);
} else {
addTypedData(field->getType(),
begin + CGM.getContext().toCharUnitsFromBits(fieldOffsetInBits));
}
}
if (cxxRecord) {
for (auto &vbaseSpecifier : cxxRecord->vbases()) {
auto baseRecord = vbaseSpecifier.getType()->getAsCXXRecordDecl();
addTypedData(baseRecord, begin + layout.getVBaseClassOffset(baseRecord));
}
}
}
void SwiftAggLowering::addBitFieldData(const FieldDecl *bitfield,
CharUnits recordBegin,
uint64_t bitfieldBitBegin) {
assert(bitfield->isBitField());
auto &ctx = CGM.getContext();
auto width = bitfield->getBitWidthValue(ctx);
if (width == 0) return;
CharUnits bitfieldByteBegin = ctx.toCharUnitsFromBits(bitfieldBitBegin);
uint64_t bitfieldBitLast = bitfieldBitBegin + width - 1;
CharUnits bitfieldByteEnd =
ctx.toCharUnitsFromBits(bitfieldBitLast) + CharUnits::One();
addOpaqueData(recordBegin + bitfieldByteBegin,
recordBegin + bitfieldByteEnd);
}
void SwiftAggLowering::addTypedData(llvm::Type *type, CharUnits begin) {
assert(type && "didn't provide type for typed data");
addTypedData(type, begin, begin + getTypeStoreSize(CGM, type));
}
void SwiftAggLowering::addTypedData(llvm::Type *type,
CharUnits begin, CharUnits end) {
assert(type && "didn't provide type for typed data");
assert(getTypeStoreSize(CGM, type) == end - begin);
if (auto vecTy = dyn_cast<llvm::VectorType>(type)) {
SmallVector<llvm::Type*, 4> componentTys;
legalizeVectorType(CGM, end - begin, vecTy, componentTys);
assert(componentTys.size() >= 1);
for (size_t i = 0, e = componentTys.size(); i != e - 1; ++i) {
llvm::Type *componentTy = componentTys[i];
auto componentSize = getTypeStoreSize(CGM, componentTy);
assert(componentSize < end - begin);
addLegalTypedData(componentTy, begin, begin + componentSize);
begin += componentSize;
}
return addLegalTypedData(componentTys.back(), begin, end);
}
if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
if (!isLegalIntegerType(CGM, intTy))
return addOpaqueData(begin, end);
}
return addLegalTypedData(type, begin, end);
}
void SwiftAggLowering::addLegalTypedData(llvm::Type *type,
CharUnits begin, CharUnits end) {
if (!begin.isZero() && !begin.isMultipleOf(getNaturalAlignment(CGM, type))) {
if (auto vecTy = dyn_cast<llvm::VectorType>(type)) {
auto split = splitLegalVectorType(CGM, end - begin, vecTy);
auto eltTy = split.first;
auto numElts = split.second;
auto eltSize = (end - begin) / numElts;
assert(eltSize == getTypeStoreSize(CGM, eltTy));
for (size_t i = 0, e = numElts; i != e; ++i) {
addLegalTypedData(eltTy, begin, begin + eltSize);
begin += eltSize;
}
assert(begin == end);
return;
}
return addOpaqueData(begin, end);
}
addEntry(type, begin, end);
}
void SwiftAggLowering::addEntry(llvm::Type *type,
CharUnits begin, CharUnits end) {
assert((!type ||
(!isa<llvm::StructType>(type) && !isa<llvm::ArrayType>(type))) &&
"cannot add aggregate-typed data");
assert(!type || begin.isMultipleOf(getNaturalAlignment(CGM, type)));
if (Entries.empty() || Entries.back().End <= begin) {
Entries.push_back({begin, end, type});
return;
}
size_t index = Entries.size() - 1;
while (index != 0) {
if (Entries[index - 1].End <= begin) break;
--index;
}
if (Entries[index].Begin >= end) {
Entries.insert(Entries.begin() + index, {begin, end, type});
return;
}
restartAfterSplit:
if (Entries[index].Begin == begin && Entries[index].End == end) {
if (Entries[index].Type == type) return;
if (Entries[index].Type == nullptr) {
return;
} else if (type == nullptr) {
Entries[index].Type = nullptr;
return;
}
if (auto entryType = getCommonType(Entries[index].Type, type)) {
Entries[index].Type = entryType;
return;
}
Entries[index].Type = nullptr;
return;
}
if (auto vecTy = dyn_cast_or_null<llvm::VectorType>(type)) {
auto eltTy = vecTy->getElementType();
CharUnits eltSize =
(end - begin) / cast<llvm::FixedVectorType>(vecTy)->getNumElements();
assert(eltSize == getTypeStoreSize(CGM, eltTy));
for (unsigned i = 0,
e = cast<llvm::FixedVectorType>(vecTy)->getNumElements();
i != e; ++i) {
addEntry(eltTy, begin, begin + eltSize);
begin += eltSize;
}
assert(begin == end);
return;
}
if (Entries[index].Type && Entries[index].Type->isVectorTy()) {
splitVectorEntry(index);
goto restartAfterSplit;
}
Entries[index].Type = nullptr;
if (begin < Entries[index].Begin) {
Entries[index].Begin = begin;
assert(index == 0 || begin >= Entries[index - 1].End);
}
while (end > Entries[index].End) {
assert(Entries[index].Type == nullptr);
if (index == Entries.size() - 1 || end <= Entries[index + 1].Begin) {
Entries[index].End = end;
break;
}
Entries[index].End = Entries[index + 1].Begin;
index++;
if (Entries[index].Type == nullptr)
continue;
if (Entries[index].Type->isVectorTy() &&
end < Entries[index].End) {
splitVectorEntry(index);
}
Entries[index].Type = nullptr;
}
}
void SwiftAggLowering::splitVectorEntry(unsigned index) {
auto vecTy = cast<llvm::VectorType>(Entries[index].Type);
auto split = splitLegalVectorType(CGM, Entries[index].getWidth(), vecTy);
auto eltTy = split.first;
CharUnits eltSize = getTypeStoreSize(CGM, eltTy);
auto numElts = split.second;
Entries.insert(Entries.begin() + index + 1, numElts - 1, StorageEntry());
CharUnits begin = Entries[index].Begin;
for (unsigned i = 0; i != numElts; ++i) {
Entries[index].Type = eltTy;
Entries[index].Begin = begin;
Entries[index].End = begin + eltSize;
begin += eltSize;
}
}
static CharUnits getOffsetAtStartOfUnit(CharUnits offset, CharUnits unitSize) {
assert(isPowerOf2(unitSize.getQuantity()));
auto unitMask = ~(unitSize.getQuantity() - 1);
return CharUnits::fromQuantity(offset.getQuantity() & unitMask);
}
static bool areBytesInSameUnit(CharUnits first, CharUnits second,
CharUnits chunkSize) {
return getOffsetAtStartOfUnit(first, chunkSize)
== getOffsetAtStartOfUnit(second, chunkSize);
}
static bool isMergeableEntryType(llvm::Type *type) {
if (type == nullptr) return true;
return (!type->isFloatingPointTy() && !type->isVectorTy());
}
bool SwiftAggLowering::shouldMergeEntries(const StorageEntry &first,
const StorageEntry &second,
CharUnits chunkSize) {
if (!areBytesInSameUnit(first.End - CharUnits::One(), second.Begin,
chunkSize))
return false;
return (isMergeableEntryType(first.Type) &&
isMergeableEntryType(second.Type));
}
void SwiftAggLowering::finish() {
if (Entries.empty()) {
Finished = true;
return;
}
const CharUnits chunkSize = getMaximumVoluntaryIntegerSize(CGM);
bool hasOpaqueEntries = (Entries[0].Type == nullptr);
for (size_t i = 1, e = Entries.size(); i != e; ++i) {
if (shouldMergeEntries(Entries[i - 1], Entries[i], chunkSize)) {
Entries[i - 1].Type = nullptr;
Entries[i].Type = nullptr;
Entries[i - 1].End = Entries[i].Begin;
hasOpaqueEntries = true;
} else if (Entries[i].Type == nullptr) {
hasOpaqueEntries = true;
}
}
if (!hasOpaqueEntries) {
Finished = true;
return;
}
auto orig = std::move(Entries);
assert(Entries.empty());
for (size_t i = 0, e = orig.size(); i != e; ++i) {
if (orig[i].Type != nullptr) {
Entries.push_back(orig[i]);
continue;
}
auto begin = orig[i].Begin;
auto end = orig[i].End;
while (i + 1 != e &&
orig[i + 1].Type == nullptr &&
end == orig[i + 1].Begin) {
end = orig[i + 1].End;
i++;
}
do {
CharUnits localBegin = begin;
CharUnits chunkBegin = getOffsetAtStartOfUnit(localBegin, chunkSize);
CharUnits chunkEnd = chunkBegin + chunkSize;
CharUnits localEnd = std::min(end, chunkEnd);
CharUnits unitSize = CharUnits::One();
CharUnits unitBegin, unitEnd;
for (; ; unitSize *= 2) {
assert(unitSize <= chunkSize);
unitBegin = getOffsetAtStartOfUnit(localBegin, unitSize);
unitEnd = unitBegin + unitSize;
if (unitEnd >= localEnd) break;
}
auto entryTy =
llvm::IntegerType::get(CGM.getLLVMContext(),
CGM.getContext().toBits(unitSize));
Entries.push_back({unitBegin, unitEnd, entryTy});
begin = localEnd;
} while (begin != end);
}
Finished = true;
}
void SwiftAggLowering::enumerateComponents(EnumerationCallback callback) const {
assert(Finished && "haven't yet finished lowering");
for (auto &entry : Entries) {
callback(entry.Begin, entry.End, entry.Type);
}
}
std::pair<llvm::StructType*, llvm::Type*>
SwiftAggLowering::getCoerceAndExpandTypes() const {
assert(Finished && "haven't yet finished lowering");
auto &ctx = CGM.getLLVMContext();
if (Entries.empty()) {
auto type = llvm::StructType::get(ctx);
return { type, type };
}
SmallVector<llvm::Type*, 8> elts;
CharUnits lastEnd = CharUnits::Zero();
bool hasPadding = false;
bool packed = false;
for (auto &entry : Entries) {
if (entry.Begin != lastEnd) {
auto paddingSize = entry.Begin - lastEnd;
assert(!paddingSize.isNegative());
auto padding = llvm::ArrayType::get(llvm::Type::getInt8Ty(ctx),
paddingSize.getQuantity());
elts.push_back(padding);
hasPadding = true;
}
if (!packed && !entry.Begin.isMultipleOf(
CharUnits::fromQuantity(
CGM.getDataLayout().getABITypeAlignment(entry.Type))))
packed = true;
elts.push_back(entry.Type);
lastEnd = entry.Begin + getTypeAllocSize(CGM, entry.Type);
assert(entry.End <= lastEnd);
}
auto coercionType = llvm::StructType::get(ctx, elts, packed);
llvm::Type *unpaddedType = coercionType;
if (hasPadding) {
elts.clear();
for (auto &entry : Entries) {
elts.push_back(entry.Type);
}
if (elts.size() == 1) {
unpaddedType = elts[0];
} else {
unpaddedType = llvm::StructType::get(ctx, elts, false);
}
} else if (Entries.size() == 1) {
unpaddedType = Entries[0].Type;
}
return { coercionType, unpaddedType };
}
bool SwiftAggLowering::shouldPassIndirectly(bool asReturnValue) const {
assert(Finished && "haven't yet finished lowering");
if (Entries.empty()) return false;
if (Entries.size() == 1) {
return getSwiftABIInfo(CGM).shouldPassIndirectlyForSwift(
Entries.back().Type,
asReturnValue);
}
SmallVector<llvm::Type*, 8> componentTys;
componentTys.reserve(Entries.size());
for (auto &entry : Entries) {
componentTys.push_back(entry.Type);
}
return getSwiftABIInfo(CGM).shouldPassIndirectlyForSwift(componentTys,
asReturnValue);
}
bool swiftcall::shouldPassIndirectly(CodeGenModule &CGM,
ArrayRef<llvm::Type*> componentTys,
bool asReturnValue) {
return getSwiftABIInfo(CGM).shouldPassIndirectlyForSwift(componentTys,
asReturnValue);
}
CharUnits swiftcall::getMaximumVoluntaryIntegerSize(CodeGenModule &CGM) {
return CGM.getContext().toCharUnitsFromBits(
CGM.getContext().getTargetInfo().getPointerWidth(0));
}
CharUnits swiftcall::getNaturalAlignment(CodeGenModule &CGM, llvm::Type *type) {
auto size = (unsigned long long) getTypeStoreSize(CGM, type).getQuantity();
if (!isPowerOf2(size)) {
size = 1ULL << (llvm::findLastSet(size, llvm::ZB_Undefined) + 1);
}
assert(size >= CGM.getDataLayout().getABITypeAlignment(type));
return CharUnits::fromQuantity(size);
}
bool swiftcall::isLegalIntegerType(CodeGenModule &CGM,
llvm::IntegerType *intTy) {
auto size = intTy->getBitWidth();
switch (size) {
case 1:
case 8:
case 16:
case 32:
case 64:
return true;
case 128:
return CGM.getContext().getTargetInfo().hasInt128Type();
default:
return false;
}
}
bool swiftcall::isLegalVectorType(CodeGenModule &CGM, CharUnits vectorSize,
llvm::VectorType *vectorTy) {
return isLegalVectorType(
CGM, vectorSize, vectorTy->getElementType(),
cast<llvm::FixedVectorType>(vectorTy)->getNumElements());
}
bool swiftcall::isLegalVectorType(CodeGenModule &CGM, CharUnits vectorSize,
llvm::Type *eltTy, unsigned numElts) {
assert(numElts > 1 && "illegal vector length");
return getSwiftABIInfo(CGM)
.isLegalVectorTypeForSwift(vectorSize, eltTy, numElts);
}
std::pair<llvm::Type*, unsigned>
swiftcall::splitLegalVectorType(CodeGenModule &CGM, CharUnits vectorSize,
llvm::VectorType *vectorTy) {
auto numElts = cast<llvm::FixedVectorType>(vectorTy)->getNumElements();
auto eltTy = vectorTy->getElementType();
if (numElts >= 4 && isPowerOf2(numElts)) {
if (isLegalVectorType(CGM, vectorSize / 2, eltTy, numElts / 2))
return {llvm::FixedVectorType::get(eltTy, numElts / 2), 2};
}
return {eltTy, numElts};
}
void swiftcall::legalizeVectorType(CodeGenModule &CGM, CharUnits origVectorSize,
llvm::VectorType *origVectorTy,
llvm::SmallVectorImpl<llvm::Type*> &components) {
if (isLegalVectorType(CGM, origVectorSize, origVectorTy)) {
components.push_back(origVectorTy);
return;
}
auto numElts = cast<llvm::FixedVectorType>(origVectorTy)->getNumElements();
auto eltTy = origVectorTy->getElementType();
assert(numElts != 1);
unsigned logCandidateNumElts = llvm::findLastSet(numElts, llvm::ZB_Undefined);
unsigned candidateNumElts = 1U << logCandidateNumElts;
assert(candidateNumElts <= numElts && candidateNumElts * 2 > numElts);
if (candidateNumElts == numElts) {
logCandidateNumElts--;
candidateNumElts >>= 1;
}
CharUnits eltSize = (origVectorSize / numElts);
CharUnits candidateSize = eltSize * candidateNumElts;
while (logCandidateNumElts > 0) {
assert(candidateNumElts == 1U << logCandidateNumElts);
assert(candidateNumElts <= numElts);
assert(candidateSize == eltSize * candidateNumElts);
if (!isLegalVectorType(CGM, candidateSize, eltTy, candidateNumElts)) {
logCandidateNumElts--;
candidateNumElts /= 2;
candidateSize /= 2;
continue;
}
auto numVecs = numElts >> logCandidateNumElts;
components.append(numVecs,
llvm::FixedVectorType::get(eltTy, candidateNumElts));
numElts -= (numVecs << logCandidateNumElts);
if (numElts == 0) return;
if (numElts > 2 && !isPowerOf2(numElts) &&
isLegalVectorType(CGM, eltSize * numElts, eltTy, numElts)) {
components.push_back(llvm::FixedVectorType::get(eltTy, numElts));
return;
}
do {
logCandidateNumElts--;
candidateNumElts /= 2;
candidateSize /= 2;
} while (candidateNumElts > numElts);
}
components.append(numElts, eltTy);
}
bool swiftcall::mustPassRecordIndirectly(CodeGenModule &CGM,
const RecordDecl *record) {
return !record->canPassInRegisters();
}
static ABIArgInfo classifyExpandedType(SwiftAggLowering &lowering,
bool forReturn,
CharUnits alignmentForIndirect) {
if (lowering.empty()) {
return ABIArgInfo::getIgnore();
} else if (lowering.shouldPassIndirectly(forReturn)) {
return ABIArgInfo::getIndirect(alignmentForIndirect, false);
} else {
auto types = lowering.getCoerceAndExpandTypes();
return ABIArgInfo::getCoerceAndExpand(types.first, types.second);
}
}
static ABIArgInfo classifyType(CodeGenModule &CGM, CanQualType type,
bool forReturn) {
if (auto recordType = dyn_cast<RecordType>(type)) {
auto record = recordType->getDecl();
auto &layout = CGM.getContext().getASTRecordLayout(record);
if (mustPassRecordIndirectly(CGM, record))
return ABIArgInfo::getIndirect(layout.getAlignment(), false);
SwiftAggLowering lowering(CGM);
lowering.addTypedData(recordType->getDecl(), CharUnits::Zero(), layout);
lowering.finish();
return classifyExpandedType(lowering, forReturn, layout.getAlignment());
}
if (isa<ComplexType>(type)) {
return (forReturn ? ABIArgInfo::getDirect() : ABIArgInfo::getExpand());
}
if (isa<VectorType>(type)) {
SwiftAggLowering lowering(CGM);
lowering.addTypedData(type, CharUnits::Zero());
lowering.finish();
CharUnits alignment = CGM.getContext().getTypeAlignInChars(type);
return classifyExpandedType(lowering, forReturn, alignment);
}
if (type->isVoidType()) {
return ABIArgInfo::getIgnore();
}
return ABIArgInfo::getDirect();
}
ABIArgInfo swiftcall::classifyReturnType(CodeGenModule &CGM, CanQualType type) {
return classifyType(CGM, type, true);
}
ABIArgInfo swiftcall::classifyArgumentType(CodeGenModule &CGM,
CanQualType type) {
return classifyType(CGM, type, false);
}
void swiftcall::computeABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
auto &retInfo = FI.getReturnInfo();
retInfo = classifyReturnType(CGM, FI.getReturnType());
for (unsigned i = 0, e = FI.arg_size(); i != e; ++i) {
auto &argInfo = FI.arg_begin()[i];
argInfo.info = classifyArgumentType(CGM, argInfo.type);
}
}
bool swiftcall::isSwiftErrorLoweredInRegister(CodeGenModule &CGM) {
return getSwiftABIInfo(CGM).isSwiftErrorInRegister();
}