16#include "llvm/ADT/ScopeExit.h"
17#include "llvm/Support/Threading.h"
33 return *recursiveStack->second;
41 return *recursiveStackInserted.first->second;
51 return values.size() == 1 &&
52 isa<LLVM::LLVMPointerType>(values.front().
getType());
72 assert(resultType &&
"expected non-null result type");
75 resultType, inputs[0]);
97 return UnrealizedConversionCastOp::create(builder, loc, resultType, packed)
103 MemRefType resultType,
113 return UnrealizedConversionCastOp::create(builder, loc, resultType, packed)
121 :
llvmDialect(ctx->getOrLoadDialect<
LLVM::LLVMDialect>()), options(options),
122 dataLayoutAnalysis(analysis) {
123 assert(
llvmDialect &&
"LLVM IR dialect is not registered");
126 addConversion([&](ComplexType type) {
return convertComplexType(type); });
127 addConversion([&](FloatType type) {
return convertFloatType(type); });
128 addConversion([&](FunctionType type) {
return convertFunctionType(type); });
129 addConversion([&](IndexType type) {
return convertIndexType(type); });
130 addConversion([&](IntegerType type) {
return convertIntegerType(type); });
131 addConversion([&](MemRefType type) {
return convertMemRefType(type); });
134 addConversion([&](VectorType type) -> std::optional<Type> {
135 FailureOr<Type> llvmType = convertVectorType(type);
136 if (failed(llvmType))
144 addConversion([](
Type type) {
150 -> std::optional<LogicalResult> {
153 results.push_back(type);
157 if (type.isIdentified()) {
158 auto convertedType = LLVM::LLVMStructType::getIdentified(
159 type.getContext(), (
"_Converted." + type.getName()).str());
162 if (llvm::count(recursiveStack, type)) {
163 results.push_back(convertedType);
166 recursiveStack.push_back(type);
167 llvm::scope_exit popConversionCallStack(
168 [&recursiveStack]() { recursiveStack.pop_back(); });
171 convertedElemTypes.reserve(type.getBody().size());
172 if (failed(convertTypes(type.getBody(), convertedElemTypes)))
177 if (!convertedType.isInitialized()) {
179 convertedType.setBody(convertedElemTypes, type.isPacked()))) {
182 results.push_back(convertedType);
190 convertedType.isPacked() == type.isPacked()) {
191 results.push_back(convertedType);
199 convertedSubtypes.reserve(type.getBody().size());
200 if (failed(convertTypes(type.getBody(), convertedSubtypes)))
203 results.push_back(LLVM::LLVMStructType::getLiteral(
204 type.getContext(), convertedSubtypes, type.isPacked()));
207 addConversion([&](LLVM::LLVMArrayType type) -> std::optional<Type> {
208 if (
auto element = convertType(type.getElementType()))
209 return LLVM::LLVMArrayType::get(element, type.getNumElements());
212 addConversion([&](LLVM::LLVMFunctionType type) -> std::optional<Type> {
213 Type convertedResType = convertType(type.getReturnType());
214 if (!convertedResType)
218 convertedArgTypes.reserve(type.getNumParams());
219 if (failed(convertTypes(type.getParams(), convertedArgTypes)))
222 return LLVM::LLVMFunctionType::get(convertedResType, convertedArgTypes,
228 addSourceMaterialization([&](
OpBuilder &builder,
Type resultType,
230 return UnrealizedConversionCastOp::create(builder, loc, resultType, inputs)
233 addTargetMaterialization([&](
OpBuilder &builder,
Type resultType,
235 return UnrealizedConversionCastOp::create(builder, loc, resultType, inputs)
242 addSourceMaterialization([&](
OpBuilder &builder,
248 addSourceMaterialization([&](
OpBuilder &builder, MemRefType resultType,
254 addTargetMaterialization([&](
OpBuilder &builder,
Type resultType,
262 if (resultType != convertType(originalType))
264 if (
auto memrefType = dyn_cast<MemRefType>(originalType))
266 if (
auto unrankedMemrefType = dyn_cast<UnrankedMemRefType>(originalType))
273 addTypeAttributeConversion(
287 return options.dataLayout.getPointerSizeInBits(addressSpace);
290Type LLVMTypeConverter::convertIndexType(IndexType type)
const {
294Type LLVMTypeConverter::convertIntegerType(IntegerType type)
const {
295 return IntegerType::get(&
getContext(), type.getWidth());
298Type LLVMTypeConverter::convertFloatType(FloatType type)
const {
304 if (isa<Float8E5M2Type, Float8E4M3Type, Float8E4M3FNType, Float8E5M2FNUZType,
305 Float8E4M3FNUZType, Float8E4M3B11FNUZType, Float8E3M4Type,
306 Float4E2M1FNType, Float6E2M3FNType, Float6E3M2FNType,
307 Float8E8M0FNUType, Float8E5M3FNUType>(type))
308 return IntegerType::get(&
getContext(), type.getWidth());
319Type LLVMTypeConverter::convertComplexType(ComplexType type)
const {
320 auto elementType = convertType(type.getElementType());
321 return LLVM::LLVMStructType::getLiteral(&
getContext(),
322 {elementType, elementType});
327Type LLVMTypeConverter::convertFunctionType(FunctionType type)
const {
328 return LLVM::LLVMPointerType::get(type.getContext());
337 assert(
result.empty() &&
"Unexpected non-empty output");
338 result.resize(funcOp.getNumArguments(), std::nullopt);
339 bool foundByValByRefAttrs =
false;
340 for (
int argIdx : llvm::seq(funcOp.getNumArguments())) {
342 if ((namedAttr.getName() == LLVM::LLVMDialect::getByValAttrName() ||
343 namedAttr.getName() == LLVM::LLVMDialect::getByRefAttrName())) {
344 foundByValByRefAttrs =
true;
345 result[argIdx] = namedAttr;
351 if (!foundByValByRefAttrs)
363Type LLVMTypeConverter::convertFunctionSignatureImpl(
364 FunctionType funcTy,
bool isVariadic,
bool useBarePtrCallConv,
365 LLVMTypeConverter::SignatureConversion &
result,
366 SmallVectorImpl<std::optional<NamedAttribute>> *byValRefNonPtrAttrs)
const {
368 useBarePtrCallConv = useBarePtrCallConv || options.useBarePtrCallConv;
373 for (
auto [idx, type] : llvm::enumerate(funcTy.getInputs())) {
374 SmallVector<Type, 8> converted;
375 if (
failed(funcArgConverter(*
this, type, converted)))
380 if (byValRefNonPtrAttrs !=
nullptr && !byValRefNonPtrAttrs->empty() &&
381 converted.size() == 1 && (*byValRefNonPtrAttrs)[idx].has_value()) {
384 if (isa<LLVM::LLVMPointerType>(converted[0]))
385 (*byValRefNonPtrAttrs)[idx] = std::nullopt;
387 converted[0] = LLVM::LLVMPointerType::get(&
getContext());
390 result.addInputs(idx, converted);
397 funcTy.getNumResults() == 0
402 return LLVM::LLVMFunctionType::get(resultType,
result.getConvertedTypes(),
407 FunctionType funcTy,
bool isVariadic,
bool useBarePtrCallConv,
408 LLVMTypeConverter::SignatureConversion &
result)
const {
409 return convertFunctionSignatureImpl(funcTy, isVariadic, useBarePtrCallConv,
415 FunctionOpInterface funcOp,
bool isVariadic,
bool useBarePtrCallConv,
416 LLVMTypeConverter::SignatureConversion &
result,
417 SmallVectorImpl<std::optional<NamedAttribute>> &byValRefNonPtrAttrs)
const {
422 auto funcTy = cast<FunctionType>(funcOp.getFunctionType());
423 return convertFunctionSignatureImpl(funcTy, isVariadic, useBarePtrCallConv,
424 result, &byValRefNonPtrAttrs);
429std::pair<LLVM::LLVMFunctionType, LLVM::LLVMStructType>
433 Type resultType = type.getNumResults() == 0
439 auto ptrType = LLVM::LLVMPointerType::get(type.getContext());
440 auto structType = dyn_cast<LLVM::LLVMStructType>(resultType);
444 inputs.push_back(ptrType);
445 resultType = LLVM::LLVMVoidType::get(&
getContext());
448 for (
Type t : type.getInputs()) {
449 auto converted = convertType(t);
452 if (isa<MemRefType, UnrankedMemRefType>(t))
454 inputs.push_back(converted);
457 return {LLVM::LLVMFunctionType::get(resultType, inputs), structType};
490 bool unpackAggregates)
const {
491 if (!type.isStrided()) {
493 UnknownLoc::get(type.getContext()),
494 "conversion to strided form failed either due to non-strided layout "
495 "maps (which should have been normalized away) or other reasons");
499 Type elementType = convertType(type.getElementType());
504 if (failed(addressSpace)) {
505 emitError(UnknownLoc::get(type.getContext()),
506 "conversion of memref memory space ")
507 << type.getMemorySpace()
508 <<
" to integer address space "
509 "failed. Consider adding memory space conversions.";
512 auto ptrTy = LLVM::LLVMPointerType::get(type.getContext(), *addressSpace);
517 auto rank = type.getRank();
521 if (unpackAggregates)
522 results.insert(results.end(), 2 * rank, indexTy);
524 results.insert(results.end(), 2, LLVM::LLVMArrayType::get(indexTy, rank));
539Type LLVMTypeConverter::convertMemRefType(MemRefType type)
const {
546 return LLVM::LLVMStructType::getLiteral(&
getContext(), types);
569Type LLVMTypeConverter::convertUnrankedMemRefType(
571 if (!convertType(type.getElementType()))
573 return LLVM::LLVMStructType::getLiteral(&
getContext(),
581 std::optional<Attribute> converted =
587 if (
auto explicitSpace = dyn_cast_if_present<IntegerAttr>(*converted)) {
588 if (explicitSpace.getType().isIndex() ||
589 explicitSpace.getType().isSignlessInteger())
590 return explicitSpace.getInt();
597 if (isa<UnrankedMemRefType>(type))
603 auto memrefTy = cast<MemRefType>(type);
604 if (!memrefTy.hasStaticShape())
609 if (failed(memrefTy.getStridesAndOffset(strides, offset)))
613 if (ShapedType::isDynamic(stride))
616 return ShapedType::isStatic(offset);
629 return LLVM::LLVMPointerType::get(type.
getContext(), *addressSpace);
639FailureOr<Type> LLVMTypeConverter::convertVectorType(VectorType type)
const {
640 auto elementType = convertType(type.getElementType());
643 if (type.getShape().empty())
644 return VectorType::get({1}, elementType);
645 Type vectorType = VectorType::get(type.getShape().back(), elementType,
646 type.getScalableDims().back());
648 "expected vector type compatible with the LLVM dialect");
652 if (llvm::is_contained(type.getScalableDims().drop_back(),
true))
654 auto shape = type.getShape();
655 for (
int i = shape.size() - 2; i >= 0; --i)
656 vectorType = LLVM::LLVMArrayType::get(vectorType, shape[i]);
667 if (useBarePtrCallConv) {
668 if (
auto memrefTy = dyn_cast<BaseMemRefType>(type)) {
669 Type converted = convertMemRefToBarePtr(memrefTy);
672 result.push_back(converted);
677 return convertType(type,
result);
685 assert(!types.empty() &&
"expected non-empty list of type");
686 if (types.size() == 1)
687 return convertType(types[0]);
690 resultTypes.reserve(types.size());
691 for (
Type type : types) {
692 Type converted = convertType(type);
695 resultTypes.push_back(converted);
698 return LLVM::LLVMStructType::getLiteral(&
getContext(), resultTypes);
706 TypeRange types,
bool useBarePtrCallConv,
708 int64_t *numConvertedTypes)
const {
709 assert(!types.empty() &&
"expected non-empty list of type");
710 assert((!groupedTypes || groupedTypes->empty()) &&
711 "expected groupedTypes to be empty");
713 useBarePtrCallConv |= options.useBarePtrCallConv;
715 resultTypes.reserve(types.size());
716 size_t sizeBefore = 0;
717 for (
auto t : types) {
723 llvm::append_range(group,
ArrayRef(resultTypes).drop_front(sizeBefore));
725 sizeBefore = resultTypes.size();
728 if (numConvertedTypes)
729 *numConvertedTypes = resultTypes.size();
730 if (resultTypes.size() == 1)
731 return resultTypes.front();
732 if (resultTypes.empty())
734 return LLVM::LLVMStructType::getLiteral(&
getContext(), resultTypes);
741 auto ptrType = LLVM::LLVMPointerType::get(builder.
getContext());
742 Value one = LLVM::ConstantOp::create(builder, loc, builder.
getI64Type(),
745 LLVM::AllocaOp::create(builder, loc, ptrType, operand.
getType(), one);
747 LLVM::StoreOp::create(builder, loc, operand, allocated);
753 OpBuilder &builder,
bool useBarePtrCallConv)
const {
755 for (
size_t i = 0, e = adaptorOperands.size(); i < e; i++)
756 ranges.push_back(adaptorOperands.slice(i, 1));
757 return promoteOperands(loc, opOperands, ranges, builder, useBarePtrCallConv);
762 OpBuilder &builder,
bool useBarePtrCallConv)
const {
764 promotedOperands.reserve(adaptorOperands.size());
765 useBarePtrCallConv |= options.useBarePtrCallConv;
766 for (
auto [operand, llvmOperand] :
767 llvm::zip_equal(opOperands, adaptorOperands)) {
768 if (useBarePtrCallConv) {
771 if (isa<MemRefType>(operand.getType())) {
772 assert(llvmOperand.size() == 1 &&
"Expected a single operand");
774 promotedOperands.push_back(desc.
alignedPtr(builder, loc));
777 if (isa<UnrankedMemRefType>(operand.getType())) {
778 llvm_unreachable(
"Unranked memrefs are not supported");
781 if (isa<UnrankedMemRefType>(operand.getType())) {
782 assert(llvmOperand.size() == 1 &&
"Expected a single operand");
787 if (
auto memrefType = dyn_cast<MemRefType>(operand.getType())) {
788 assert(llvmOperand.size() == 1 &&
"Expected a single operand");
795 llvm::append_range(promotedOperands, llvmOperand);
797 return promotedOperands;
807 if (
auto memref = dyn_cast<MemRefType>(type)) {
812 if (converted.empty())
814 result.append(converted.begin(), converted.end());
817 if (isa<UnrankedMemRefType>(type)) {
819 if (converted.empty())
821 result.append(converted.begin(), converted.end());
824 return converter.convertType(type,
result);
static void filterByValRefArgAttrs(FunctionOpInterface funcOp, SmallVectorImpl< std::optional< NamedAttribute > > &result)
Returns the llvm.byval or llvm.byref attributes that are present in the function arguments.
static Value packRankedMemRefDesc(OpBuilder &builder, MemRefType resultType, ValueRange inputs, Location loc, const LLVMTypeConverter &converter)
Pack SSA values into a ranked memref descriptor struct.
static Value unrankedMemRefMaterialization(OpBuilder &builder, UnrankedMemRefType resultType, ValueRange inputs, Location loc, const LLVMTypeConverter &converter)
MemRef descriptor elements -> UnrankedMemRefType.
static Value packUnrankedMemRefDesc(OpBuilder &builder, UnrankedMemRefType resultType, ValueRange inputs, Location loc, const LLVMTypeConverter &converter)
Pack SSA values into an unranked memref descriptor struct.
static Value rankedMemRefMaterialization(OpBuilder &builder, MemRefType resultType, ValueRange inputs, Location loc, const LLVMTypeConverter &converter)
MemRef descriptor elements -> MemRefType.
static bool isBarePointer(ValueRange values)
Helper function that checks if the given value range is a bare pointer.
This class provides a shared interface for ranked and unranked memref types.
Attribute getMemorySpace() const
Returns the memory space in which data referred to by this memref resides.
Type getElementType() const
Returns the element type of this memref type.
IntegerAttr getI64IntegerAttr(int64_t value)
MLIRContext * getContext() const
Stores data layout objects for each operation that specifies the data layout above and below the give...
The main mechanism for performing data layout queries.
llvm::TypeSize getTypeSize(Type t) const
Returns the size of the given type in the current scope.
Conversion from types to the LLVM IR dialect.
LLVM::LLVMDialect * llvmDialect
Pointer to the LLVM dialect.
llvm::sys::SmartRWMutex< true > callStackMutex
Type packOperationResults(TypeRange types) const
Convert a non-empty list of types of values produced by an operation into an LLVM-compatible type.
SmallVector< Value, 4 > promoteOperands(Location loc, ValueRange opOperands, ArrayRef< ValueRange > adaptorOperands, OpBuilder &builder, bool useBarePtrCallConv=false) const
Promote the LLVM representation of all operands including promoting MemRef descriptors to stack and u...
Type packFunctionResults(TypeRange types, bool useBarePointerCallConv=false, SmallVector< SmallVector< Type > > *groupedTypes=nullptr, int64_t *numConvertedTypes=nullptr) const
Convert a non-empty list of types to be returned from a function into an LLVM-compatible type.
LogicalResult convertCallingConventionType(Type type, SmallVectorImpl< Type > &result, bool useBarePointerCallConv=false) const
Convert a type in the context of the default or bare pointer calling convention.
Type convertFunctionSignature(FunctionType funcTy, bool isVariadic, bool useBarePtrCallConv, SignatureConversion &result) const
Convert a function type.
unsigned getUnrankedMemRefDescriptorSize(UnrankedMemRefType type, const DataLayout &layout) const
Returns the size of the unranked memref descriptor object in bytes.
SmallVector< Type, 5 > getMemRefDescriptorFields(MemRefType type, bool unpackAggregates) const
Convert a memref type into a list of LLVM IR types that will form the memref descriptor.
DenseMap< uint64_t, std::unique_ptr< SmallVector< Type > > > conversionCallStack
SmallVector< Type > & getCurrentThreadRecursiveStack()
Value promoteOneMemRefDescriptor(Location loc, Value operand, OpBuilder &builder) const
Promote the LLVM struct representation of one MemRef descriptor to stack and use pointer to struct to...
LLVMTypeConverter(MLIRContext *ctx, const DataLayoutAnalysis *analysis=nullptr)
Create an LLVMTypeConverter using the default LowerToLLVMOptions.
unsigned getPointerBitwidth(unsigned addressSpace=0) const
Gets the pointer bitwidth.
SmallVector< Type, 2 > getUnrankedMemRefDescriptorFields() const
Convert an unranked memref type into a list of non-aggregate LLVM IR types that will form the unranke...
FailureOr< unsigned > getMemRefAddressSpace(BaseMemRefType type) const
Return the LLVM address space corresponding to the memory space of the memref type type or failure if...
LLVM::LLVMDialect * getDialect() const
Returns the LLVM dialect.
static bool canConvertToBarePtr(BaseMemRefType type)
Check if a memref type can be converted to a bare pointer.
MLIRContext & getContext() const
Returns the MLIR context.
unsigned getMemRefDescriptorSize(MemRefType type, const DataLayout &layout) const
Returns the size of the memref descriptor object in bytes.
std::pair< LLVM::LLVMFunctionType, LLVM::LLVMStructType > convertFunctionTypeCWrapper(FunctionType type) const
Converts the function type to a C-compatible format, in particular using pointers to memref descripto...
unsigned getIndexTypeBitwidth() const
Gets the bitwidth of the index type when converted to LLVM.
Type getIndexType() const
Gets the LLVM representation of the index type.
friend LogicalResult structFuncArgTypeConverter(const LLVMTypeConverter &converter, Type type, SmallVectorImpl< Type > &result)
Give structFuncArgTypeConverter access to memref-specific functions.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Options to control the LLVM lowering.
MLIRContext is the top-level object for a collection of MLIR operations.
Helper class to produce LLVM dialect operations extracting or inserting elements of a MemRef descript...
Value alignedPtr(OpBuilder &builder, Location loc)
Builds IR extracting the aligned pointer from the descriptor.
static MemRefDescriptor fromStaticShape(OpBuilder &builder, Location loc, const LLVMTypeConverter &typeConverter, MemRefType type, Value memory)
Builds IR creating a MemRef descriptor that represents type and populates it with static shape and st...
static void unpack(OpBuilder &builder, Location loc, Value packed, MemRefType type, SmallVectorImpl< Value > &results)
Builds IR extracting individual elements of a MemRef descriptor structure and returning them as resul...
static Value pack(OpBuilder &builder, Location loc, const LLVMTypeConverter &converter, MemRefType type, ValueRange values)
Builds IR populating a MemRef descriptor structure from a list of individual values composing that de...
NamedAttribute represents a combination of a name and an Attribute value.
This class helps build Operations.
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
static Value pack(OpBuilder &builder, Location loc, const LLVMTypeConverter &converter, UnrankedMemRefType type, ValueRange values)
Builds IR populating an unranked MemRef descriptor structure from a list of individual constituent va...
static void unpack(OpBuilder &builder, Location loc, Value packed, SmallVectorImpl< Value > &results)
Builds IR extracting individual elements that compose an unranked memref descriptor and returns them ...
This class provides an abstraction over the different types of ranges over Values.
type_range getType() const
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
bool isCompatibleVectorType(Type type)
Returns true if the given type is a vector type compatible with the LLVM dialect.
bool isCompatibleType(Type type)
Returns true if the given type is compatible with the LLVM dialect.
Include the generated interface declarations.
LogicalResult barePtrFuncArgTypeConverter(const LLVMTypeConverter &converter, Type type, SmallVectorImpl< Type > &result)
Callback to convert function argument types.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
LogicalResult structFuncArgTypeConverter(const LLVMTypeConverter &converter, Type type, SmallVectorImpl< Type > &result)
Callback to convert function argument types.