2019-05-14 15:03:48 -07:00
|
|
|
//===- ModuleTranslation.cpp - MLIR to LLVM conversion --------------------===//
|
2019-04-30 06:08:21 -07:00
|
|
|
//
|
2020-01-26 03:58:30 +00:00
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
2019-12-23 09:35:36 -08:00
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
2019-04-30 06:08:21 -07:00
|
|
|
//
|
2019-12-23 09:35:36 -08:00
|
|
|
//===----------------------------------------------------------------------===//
|
2019-04-30 06:08:21 -07:00
|
|
|
//
|
|
|
|
|
// This file implements the translation between an MLIR LLVM dialect module and
|
|
|
|
|
// the corresponding LLVMIR module. It only handles core LLVM IR operations.
|
|
|
|
|
//
|
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
|
|
#include "mlir/Target/LLVMIR/ModuleTranslation.h"
|
|
|
|
|
|
2020-02-05 17:10:55 -08:00
|
|
|
#include "DebugTranslation.h"
|
2022-03-01 18:21:38 +01:00
|
|
|
#include "mlir/Dialect/DLTI/DLTI.h"
|
2019-08-19 11:00:47 -07:00
|
|
|
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
|
2021-02-16 17:36:45 +01:00
|
|
|
#include "mlir/Dialect/LLVMIR/Transforms/LegalizeForExport.h"
|
2020-03-04 23:36:21 +00:00
|
|
|
#include "mlir/Dialect/OpenMP/OpenMPDialect.h"
|
2019-04-30 06:08:21 -07:00
|
|
|
#include "mlir/IR/Attributes.h"
|
2020-11-19 10:43:12 -08:00
|
|
|
#include "mlir/IR/BuiltinOps.h"
|
2020-12-03 17:22:29 -08:00
|
|
|
#include "mlir/IR/BuiltinTypes.h"
|
2020-10-02 13:17:26 +03:00
|
|
|
#include "mlir/IR/RegionGraphTraits.h"
|
2019-04-30 06:08:21 -07:00
|
|
|
#include "mlir/Support/LLVM.h"
|
2021-02-11 15:01:33 +01:00
|
|
|
#include "mlir/Target/LLVMIR/LLVMTranslationInterface.h"
|
2021-06-22 13:57:04 -04:00
|
|
|
#include "mlir/Target/LLVMIR/TypeToLLVM.h"
|
2020-04-14 14:53:50 -07:00
|
|
|
#include "llvm/ADT/TypeSwitch.h"
|
2019-04-30 06:08:21 -07:00
|
|
|
|
2020-10-02 13:17:26 +03:00
|
|
|
#include "llvm/ADT/PostOrderIterator.h"
|
2019-04-30 06:08:21 -07:00
|
|
|
#include "llvm/ADT/SetVector.h"
|
2020-03-04 23:36:21 +00:00
|
|
|
#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
|
2019-04-30 06:08:21 -07:00
|
|
|
#include "llvm/IR/BasicBlock.h"
|
2020-07-13 23:13:04 +01:00
|
|
|
#include "llvm/IR/CFG.h"
|
2019-04-30 06:08:21 -07:00
|
|
|
#include "llvm/IR/Constants.h"
|
|
|
|
|
#include "llvm/IR/DerivedTypes.h"
|
|
|
|
|
#include "llvm/IR/IRBuilder.h"
|
2020-11-27 22:02:23 +00:00
|
|
|
#include "llvm/IR/InlineAsm.h"
|
2021-05-06 12:05:07 +05:30
|
|
|
#include "llvm/IR/IntrinsicsNVPTX.h"
|
2019-04-30 06:08:21 -07:00
|
|
|
#include "llvm/IR/LLVMContext.h"
|
2020-07-24 09:41:22 +03:00
|
|
|
#include "llvm/IR/MDBuilder.h"
|
2019-04-30 06:08:21 -07:00
|
|
|
#include "llvm/IR/Module.h"
|
2021-02-16 17:36:45 +01:00
|
|
|
#include "llvm/IR/Verifier.h"
|
2020-07-13 23:13:04 +01:00
|
|
|
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
|
2019-04-30 06:08:21 -07:00
|
|
|
#include "llvm/Transforms/Utils/Cloning.h"
|
2021-10-20 15:14:54 +05:30
|
|
|
#include "llvm/Transforms/Utils/ModuleUtils.h"
|
2023-01-13 21:05:06 -08:00
|
|
|
#include <optional>
|
2019-04-30 06:08:21 -07:00
|
|
|
|
2019-12-18 10:46:16 -08:00
|
|
|
using namespace mlir;
|
|
|
|
|
using namespace mlir::LLVM;
|
2020-02-05 17:10:55 -08:00
|
|
|
using namespace mlir::LLVM::detail;
|
2019-04-30 06:08:21 -07:00
|
|
|
|
2020-01-27 14:49:34 +01:00
|
|
|
#include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
|
|
|
|
|
|
2022-03-01 18:21:38 +01:00
|
|
|
/// Translates the given data layout spec attribute to the LLVM IR data layout.
|
2022-09-07 12:42:52 -04:00
|
|
|
/// Only integer, float, pointer and endianness entries are currently supported.
|
|
|
|
|
static FailureOr<llvm::DataLayout>
|
2022-03-01 18:21:38 +01:00
|
|
|
translateDataLayout(DataLayoutSpecInterface attribute,
|
|
|
|
|
const DataLayout &dataLayout,
|
2023-01-14 01:25:58 -08:00
|
|
|
std::optional<Location> loc = std::nullopt) {
|
2022-03-01 18:21:38 +01:00
|
|
|
if (!loc)
|
|
|
|
|
loc = UnknownLoc::get(attribute.getContext());
|
|
|
|
|
|
|
|
|
|
// Translate the endianness attribute.
|
|
|
|
|
std::string llvmDataLayout;
|
|
|
|
|
llvm::raw_string_ostream layoutStream(llvmDataLayout);
|
|
|
|
|
for (DataLayoutEntryInterface entry : attribute.getEntries()) {
|
|
|
|
|
auto key = entry.getKey().dyn_cast<StringAttr>();
|
|
|
|
|
if (!key)
|
|
|
|
|
continue;
|
|
|
|
|
if (key.getValue() == DLTIDialect::kDataLayoutEndiannessKey) {
|
|
|
|
|
auto value = entry.getValue().cast<StringAttr>();
|
|
|
|
|
bool isLittleEndian =
|
|
|
|
|
value.getValue() == DLTIDialect::kDataLayoutEndiannessLittle;
|
|
|
|
|
layoutStream << (isLittleEndian ? "e" : "E");
|
|
|
|
|
layoutStream.flush();
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
emitError(*loc) << "unsupported data layout key " << key;
|
|
|
|
|
return failure();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Go through the list of entries to check which types are explicitly
|
2022-09-07 12:42:52 -04:00
|
|
|
// specified in entries. Where possible, data layout queries are used instead
|
|
|
|
|
// of directly inspecting the entries.
|
2022-03-01 18:21:38 +01:00
|
|
|
for (DataLayoutEntryInterface entry : attribute.getEntries()) {
|
|
|
|
|
auto type = entry.getKey().dyn_cast<Type>();
|
|
|
|
|
if (!type)
|
|
|
|
|
continue;
|
2022-03-02 16:56:21 +01:00
|
|
|
// Data layout for the index type is irrelevant at this point.
|
|
|
|
|
if (type.isa<IndexType>())
|
|
|
|
|
continue;
|
2022-09-07 12:42:52 -04:00
|
|
|
layoutStream << "-";
|
|
|
|
|
LogicalResult result =
|
|
|
|
|
llvm::TypeSwitch<Type, LogicalResult>(type)
|
|
|
|
|
.Case<IntegerType, Float16Type, Float32Type, Float64Type,
|
|
|
|
|
Float80Type, Float128Type>([&](Type type) -> LogicalResult {
|
|
|
|
|
if (auto intType = type.dyn_cast<IntegerType>()) {
|
|
|
|
|
if (intType.getSignedness() != IntegerType::Signless)
|
|
|
|
|
return emitError(*loc)
|
|
|
|
|
<< "unsupported data layout for non-signless integer "
|
|
|
|
|
<< intType;
|
|
|
|
|
layoutStream << "i";
|
|
|
|
|
} else {
|
|
|
|
|
layoutStream << "f";
|
|
|
|
|
}
|
|
|
|
|
unsigned size = dataLayout.getTypeSizeInBits(type);
|
|
|
|
|
unsigned abi = dataLayout.getTypeABIAlignment(type) * 8u;
|
|
|
|
|
unsigned preferred =
|
|
|
|
|
dataLayout.getTypePreferredAlignment(type) * 8u;
|
|
|
|
|
layoutStream << size << ":" << abi;
|
|
|
|
|
if (abi != preferred)
|
|
|
|
|
layoutStream << ":" << preferred;
|
|
|
|
|
return success();
|
|
|
|
|
})
|
|
|
|
|
.Case([&](LLVMPointerType ptrType) {
|
|
|
|
|
layoutStream << "p" << ptrType.getAddressSpace() << ":";
|
|
|
|
|
unsigned size = dataLayout.getTypeSizeInBits(type);
|
|
|
|
|
unsigned abi = dataLayout.getTypeABIAlignment(type) * 8u;
|
|
|
|
|
unsigned preferred =
|
|
|
|
|
dataLayout.getTypePreferredAlignment(type) * 8u;
|
|
|
|
|
layoutStream << size << ":" << abi << ":" << preferred;
|
2023-01-14 01:25:58 -08:00
|
|
|
if (std::optional<unsigned> index = extractPointerSpecValue(
|
2022-09-07 12:42:52 -04:00
|
|
|
entry.getValue(), PtrDLEntryPos::Index))
|
|
|
|
|
layoutStream << ":" << *index;
|
|
|
|
|
return success();
|
|
|
|
|
})
|
|
|
|
|
.Default([loc](Type type) {
|
|
|
|
|
return emitError(*loc)
|
|
|
|
|
<< "unsupported type in data layout: " << type;
|
2022-03-01 18:21:38 +01:00
|
|
|
});
|
2022-09-07 12:42:52 -04:00
|
|
|
if (failed(result))
|
2022-03-01 18:21:38 +01:00
|
|
|
return failure();
|
|
|
|
|
}
|
|
|
|
|
layoutStream.flush();
|
|
|
|
|
StringRef layoutSpec(llvmDataLayout);
|
|
|
|
|
if (layoutSpec.startswith("-"))
|
|
|
|
|
layoutSpec = layoutSpec.drop_front();
|
|
|
|
|
|
|
|
|
|
return llvm::DataLayout(layoutSpec);
|
|
|
|
|
}
|
|
|
|
|
|
2020-01-17 18:01:05 +01:00
|
|
|
/// Builds a constant of a sequential LLVM type `type`, potentially containing
|
|
|
|
|
/// other sequential types recursively, from the individual constant values
|
|
|
|
|
/// provided in `constants`. `shape` contains the number of elements in nested
|
|
|
|
|
/// sequential types. Reports errors at `loc` and returns nullptr on error.
|
2020-01-16 16:21:14 +01:00
|
|
|
static llvm::Constant *
|
|
|
|
|
buildSequentialConstant(ArrayRef<llvm::Constant *> &constants,
|
|
|
|
|
ArrayRef<int64_t> shape, llvm::Type *type,
|
|
|
|
|
Location loc) {
|
|
|
|
|
if (shape.empty()) {
|
|
|
|
|
llvm::Constant *result = constants.front();
|
|
|
|
|
constants = constants.drop_front();
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
|
2020-04-06 17:03:49 -07:00
|
|
|
llvm::Type *elementType;
|
|
|
|
|
if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
|
|
|
|
|
elementType = arrayTy->getElementType();
|
|
|
|
|
} else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
|
|
|
|
|
elementType = vectorTy->getElementType();
|
|
|
|
|
} else {
|
2020-01-16 16:21:14 +01:00
|
|
|
emitError(loc) << "expected sequential LLVM types wrapping a scalar";
|
|
|
|
|
return nullptr;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
SmallVector<llvm::Constant *, 8> nested;
|
|
|
|
|
nested.reserve(shape.front());
|
|
|
|
|
for (int64_t i = 0; i < shape.front(); ++i) {
|
|
|
|
|
nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
|
|
|
|
|
elementType, loc));
|
|
|
|
|
if (!nested.back())
|
|
|
|
|
return nullptr;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (shape.size() == 1 && type->isVectorTy())
|
|
|
|
|
return llvm::ConstantVector::get(nested);
|
|
|
|
|
return llvm::ConstantArray::get(
|
|
|
|
|
llvm::ArrayType::get(elementType, shape.front()), nested);
|
|
|
|
|
}
|
|
|
|
|
|
2020-01-20 03:14:37 +00:00
|
|
|
/// Returns the first non-sequential type nested in sequential types.
|
2020-01-16 16:21:14 +01:00
|
|
|
static llvm::Type *getInnermostElementType(llvm::Type *type) {
|
2020-04-06 17:03:49 -07:00
|
|
|
do {
|
|
|
|
|
if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
|
|
|
|
|
type = arrayTy->getElementType();
|
|
|
|
|
} else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
|
|
|
|
|
type = vectorTy->getElementType();
|
|
|
|
|
} else {
|
|
|
|
|
return type;
|
|
|
|
|
}
|
2021-02-10 19:21:45 +01:00
|
|
|
} while (true);
|
2020-01-16 16:21:14 +01:00
|
|
|
}
|
|
|
|
|
|
2021-09-02 15:01:19 +02:00
|
|
|
/// Convert a dense elements attribute to an LLVM IR constant using its raw data
|
|
|
|
|
/// storage if possible. This supports elements attributes of tensor or vector
|
|
|
|
|
/// type and avoids constructing separate objects for individual values of the
|
|
|
|
|
/// innermost dimension. Constants for other dimensions are still constructed
|
|
|
|
|
/// recursively. Returns null if constructing from raw data is not supported for
|
|
|
|
|
/// this type, e.g., element type is not a power-of-two-sized primitive. Reports
|
|
|
|
|
/// other errors at `loc`.
|
|
|
|
|
static llvm::Constant *
|
|
|
|
|
convertDenseElementsAttr(Location loc, DenseElementsAttr denseElementsAttr,
|
|
|
|
|
llvm::Type *llvmType,
|
|
|
|
|
const ModuleTranslation &moduleTranslation) {
|
|
|
|
|
if (!denseElementsAttr)
|
|
|
|
|
return nullptr;
|
|
|
|
|
|
|
|
|
|
llvm::Type *innermostLLVMType = getInnermostElementType(llvmType);
|
|
|
|
|
if (!llvm::ConstantDataSequential::isElementTypeCompatible(innermostLLVMType))
|
|
|
|
|
return nullptr;
|
|
|
|
|
|
2021-10-21 11:57:16 +02:00
|
|
|
ShapedType type = denseElementsAttr.getType();
|
|
|
|
|
if (type.getNumElements() == 0)
|
|
|
|
|
return nullptr;
|
|
|
|
|
|
2021-09-02 15:01:19 +02:00
|
|
|
// Compute the shape of all dimensions but the innermost. Note that the
|
|
|
|
|
// innermost dimension may be that of the vector element type.
|
|
|
|
|
bool hasVectorElementType = type.getElementType().isa<VectorType>();
|
|
|
|
|
unsigned numAggregates =
|
|
|
|
|
denseElementsAttr.getNumElements() /
|
|
|
|
|
(hasVectorElementType ? 1
|
|
|
|
|
: denseElementsAttr.getType().getShape().back());
|
|
|
|
|
ArrayRef<int64_t> outerShape = type.getShape();
|
|
|
|
|
if (!hasVectorElementType)
|
|
|
|
|
outerShape = outerShape.drop_back();
|
|
|
|
|
|
|
|
|
|
// Handle the case of vector splat, LLVM has special support for it.
|
|
|
|
|
if (denseElementsAttr.isSplat() &&
|
|
|
|
|
(type.isa<VectorType>() || hasVectorElementType)) {
|
|
|
|
|
llvm::Constant *splatValue = LLVM::detail::getLLVMConstant(
|
2021-11-09 01:40:17 +00:00
|
|
|
innermostLLVMType, denseElementsAttr.getSplatValue<Attribute>(), loc,
|
2022-05-11 15:12:21 +02:00
|
|
|
moduleTranslation);
|
2021-09-02 15:01:19 +02:00
|
|
|
llvm::Constant *splatVector =
|
|
|
|
|
llvm::ConstantDataVector::getSplat(0, splatValue);
|
|
|
|
|
SmallVector<llvm::Constant *> constants(numAggregates, splatVector);
|
|
|
|
|
ArrayRef<llvm::Constant *> constantsRef = constants;
|
|
|
|
|
return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
|
|
|
|
|
}
|
|
|
|
|
if (denseElementsAttr.isSplat())
|
|
|
|
|
return nullptr;
|
|
|
|
|
|
|
|
|
|
// In case of non-splat, create a constructor for the innermost constant from
|
|
|
|
|
// a piece of raw data.
|
|
|
|
|
std::function<llvm::Constant *(StringRef)> buildCstData;
|
|
|
|
|
if (type.isa<TensorType>()) {
|
|
|
|
|
auto vectorElementType = type.getElementType().dyn_cast<VectorType>();
|
|
|
|
|
if (vectorElementType && vectorElementType.getRank() == 1) {
|
|
|
|
|
buildCstData = [&](StringRef data) {
|
|
|
|
|
return llvm::ConstantDataVector::getRaw(
|
|
|
|
|
data, vectorElementType.getShape().back(), innermostLLVMType);
|
|
|
|
|
};
|
|
|
|
|
} else if (!vectorElementType) {
|
|
|
|
|
buildCstData = [&](StringRef data) {
|
|
|
|
|
return llvm::ConstantDataArray::getRaw(data, type.getShape().back(),
|
|
|
|
|
innermostLLVMType);
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
} else if (type.isa<VectorType>()) {
|
|
|
|
|
buildCstData = [&](StringRef data) {
|
|
|
|
|
return llvm::ConstantDataVector::getRaw(data, type.getShape().back(),
|
|
|
|
|
innermostLLVMType);
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
if (!buildCstData)
|
|
|
|
|
return nullptr;
|
|
|
|
|
|
|
|
|
|
// Create innermost constants and defer to the default constant creation
|
|
|
|
|
// mechanism for other dimensions.
|
|
|
|
|
SmallVector<llvm::Constant *> constants;
|
|
|
|
|
unsigned aggregateSize = denseElementsAttr.getType().getShape().back() *
|
|
|
|
|
(innermostLLVMType->getScalarSizeInBits() / 8);
|
|
|
|
|
constants.reserve(numAggregates);
|
|
|
|
|
for (unsigned i = 0; i < numAggregates; ++i) {
|
|
|
|
|
StringRef data(denseElementsAttr.getRawData().data() + i * aggregateSize,
|
|
|
|
|
aggregateSize);
|
|
|
|
|
constants.push_back(buildCstData(data));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ArrayRef<llvm::Constant *> constantsRef = constants;
|
|
|
|
|
return buildSequentialConstant(constantsRef, outerShape, llvmType, loc);
|
|
|
|
|
}
|
|
|
|
|
|
2019-12-18 10:46:16 -08:00
|
|
|
/// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
|
|
|
|
|
/// This currently supports integer, floating point, splat and dense element
|
2021-05-14 13:00:38 +02:00
|
|
|
/// attributes and combinations thereof. Also, an array attribute with two
|
|
|
|
|
/// elements is supported to represent a complex constant. In case of error,
|
|
|
|
|
/// report it to `loc` and return nullptr.
|
2021-02-12 12:53:27 +01:00
|
|
|
llvm::Constant *mlir::LLVM::detail::getLLVMConstant(
|
|
|
|
|
llvm::Type *llvmType, Attribute attr, Location loc,
|
2022-05-11 15:12:21 +02:00
|
|
|
const ModuleTranslation &moduleTranslation) {
|
2019-09-21 01:19:43 -07:00
|
|
|
if (!attr)
|
|
|
|
|
return llvm::UndefValue::get(llvmType);
|
2021-05-14 13:00:38 +02:00
|
|
|
if (auto *structType = dyn_cast<::llvm::StructType>(llvmType)) {
|
2022-05-11 15:12:21 +02:00
|
|
|
auto arrayAttr = attr.dyn_cast<ArrayAttr>();
|
|
|
|
|
if (!arrayAttr || arrayAttr.size() != 2) {
|
|
|
|
|
emitError(loc, "expected struct type to be a complex number");
|
2021-05-14 13:00:38 +02:00
|
|
|
return nullptr;
|
|
|
|
|
}
|
|
|
|
|
llvm::Type *elementType = structType->getElementType(0);
|
2022-05-11 15:12:21 +02:00
|
|
|
llvm::Constant *real =
|
|
|
|
|
getLLVMConstant(elementType, arrayAttr[0], loc, moduleTranslation);
|
2021-05-14 13:00:38 +02:00
|
|
|
if (!real)
|
|
|
|
|
return nullptr;
|
2022-05-11 15:12:21 +02:00
|
|
|
llvm::Constant *imag =
|
|
|
|
|
getLLVMConstant(elementType, arrayAttr[1], loc, moduleTranslation);
|
2021-05-14 13:00:38 +02:00
|
|
|
if (!imag)
|
|
|
|
|
return nullptr;
|
|
|
|
|
return llvm::ConstantStruct::get(structType, {real, imag});
|
2020-01-16 16:21:14 +01:00
|
|
|
}
|
2020-03-26 12:12:06 +01:00
|
|
|
// For integer types, we allow a mismatch in sizes as the index type in
|
|
|
|
|
// MLIR might have a different size than the index type in the LLVM module.
|
2019-04-30 06:08:21 -07:00
|
|
|
if (auto intAttr = attr.dyn_cast<IntegerAttr>())
|
2020-03-26 12:12:06 +01:00
|
|
|
return llvm::ConstantInt::get(
|
|
|
|
|
llvmType,
|
|
|
|
|
intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth()));
|
2021-05-14 13:00:38 +02:00
|
|
|
if (auto floatAttr = attr.dyn_cast<FloatAttr>()) {
|
|
|
|
|
if (llvmType !=
|
|
|
|
|
llvm::Type::getFloatingPointTy(llvmType->getContext(),
|
|
|
|
|
floatAttr.getValue().getSemantics())) {
|
|
|
|
|
emitError(loc, "FloatAttr does not match expected type of the constant");
|
|
|
|
|
return nullptr;
|
|
|
|
|
}
|
2019-04-30 06:08:21 -07:00
|
|
|
return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
|
2021-05-14 13:00:38 +02:00
|
|
|
}
|
2019-11-11 18:18:02 -08:00
|
|
|
if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>())
|
2021-02-12 12:53:27 +01:00
|
|
|
return llvm::ConstantExpr::getBitCast(
|
|
|
|
|
moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType);
|
2019-04-30 06:08:21 -07:00
|
|
|
if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
|
2020-04-06 17:03:49 -07:00
|
|
|
llvm::Type *elementType;
|
|
|
|
|
uint64_t numElements;
|
2022-01-12 17:01:07 +00:00
|
|
|
bool isScalable = false;
|
2020-04-06 17:03:49 -07:00
|
|
|
if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
|
|
|
|
|
elementType = arrayTy->getElementType();
|
|
|
|
|
numElements = arrayTy->getNumElements();
|
2021-12-20 19:45:05 +00:00
|
|
|
} else if (auto *fVectorTy = dyn_cast<llvm::FixedVectorType>(llvmType)) {
|
2021-10-12 14:26:01 +01:00
|
|
|
elementType = fVectorTy->getElementType();
|
|
|
|
|
numElements = fVectorTy->getNumElements();
|
2021-12-20 19:45:05 +00:00
|
|
|
} else if (auto *sVectorTy = dyn_cast<llvm::ScalableVectorType>(llvmType)) {
|
2021-10-12 14:26:01 +01:00
|
|
|
elementType = sVectorTy->getElementType();
|
|
|
|
|
numElements = sVectorTy->getMinNumElements();
|
2022-01-12 17:01:07 +00:00
|
|
|
isScalable = true;
|
2020-04-06 17:03:49 -07:00
|
|
|
} else {
|
2021-10-12 14:26:01 +01:00
|
|
|
llvm_unreachable("unrecognized constant vector type");
|
2020-04-06 17:03:49 -07:00
|
|
|
}
|
[mlir] Fix translation of splat constants to LLVM IR
Summary:
When converting splat constants for nested sequential LLVM IR types wrapped in
MLIR, the constant conversion was erroneously assuming it was always possible
to recursively construct a constant of a sequential type given only one value.
Instead, wait until all sequential types are unpacked recursively before
constructing a scalar constant and wrapping it into the surrounding sequential
type.
Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, aartbik, liufengdb, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D72688
2020-01-14 11:30:25 +01:00
|
|
|
// Splat value is a scalar. Extract it only if the element type is not
|
|
|
|
|
// another sequence type. The recursion terminates because each step removes
|
|
|
|
|
// one outer sequential type.
|
2020-04-06 17:03:49 -07:00
|
|
|
bool elementTypeSequential =
|
2020-06-24 11:49:30 -07:00
|
|
|
isa<llvm::ArrayType, llvm::VectorType>(elementType);
|
[mlir] Fix translation of splat constants to LLVM IR
Summary:
When converting splat constants for nested sequential LLVM IR types wrapped in
MLIR, the constant conversion was erroneously assuming it was always possible
to recursively construct a constant of a sequential type given only one value.
Instead, wait until all sequential types are unpacked recursively before
constructing a scalar constant and wrapping it into the surrounding sequential
type.
Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, aartbik, liufengdb, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D72688
2020-01-14 11:30:25 +01:00
|
|
|
llvm::Constant *child = getLLVMConstant(
|
|
|
|
|
elementType,
|
2021-11-09 01:40:17 +00:00
|
|
|
elementTypeSequential ? splatAttr
|
|
|
|
|
: splatAttr.getSplatValue<Attribute>(),
|
2022-05-11 15:12:21 +02:00
|
|
|
loc, moduleTranslation);
|
2020-01-16 16:21:14 +01:00
|
|
|
if (!child)
|
|
|
|
|
return nullptr;
|
2019-09-04 03:45:38 -07:00
|
|
|
if (llvmType->isVectorTy())
|
2020-03-12 14:22:00 -07:00
|
|
|
return llvm::ConstantVector::getSplat(
|
2022-01-12 17:01:07 +00:00
|
|
|
llvm::ElementCount::get(numElements, /*Scalable=*/isScalable), child);
|
2019-09-04 03:45:38 -07:00
|
|
|
if (llvmType->isArrayTy()) {
|
2020-03-26 12:12:06 +01:00
|
|
|
auto *arrayType = llvm::ArrayType::get(elementType, numElements);
|
2019-09-04 03:45:38 -07:00
|
|
|
SmallVector<llvm::Constant *, 8> constants(numElements, child);
|
|
|
|
|
return llvm::ConstantArray::get(arrayType, constants);
|
|
|
|
|
}
|
2019-04-30 06:08:21 -07:00
|
|
|
}
|
2020-01-16 16:21:14 +01:00
|
|
|
|
2021-09-02 15:01:19 +02:00
|
|
|
// Try using raw elements data if possible.
|
|
|
|
|
if (llvm::Constant *result =
|
|
|
|
|
convertDenseElementsAttr(loc, attr.dyn_cast<DenseElementsAttr>(),
|
|
|
|
|
llvmType, moduleTranslation)) {
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Fall back to element-by-element construction otherwise.
|
2019-08-22 18:58:51 -07:00
|
|
|
if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
|
2020-01-16 16:21:14 +01:00
|
|
|
assert(elementsAttr.getType().hasStaticShape());
|
|
|
|
|
assert(!elementsAttr.getType().getShape().empty() &&
|
|
|
|
|
"unexpected empty elements attribute shape");
|
|
|
|
|
|
2019-04-30 06:08:21 -07:00
|
|
|
SmallVector<llvm::Constant *, 8> constants;
|
2020-01-16 16:21:14 +01:00
|
|
|
constants.reserve(elementsAttr.getNumElements());
|
|
|
|
|
llvm::Type *innermostType = getInnermostElementType(llvmType);
|
2019-08-22 18:58:51 -07:00
|
|
|
for (auto n : elementsAttr.getValues<Attribute>()) {
|
2021-02-12 12:53:27 +01:00
|
|
|
constants.push_back(
|
2022-05-11 15:12:21 +02:00
|
|
|
getLLVMConstant(innermostType, n, loc, moduleTranslation));
|
2019-04-30 06:08:21 -07:00
|
|
|
if (!constants.back())
|
|
|
|
|
return nullptr;
|
|
|
|
|
}
|
2020-01-16 16:21:14 +01:00
|
|
|
ArrayRef<llvm::Constant *> constantsRef = constants;
|
|
|
|
|
llvm::Constant *result = buildSequentialConstant(
|
|
|
|
|
constantsRef, elementsAttr.getType().getShape(), llvmType, loc);
|
|
|
|
|
assert(constantsRef.empty() && "did not consume all elemental constants");
|
|
|
|
|
return result;
|
2019-04-30 06:08:21 -07:00
|
|
|
}
|
2020-01-16 16:21:14 +01:00
|
|
|
|
2019-05-24 04:49:56 -07:00
|
|
|
if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
|
|
|
|
|
return llvm::ConstantDataArray::get(
|
2021-02-12 12:53:27 +01:00
|
|
|
moduleTranslation.getLLVMContext(),
|
|
|
|
|
ArrayRef<char>{stringAttr.getValue().data(),
|
|
|
|
|
stringAttr.getValue().size()});
|
2019-05-24 04:49:56 -07:00
|
|
|
}
|
2019-06-25 21:31:54 -07:00
|
|
|
emitError(loc, "unsupported constant value");
|
2019-04-30 06:08:21 -07:00
|
|
|
return nullptr;
|
|
|
|
|
}
|
|
|
|
|
|
2020-02-05 17:10:55 -08:00
|
|
|
ModuleTranslation::ModuleTranslation(Operation *module,
|
|
|
|
|
std::unique_ptr<llvm::Module> llvmModule)
|
|
|
|
|
: mlirModule(module), llvmModule(std::move(llvmModule)),
|
|
|
|
|
debugTranslation(
|
2020-03-04 23:36:21 +00:00
|
|
|
std::make_unique<DebugTranslation>(module, *this->llvmModule)),
|
2021-02-11 15:01:33 +01:00
|
|
|
typeTranslator(this->llvmModule->getContext()),
|
|
|
|
|
iface(module->getContext()) {
|
2020-02-05 17:10:55 -08:00
|
|
|
assert(satisfiesLLVMModule(mlirModule) &&
|
|
|
|
|
"mlirModule should honor LLVM's module semantics.");
|
|
|
|
|
}
|
2020-07-13 23:13:04 +01:00
|
|
|
ModuleTranslation::~ModuleTranslation() {
|
|
|
|
|
if (ompBuilder)
|
|
|
|
|
ompBuilder->finalize();
|
|
|
|
|
}
|
|
|
|
|
|
2021-08-24 17:53:42 +02:00
|
|
|
void ModuleTranslation::forgetMapping(Region ®ion) {
|
|
|
|
|
SmallVector<Region *> toProcess;
|
|
|
|
|
toProcess.push_back(®ion);
|
|
|
|
|
while (!toProcess.empty()) {
|
|
|
|
|
Region *current = toProcess.pop_back_val();
|
|
|
|
|
for (Block &block : *current) {
|
|
|
|
|
blockMapping.erase(&block);
|
|
|
|
|
for (Value arg : block.getArguments())
|
|
|
|
|
valueMapping.erase(arg);
|
|
|
|
|
for (Operation &op : block) {
|
|
|
|
|
for (Value value : op.getResults())
|
|
|
|
|
valueMapping.erase(value);
|
|
|
|
|
if (op.hasSuccessors())
|
|
|
|
|
branchMapping.erase(&op);
|
|
|
|
|
if (isa<LLVM::GlobalOp>(op))
|
|
|
|
|
globalsMapping.erase(&op);
|
|
|
|
|
accessGroupMetadataMapping.erase(&op);
|
|
|
|
|
llvm::append_range(
|
|
|
|
|
toProcess,
|
|
|
|
|
llvm::map_range(op.getRegions(), [](Region &r) { return &r; }));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-07-13 23:13:04 +01:00
|
|
|
/// Get the SSA value passed to the current block from the terminator operation
|
|
|
|
|
/// of its predecessor.
|
|
|
|
|
static Value getPHISourceValue(Block *current, Block *pred,
|
|
|
|
|
unsigned numArguments, unsigned index) {
|
|
|
|
|
Operation &terminator = *pred->getTerminator();
|
|
|
|
|
if (isa<LLVM::BrOp>(terminator))
|
|
|
|
|
return terminator.getOperand(index);
|
|
|
|
|
|
2022-01-13 14:29:09 +01:00
|
|
|
#ifndef NDEBUG
|
|
|
|
|
llvm::SmallPtrSet<Block *, 4> seenSuccessors;
|
|
|
|
|
for (unsigned i = 0, e = terminator.getNumSuccessors(); i < e; ++i) {
|
|
|
|
|
Block *successor = terminator.getSuccessor(i);
|
|
|
|
|
auto branch = cast<BranchOpInterface>(terminator);
|
2022-04-08 08:17:36 +02:00
|
|
|
SuccessorOperands successorOperands = branch.getSuccessorOperands(i);
|
2022-01-13 14:29:09 +01:00
|
|
|
assert(
|
2022-04-08 08:17:36 +02:00
|
|
|
(!seenSuccessors.contains(successor) || successorOperands.empty()) &&
|
2022-01-13 14:29:09 +01:00
|
|
|
"successors with arguments in LLVM branches must be different blocks");
|
|
|
|
|
seenSuccessors.insert(successor);
|
|
|
|
|
}
|
|
|
|
|
#endif
|
[mlir][LLVMIR] Add 'llvm.switch' op
The LLVM IR 'switch' instruction allows control flow to be transferred
to one of any number of branches depending on an integer control value,
or a default value if the control does not match any branch values. This patch
adds `llvm.switch` to the MLIR LLVMIR dialect, as well as translation routines
for lowering it to LLVM IR.
To store a variable number of operands for a variable number of branch
destinations, the new op makes use of the `AttrSizedOperandSegments`
trait. It stores its default branch operands as one segment, and all
remaining case branches' operands as another. It also stores pairs of
begin and end offset values to delineate the sub-range of each case branch's
operands. There's probably a better way to implement this, since the
offset computation complicates several parts of the op definition. This is the
approach I settled on because in doing so I was able to delegate to the default
op builder member functions. However, it may be preferable to instead specify
`skipDefaultBuilders` in the op's ODS, or use a completely separate
approach; feedback is welcome!
Another contentious part of this patch may be the custom printer and
parser functions for the op. Ideally I would have liked the MLIR to be
printed in this way:
```
llvm.switch %0, ^bb1(%1 : !llvm.i32) [
1: ^bb2,
2: ^bb3(%2, %3 : !llvm.i32, !llvm.i32)
]
```
The above would resemble how LLVM IR is formatted for the 'switch'
instruction. But I found it difficult to print and parse something like
this, whether I used the declarative assembly format or custom functions.
I also was not sure a multi-line format would be welcome -- it seems
like most MLIR ops do not use newlines. Again, I'd be happy to hear any
feedback here as well, or on any other aspect of the patch.
Differential Revision: https://reviews.llvm.org/D93005
2020-12-09 22:37:20 -05:00
|
|
|
|
|
|
|
|
// For instructions that branch based on a condition value, we need to take
|
|
|
|
|
// the operands for the branch that was taken.
|
|
|
|
|
if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) {
|
|
|
|
|
// For conditional branches, we take the operands from either the "true" or
|
|
|
|
|
// the "false" branch.
|
|
|
|
|
return condBranchOp.getSuccessor(0) == current
|
2021-10-24 18:36:33 -07:00
|
|
|
? condBranchOp.getTrueDestOperands()[index]
|
|
|
|
|
: condBranchOp.getFalseDestOperands()[index];
|
2021-02-10 19:21:45 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) {
|
[mlir][LLVMIR] Add 'llvm.switch' op
The LLVM IR 'switch' instruction allows control flow to be transferred
to one of any number of branches depending on an integer control value,
or a default value if the control does not match any branch values. This patch
adds `llvm.switch` to the MLIR LLVMIR dialect, as well as translation routines
for lowering it to LLVM IR.
To store a variable number of operands for a variable number of branch
destinations, the new op makes use of the `AttrSizedOperandSegments`
trait. It stores its default branch operands as one segment, and all
remaining case branches' operands as another. It also stores pairs of
begin and end offset values to delineate the sub-range of each case branch's
operands. There's probably a better way to implement this, since the
offset computation complicates several parts of the op definition. This is the
approach I settled on because in doing so I was able to delegate to the default
op builder member functions. However, it may be preferable to instead specify
`skipDefaultBuilders` in the op's ODS, or use a completely separate
approach; feedback is welcome!
Another contentious part of this patch may be the custom printer and
parser functions for the op. Ideally I would have liked the MLIR to be
printed in this way:
```
llvm.switch %0, ^bb1(%1 : !llvm.i32) [
1: ^bb2,
2: ^bb3(%2, %3 : !llvm.i32, !llvm.i32)
]
```
The above would resemble how LLVM IR is formatted for the 'switch'
instruction. But I found it difficult to print and parse something like
this, whether I used the declarative assembly format or custom functions.
I also was not sure a multi-line format would be welcome -- it seems
like most MLIR ops do not use newlines. Again, I'd be happy to hear any
feedback here as well, or on any other aspect of the patch.
Differential Revision: https://reviews.llvm.org/D93005
2020-12-09 22:37:20 -05:00
|
|
|
// For switches, we take the operands from either the default case, or from
|
|
|
|
|
// the case branch that was taken.
|
2021-10-29 13:29:48 -07:00
|
|
|
if (switchOp.getDefaultDestination() == current)
|
|
|
|
|
return switchOp.getDefaultOperands()[index];
|
2022-01-02 22:02:14 +00:00
|
|
|
for (const auto &i : llvm::enumerate(switchOp.getCaseDestinations()))
|
[mlir][LLVMIR] Add 'llvm.switch' op
The LLVM IR 'switch' instruction allows control flow to be transferred
to one of any number of branches depending on an integer control value,
or a default value if the control does not match any branch values. This patch
adds `llvm.switch` to the MLIR LLVMIR dialect, as well as translation routines
for lowering it to LLVM IR.
To store a variable number of operands for a variable number of branch
destinations, the new op makes use of the `AttrSizedOperandSegments`
trait. It stores its default branch operands as one segment, and all
remaining case branches' operands as another. It also stores pairs of
begin and end offset values to delineate the sub-range of each case branch's
operands. There's probably a better way to implement this, since the
offset computation complicates several parts of the op definition. This is the
approach I settled on because in doing so I was able to delegate to the default
op builder member functions. However, it may be preferable to instead specify
`skipDefaultBuilders` in the op's ODS, or use a completely separate
approach; feedback is welcome!
Another contentious part of this patch may be the custom printer and
parser functions for the op. Ideally I would have liked the MLIR to be
printed in this way:
```
llvm.switch %0, ^bb1(%1 : !llvm.i32) [
1: ^bb2,
2: ^bb3(%2, %3 : !llvm.i32, !llvm.i32)
]
```
The above would resemble how LLVM IR is formatted for the 'switch'
instruction. But I found it difficult to print and parse something like
this, whether I used the declarative assembly format or custom functions.
I also was not sure a multi-line format would be welcome -- it seems
like most MLIR ops do not use newlines. Again, I'd be happy to hear any
feedback here as well, or on any other aspect of the patch.
Differential Revision: https://reviews.llvm.org/D93005
2020-12-09 22:37:20 -05:00
|
|
|
if (i.value() == current)
|
|
|
|
|
return switchOp.getCaseOperands(i.index())[index];
|
|
|
|
|
}
|
|
|
|
|
|
2022-01-06 00:41:35 +01:00
|
|
|
if (auto invokeOp = dyn_cast<LLVM::InvokeOp>(terminator)) {
|
|
|
|
|
return invokeOp.getNormalDest() == current
|
|
|
|
|
? invokeOp.getNormalDestOperands()[index]
|
|
|
|
|
: invokeOp.getUnwindDestOperands()[index];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
llvm_unreachable(
|
|
|
|
|
"only branch, switch or invoke operations can be terminators "
|
|
|
|
|
"of a block that has successors");
|
2020-07-13 23:13:04 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Connect the PHI nodes to the results of preceding blocks.
|
2021-02-11 15:01:43 +01:00
|
|
|
void mlir::LLVM::detail::connectPHINodes(Region ®ion,
|
|
|
|
|
const ModuleTranslation &state) {
|
2020-07-13 23:13:04 +01:00
|
|
|
// Skip the first block, it cannot be branched to and its arguments correspond
|
|
|
|
|
// to the arguments of the LLVM function.
|
2022-07-15 23:58:11 -07:00
|
|
|
for (Block &bb : llvm::drop_begin(region)) {
|
|
|
|
|
llvm::BasicBlock *llvmBB = state.lookupBlock(&bb);
|
2020-07-13 23:13:04 +01:00
|
|
|
auto phis = llvmBB->phis();
|
2022-07-15 23:58:11 -07:00
|
|
|
auto numArguments = bb.getNumArguments();
|
2020-07-13 23:13:04 +01:00
|
|
|
assert(numArguments == std::distance(phis.begin(), phis.end()));
|
|
|
|
|
for (auto &numberedPhiNode : llvm::enumerate(phis)) {
|
|
|
|
|
auto &phiNode = numberedPhiNode.value();
|
|
|
|
|
unsigned index = numberedPhiNode.index();
|
2022-07-15 23:58:11 -07:00
|
|
|
for (auto *pred : bb.getPredecessors()) {
|
2020-12-08 16:09:20 +01:00
|
|
|
// Find the LLVM IR block that contains the converted terminator
|
|
|
|
|
// instruction and use it in the PHI node. Note that this block is not
|
2021-02-10 19:21:45 +01:00
|
|
|
// necessarily the same as state.lookupBlock(pred), some operations
|
2020-12-08 16:09:20 +01:00
|
|
|
// (in particular, OpenMP operations using OpenMPIRBuilder) may have
|
|
|
|
|
// split the blocks.
|
|
|
|
|
llvm::Instruction *terminator =
|
2021-02-10 19:21:45 +01:00
|
|
|
state.lookupBranch(pred->getTerminator());
|
2020-12-08 16:09:20 +01:00
|
|
|
assert(terminator && "missing the mapping for a terminator");
|
2022-07-15 23:58:11 -07:00
|
|
|
phiNode.addIncoming(state.lookupValue(getPHISourceValue(
|
|
|
|
|
&bb, pred, numArguments, index)),
|
|
|
|
|
terminator->getParent());
|
2020-07-13 23:13:04 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Sort function blocks topologically.
|
2021-04-15 16:08:54 -07:00
|
|
|
SetVector<Block *>
|
2021-02-11 15:01:43 +01:00
|
|
|
mlir::LLVM::detail::getTopologicallySortedBlocks(Region ®ion) {
|
2020-10-02 13:17:26 +03:00
|
|
|
// For each block that has not been visited yet (i.e. that has no
|
|
|
|
|
// predecessors), add it to the list as well as its successors.
|
2021-04-15 16:08:54 -07:00
|
|
|
SetVector<Block *> blocks;
|
2021-02-11 15:01:43 +01:00
|
|
|
for (Block &b : region) {
|
2020-10-02 13:17:26 +03:00
|
|
|
if (blocks.count(&b) == 0) {
|
|
|
|
|
llvm::ReversePostOrderTraversal<Block *> traversal(&b);
|
|
|
|
|
blocks.insert(traversal.begin(), traversal.end());
|
|
|
|
|
}
|
2020-07-13 23:13:04 +01:00
|
|
|
}
|
2021-02-11 15:01:43 +01:00
|
|
|
assert(blocks.size() == region.getBlocks().size() &&
|
|
|
|
|
"some blocks are not sorted");
|
2020-07-13 23:13:04 +01:00
|
|
|
|
|
|
|
|
return blocks;
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-12 12:53:27 +01:00
|
|
|
llvm::Value *mlir::LLVM::detail::createIntrinsicCall(
|
|
|
|
|
llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic,
|
|
|
|
|
ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) {
|
|
|
|
|
llvm::Module *module = builder.GetInsertBlock()->getModule();
|
|
|
|
|
llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys);
|
|
|
|
|
return builder.CreateCall(fn, args);
|
|
|
|
|
}
|
|
|
|
|
|
2019-12-18 10:46:16 -08:00
|
|
|
/// Given a single MLIR operation, create the corresponding LLVM IR operation
|
2021-02-12 12:53:27 +01:00
|
|
|
/// using the `builder`.
|
2021-02-16 17:36:45 +01:00
|
|
|
LogicalResult
|
2021-04-08 22:15:39 +00:00
|
|
|
ModuleTranslation::convertOperation(Operation &op,
|
2021-02-16 17:36:45 +01:00
|
|
|
llvm::IRBuilderBase &builder) {
|
2021-04-08 22:15:39 +00:00
|
|
|
const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op);
|
|
|
|
|
if (!opIface)
|
|
|
|
|
return op.emitError("cannot be converted to LLVM IR: missing "
|
|
|
|
|
"`LLVMTranslationDialectInterface` registration for "
|
|
|
|
|
"dialect for op: ")
|
|
|
|
|
<< op.getName();
|
2019-08-12 06:10:29 -07:00
|
|
|
|
2021-04-08 22:15:39 +00:00
|
|
|
if (failed(opIface->convertOperation(&op, builder, *this)))
|
|
|
|
|
return op.emitError("LLVM Translation failed for operation: ")
|
|
|
|
|
<< op.getName();
|
|
|
|
|
|
|
|
|
|
return convertDialectAttributes(&op);
|
2019-04-30 06:08:21 -07:00
|
|
|
}
|
|
|
|
|
|
2019-12-18 10:46:16 -08:00
|
|
|
/// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes
|
|
|
|
|
/// to define values corresponding to the MLIR block arguments. These nodes
|
2021-01-05 16:04:00 +01:00
|
|
|
/// are not connected to the source basic blocks, which may not exist yet. Uses
|
|
|
|
|
/// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have
|
|
|
|
|
/// been created for `bb` and included in the block mapping. Inserts new
|
|
|
|
|
/// instructions at the end of the block and leaves `builder` in a state
|
|
|
|
|
/// suitable for further insertion into the end of the block.
|
|
|
|
|
LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments,
|
2021-02-16 17:36:45 +01:00
|
|
|
llvm::IRBuilderBase &builder) {
|
2021-02-10 19:21:45 +01:00
|
|
|
builder.SetInsertPoint(lookupBlock(&bb));
|
2020-02-05 17:10:55 -08:00
|
|
|
auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
|
2019-04-30 06:08:21 -07:00
|
|
|
|
|
|
|
|
// Before traversing operations, make block arguments available through
|
|
|
|
|
// value remapping and PHI nodes, but do not add incoming edges for the PHI
|
|
|
|
|
// nodes just yet: those values may be defined by this or following blocks.
|
|
|
|
|
// This step is omitted if "ignoreArguments" is set. The arguments of the
|
|
|
|
|
// first block have been already made available through the remapping of
|
|
|
|
|
// LLVM function arguments.
|
|
|
|
|
if (!ignoreArguments) {
|
|
|
|
|
auto predecessors = bb.getPredecessors();
|
|
|
|
|
unsigned numPredecessors =
|
|
|
|
|
std::distance(predecessors.begin(), predecessors.end());
|
2019-12-22 21:59:55 -08:00
|
|
|
for (auto arg : bb.getArguments()) {
|
2021-01-05 16:22:53 +01:00
|
|
|
auto wrappedType = arg.getType();
|
|
|
|
|
if (!isCompatibleType(wrappedType))
|
2019-08-09 10:45:15 -07:00
|
|
|
return emitError(bb.front().getLoc(),
|
|
|
|
|
"block argument does not have an LLVM type");
|
2020-07-23 10:32:12 +02:00
|
|
|
llvm::Type *type = convertType(wrappedType);
|
2019-04-30 06:08:21 -07:00
|
|
|
llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
|
2021-02-10 19:21:45 +01:00
|
|
|
mapValue(arg, phi);
|
2019-04-30 06:08:21 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Traverse operations.
|
|
|
|
|
for (auto &op : bb) {
|
2020-02-05 17:10:55 -08:00
|
|
|
// Set the current debug location within the builder.
|
|
|
|
|
builder.SetCurrentDebugLocation(
|
|
|
|
|
debugTranslation->translateLoc(op.getLoc(), subprogram));
|
|
|
|
|
|
2019-08-09 10:45:15 -07:00
|
|
|
if (failed(convertOperation(op, builder)))
|
|
|
|
|
return failure();
|
2019-04-30 06:08:21 -07:00
|
|
|
}
|
|
|
|
|
|
2019-08-09 10:45:15 -07:00
|
|
|
return success();
|
2019-04-30 06:08:21 -07:00
|
|
|
}
|
|
|
|
|
|
2021-02-16 17:36:45 +01:00
|
|
|
/// A helper method to get the single Block in an operation honoring LLVM's
|
|
|
|
|
/// module requirements.
|
|
|
|
|
static Block &getModuleBody(Operation *module) {
|
|
|
|
|
return module->getRegion(0).front();
|
|
|
|
|
}
|
|
|
|
|
|
2021-03-25 09:40:42 +01:00
|
|
|
/// A helper method to decide if a constant must not be set as a global variable
|
2021-07-08 16:07:09 +02:00
|
|
|
/// initializer. For an external linkage variable, the variable with an
|
|
|
|
|
/// initializer is considered externally visible and defined in this module, the
|
|
|
|
|
/// variable without an initializer is externally available and is defined
|
|
|
|
|
/// elsewhere.
|
2021-03-25 09:40:42 +01:00
|
|
|
static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage,
|
|
|
|
|
llvm::Constant *cst) {
|
2021-07-08 16:07:09 +02:00
|
|
|
return (linkage == llvm::GlobalVariable::ExternalLinkage && !cst) ||
|
2021-03-25 09:40:42 +01:00
|
|
|
linkage == llvm::GlobalVariable::ExternalWeakLinkage;
|
|
|
|
|
}
|
|
|
|
|
|
2021-06-29 14:57:16 +02:00
|
|
|
/// Sets the runtime preemption specifier of `gv` to dso_local if
|
|
|
|
|
/// `dsoLocalRequested` is true, otherwise it is left unchanged.
|
|
|
|
|
static void addRuntimePreemptionSpecifier(bool dsoLocalRequested,
|
|
|
|
|
llvm::GlobalValue *gv) {
|
|
|
|
|
if (dsoLocalRequested)
|
|
|
|
|
gv->setDSOLocal(true);
|
|
|
|
|
}
|
|
|
|
|
|
2019-12-18 10:46:16 -08:00
|
|
|
/// Create named global variables that correspond to llvm.mlir.global
|
2021-10-20 15:14:54 +05:30
|
|
|
/// definitions. Convert llvm.global_ctors and global_dtors ops.
|
2020-03-02 15:18:41 +01:00
|
|
|
LogicalResult ModuleTranslation::convertGlobals() {
|
2019-12-16 01:35:03 -08:00
|
|
|
for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
|
2020-07-23 10:32:12 +02:00
|
|
|
llvm::Type *type = convertType(op.getType());
|
2021-07-08 16:07:09 +02:00
|
|
|
llvm::Constant *cst = nullptr;
|
2019-11-05 15:10:28 -08:00
|
|
|
if (op.getValueOrNull()) {
|
|
|
|
|
// String attributes are treated separately because they cannot appear as
|
|
|
|
|
// in-function constants and are thus not supported by getLLVMConstant.
|
|
|
|
|
if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
|
|
|
|
|
cst = llvm::ConstantDataArray::getString(
|
|
|
|
|
llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
|
|
|
|
|
type = cst->getType();
|
2021-02-12 12:53:27 +01:00
|
|
|
} else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(),
|
|
|
|
|
*this))) {
|
2020-03-02 15:18:41 +01:00
|
|
|
return failure();
|
2019-11-05 15:10:28 -08:00
|
|
|
}
|
2019-08-09 08:59:45 -07:00
|
|
|
}
|
|
|
|
|
|
2021-10-24 18:36:33 -07:00
|
|
|
auto linkage = convertLinkageToLLVM(op.getLinkage());
|
|
|
|
|
auto addrSpace = op.getAddrSpace();
|
2021-07-08 16:07:09 +02:00
|
|
|
|
|
|
|
|
// LLVM IR requires constant with linkage other than external or weak
|
|
|
|
|
// external to have initializers. If MLIR does not provide an initializer,
|
|
|
|
|
// default to undef.
|
|
|
|
|
bool dropInitializer = shouldDropGlobalInitializer(linkage, cst);
|
|
|
|
|
if (!dropInitializer && !cst)
|
|
|
|
|
cst = llvm::UndefValue::get(type);
|
|
|
|
|
else if (dropInitializer && cst)
|
|
|
|
|
cst = nullptr;
|
|
|
|
|
|
2019-09-19 04:50:17 -07:00
|
|
|
auto *var = new llvm::GlobalVariable(
|
2021-10-24 18:36:33 -07:00
|
|
|
*llvmModule, type, op.getConstant(), linkage, cst, op.getSymName(),
|
2022-04-13 08:20:56 +05:30
|
|
|
/*InsertBefore=*/nullptr,
|
|
|
|
|
op.getThreadLocal_() ? llvm::GlobalValue::GeneralDynamicTLSModel
|
|
|
|
|
: llvm::GlobalValue::NotThreadLocal,
|
|
|
|
|
addrSpace);
|
2019-09-19 04:50:17 -07:00
|
|
|
|
2022-07-13 00:57:02 -07:00
|
|
|
if (op.getUnnamedAddr().has_value())
|
2021-10-24 18:36:33 -07:00
|
|
|
var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.getUnnamedAddr()));
|
2021-04-19 21:45:01 -04:00
|
|
|
|
2022-07-13 00:57:02 -07:00
|
|
|
if (op.getSection().has_value())
|
2021-10-24 18:36:33 -07:00
|
|
|
var->setSection(*op.getSection());
|
2021-04-28 03:59:11 +00:00
|
|
|
|
2021-10-24 18:36:33 -07:00
|
|
|
addRuntimePreemptionSpecifier(op.getDsoLocal(), var);
|
2021-06-29 14:57:16 +02:00
|
|
|
|
2022-12-14 11:39:19 +01:00
|
|
|
std::optional<uint64_t> alignment = op.getAlignment();
|
2022-07-13 00:57:02 -07:00
|
|
|
if (alignment.has_value())
|
2022-07-14 00:19:59 -07:00
|
|
|
var->setAlignment(llvm::MaybeAlign(alignment.value()));
|
2021-05-12 08:45:25 +02:00
|
|
|
|
2019-08-12 06:10:29 -07:00
|
|
|
globalsMapping.try_emplace(op, var);
|
2019-08-09 08:30:13 -07:00
|
|
|
}
|
2020-03-02 15:18:41 +01:00
|
|
|
|
2021-03-25 09:40:42 +01:00
|
|
|
// Convert global variable bodies. This is done after all global variables
|
|
|
|
|
// have been created in LLVM IR because a global body may refer to another
|
|
|
|
|
// global or itself. So all global variables need to be mapped first.
|
|
|
|
|
for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
|
|
|
|
|
if (Block *initializer = op.getInitializerBlock()) {
|
|
|
|
|
llvm::IRBuilder<> builder(llvmModule->getContext());
|
|
|
|
|
for (auto &op : initializer->without_terminator()) {
|
|
|
|
|
if (failed(convertOperation(op, builder)) ||
|
|
|
|
|
!isa<llvm::Constant>(lookupValue(op.getResult(0))))
|
|
|
|
|
return emitError(op.getLoc(), "unemittable constant value");
|
|
|
|
|
}
|
|
|
|
|
ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
|
|
|
|
|
llvm::Constant *cst =
|
|
|
|
|
cast<llvm::Constant>(lookupValue(ret.getOperand(0)));
|
|
|
|
|
auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op));
|
|
|
|
|
if (!shouldDropGlobalInitializer(global->getLinkage(), cst))
|
|
|
|
|
global->setInitializer(cst);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-10-20 15:14:54 +05:30
|
|
|
// Convert llvm.mlir.global_ctors and dtors.
|
|
|
|
|
for (Operation &op : getModuleBody(mlirModule)) {
|
|
|
|
|
auto ctorOp = dyn_cast<GlobalCtorsOp>(op);
|
|
|
|
|
auto dtorOp = dyn_cast<GlobalDtorsOp>(op);
|
|
|
|
|
if (!ctorOp && !dtorOp)
|
|
|
|
|
continue;
|
2021-11-30 19:42:37 -08:00
|
|
|
auto range = ctorOp ? llvm::zip(ctorOp.getCtors(), ctorOp.getPriorities())
|
|
|
|
|
: llvm::zip(dtorOp.getDtors(), dtorOp.getPriorities());
|
2021-10-20 15:14:54 +05:30
|
|
|
auto appendGlobalFn =
|
|
|
|
|
ctorOp ? llvm::appendToGlobalCtors : llvm::appendToGlobalDtors;
|
|
|
|
|
for (auto symbolAndPriority : range) {
|
|
|
|
|
llvm::Function *f = lookupFunction(
|
|
|
|
|
std::get<0>(symbolAndPriority).cast<FlatSymbolRefAttr>().getValue());
|
|
|
|
|
appendGlobalFn(
|
2022-01-08 20:06:50 +00:00
|
|
|
*llvmModule, f,
|
2021-10-20 15:14:54 +05:30
|
|
|
std::get<1>(symbolAndPriority).cast<IntegerAttr>().getInt(),
|
|
|
|
|
/*Data=*/nullptr);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-03-02 15:18:41 +01:00
|
|
|
return success();
|
2019-08-09 08:30:13 -07:00
|
|
|
}
|
|
|
|
|
|
2020-03-30 18:50:42 +02:00
|
|
|
/// Attempts to add an attribute identified by `key`, optionally with the given
|
|
|
|
|
/// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
|
|
|
|
|
/// attribute has a kind known to LLVM IR, create the attribute of this kind,
|
|
|
|
|
/// otherwise keep it as a string attribute. Performs additional checks for
|
|
|
|
|
/// attributes known to have or not have a value in order to avoid assertions
|
|
|
|
|
/// inside LLVM upon construction.
|
|
|
|
|
static LogicalResult checkedAddLLVMFnAttribute(Location loc,
|
|
|
|
|
llvm::Function *llvmFunc,
|
|
|
|
|
StringRef key,
|
|
|
|
|
StringRef value = StringRef()) {
|
|
|
|
|
auto kind = llvm::Attribute::getAttrKindFromName(key);
|
|
|
|
|
if (kind == llvm::Attribute::None) {
|
|
|
|
|
llvmFunc->addFnAttr(key, value);
|
|
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
2021-07-12 21:25:46 +02:00
|
|
|
if (llvm::Attribute::isIntAttrKind(kind)) {
|
2020-03-30 18:50:42 +02:00
|
|
|
if (value.empty())
|
|
|
|
|
return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
|
|
|
|
|
|
|
|
|
|
int result;
|
|
|
|
|
if (!value.getAsInteger(/*Radix=*/0, result))
|
|
|
|
|
llvmFunc->addFnAttr(
|
|
|
|
|
llvm::Attribute::get(llvmFunc->getContext(), kind, result));
|
|
|
|
|
else
|
|
|
|
|
llvmFunc->addFnAttr(key, value);
|
|
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!value.empty())
|
|
|
|
|
return emitError(loc) << "LLVM attribute '" << key
|
|
|
|
|
<< "' does not expect a value, found '" << value
|
|
|
|
|
<< "'";
|
|
|
|
|
|
|
|
|
|
llvmFunc->addFnAttr(kind);
|
|
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Attaches the attributes listed in the given array attribute to `llvmFunc`.
|
|
|
|
|
/// Reports error to `loc` if any and returns immediately. Expects `attributes`
|
|
|
|
|
/// to be an array attribute containing either string attributes, treated as
|
|
|
|
|
/// value-less LLVM attributes, or array attributes containing two string
|
|
|
|
|
/// attributes, with the first string being the name of the corresponding LLVM
|
|
|
|
|
/// attribute and the second string beings its value. Note that even integer
|
|
|
|
|
/// attributes are expected to have their values expressed as strings.
|
|
|
|
|
static LogicalResult
|
2022-12-14 11:39:19 +01:00
|
|
|
forwardPassthroughAttributes(Location loc, std::optional<ArrayAttr> attributes,
|
2020-03-30 18:50:42 +02:00
|
|
|
llvm::Function *llvmFunc) {
|
|
|
|
|
if (!attributes)
|
|
|
|
|
return success();
|
|
|
|
|
|
|
|
|
|
for (Attribute attr : *attributes) {
|
|
|
|
|
if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
|
|
|
|
|
if (failed(
|
|
|
|
|
checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
|
|
|
|
|
return failure();
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
auto arrayAttr = attr.dyn_cast<ArrayAttr>();
|
|
|
|
|
if (!arrayAttr || arrayAttr.size() != 2)
|
|
|
|
|
return emitError(loc)
|
|
|
|
|
<< "expected 'passthrough' to contain string or array attributes";
|
|
|
|
|
|
|
|
|
|
auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>();
|
|
|
|
|
auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>();
|
|
|
|
|
if (!keyAttr || !valueAttr)
|
|
|
|
|
return emitError(loc)
|
|
|
|
|
<< "expected arrays within 'passthrough' to contain two strings";
|
|
|
|
|
|
|
|
|
|
if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
|
|
|
|
|
valueAttr.getValue())))
|
|
|
|
|
return failure();
|
|
|
|
|
}
|
|
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-10 01:33:33 -07:00
|
|
|
LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
|
2020-12-08 16:09:20 +01:00
|
|
|
// Clear the block, branch value mappings, they are only relevant within one
|
2019-04-30 06:08:21 -07:00
|
|
|
// function.
|
|
|
|
|
blockMapping.clear();
|
|
|
|
|
valueMapping.clear();
|
2020-12-08 16:09:20 +01:00
|
|
|
branchMapping.clear();
|
2021-02-10 19:21:45 +01:00
|
|
|
llvm::Function *llvmFunc = lookupFunction(func.getName());
|
2020-02-05 17:10:55 -08:00
|
|
|
|
|
|
|
|
// Translate the debug information for this function.
|
|
|
|
|
debugTranslation->translate(func, *llvmFunc);
|
|
|
|
|
|
2019-04-30 06:08:21 -07:00
|
|
|
// Add function arguments to the value remapping table.
|
2022-11-02 12:47:50 -07:00
|
|
|
for (auto [mlirArg, llvmArg] :
|
|
|
|
|
llvm::zip(func.getArguments(), llvmFunc->args()))
|
2021-02-10 19:21:45 +01:00
|
|
|
mapValue(mlirArg, &llvmArg);
|
2019-04-30 06:08:21 -07:00
|
|
|
|
2020-03-19 13:09:31 +01:00
|
|
|
// Check the personality and set it.
|
2022-06-20 11:22:37 -07:00
|
|
|
if (func.getPersonality()) {
|
2020-03-19 13:09:31 +01:00
|
|
|
llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
|
2021-10-29 13:29:48 -07:00
|
|
|
if (llvm::Constant *pfunc = getLLVMConstant(ty, func.getPersonalityAttr(),
|
|
|
|
|
func.getLoc(), *this))
|
2020-03-19 13:09:31 +01:00
|
|
|
llvmFunc->setPersonalityFn(pfunc);
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-11 10:23:35 +01:00
|
|
|
if (auto gc = func.getGarbageCollector())
|
|
|
|
|
llvmFunc->setGC(gc->str());
|
|
|
|
|
|
2019-04-30 06:08:21 -07:00
|
|
|
// First, create all blocks so we can jump to them.
|
|
|
|
|
llvm::LLVMContext &llvmContext = llvmFunc->getContext();
|
|
|
|
|
for (auto &bb : func) {
|
|
|
|
|
auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
|
|
|
|
|
llvmBB->insertInto(llvmFunc);
|
2021-02-10 19:21:45 +01:00
|
|
|
mapBlock(&bb, llvmBB);
|
2019-04-30 06:08:21 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Then, convert blocks one by one in topological order to ensure defs are
|
|
|
|
|
// converted before uses.
|
2021-02-11 15:01:43 +01:00
|
|
|
auto blocks = detail::getTopologicallySortedBlocks(func.getBody());
|
2021-01-05 16:04:00 +01:00
|
|
|
for (Block *bb : blocks) {
|
|
|
|
|
llvm::IRBuilder<> builder(llvmContext);
|
|
|
|
|
if (failed(convertBlock(*bb, bb->isEntryBlock(), builder)))
|
2019-08-09 10:45:15 -07:00
|
|
|
return failure();
|
2019-04-30 06:08:21 -07:00
|
|
|
}
|
|
|
|
|
|
2021-02-12 12:53:27 +01:00
|
|
|
// After all blocks have been traversed and values mapped, connect the PHI
|
|
|
|
|
// nodes to the results of preceding blocks.
|
2021-02-11 15:01:43 +01:00
|
|
|
detail::connectPHINodes(func.getBody(), *this);
|
2021-02-12 12:53:27 +01:00
|
|
|
|
|
|
|
|
// Finally, convert dialect attributes attached to the function.
|
|
|
|
|
return convertDialectAttributes(func);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) {
|
|
|
|
|
for (NamedAttribute attribute : op->getDialectAttrs())
|
|
|
|
|
if (failed(iface.amendOperation(op, attribute, *this)))
|
|
|
|
|
return failure();
|
2019-08-09 10:45:15 -07:00
|
|
|
return success();
|
2019-04-30 06:08:21 -07:00
|
|
|
}
|
|
|
|
|
|
2020-07-06 16:49:52 -07:00
|
|
|
LogicalResult ModuleTranslation::convertFunctionSignatures() {
|
2019-04-30 06:08:21 -07:00
|
|
|
// Declare all functions first because there may be function calls that form a
|
2020-07-06 16:49:52 -07:00
|
|
|
// call graph with cycles, or global initializers that reference functions.
|
2019-12-16 01:35:03 -08:00
|
|
|
for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
|
2019-10-10 01:33:33 -07:00
|
|
|
llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
|
|
|
|
|
function.getName(),
|
2022-03-15 17:36:15 -07:00
|
|
|
cast<llvm::FunctionType>(convertType(function.getFunctionType())));
|
2020-03-30 18:50:42 +02:00
|
|
|
llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
|
2021-10-29 13:29:48 -07:00
|
|
|
llvmFunc->setLinkage(convertLinkageToLLVM(function.getLinkage()));
|
2023-01-11 09:12:48 -08:00
|
|
|
llvmFunc->setCallingConv(convertCConvToLLVM(function.getCConv()));
|
2021-02-10 19:21:45 +01:00
|
|
|
mapFunction(function.getName(), llvmFunc);
|
2021-10-29 13:29:48 -07:00
|
|
|
addRuntimePreemptionSpecifier(function.getDsoLocal(), llvmFunc);
|
2020-03-30 18:50:42 +02:00
|
|
|
|
2022-11-07 12:48:32 -08:00
|
|
|
// Convert function attributes.
|
2022-08-08 17:47:05 -07:00
|
|
|
if (function->getAttrOfType<UnitAttr>(LLVMDialect::getReadnoneAttrName()))
|
2022-10-21 16:22:26 +02:00
|
|
|
llvmFunc->setDoesNotAccessMemory();
|
2022-08-08 17:47:05 -07:00
|
|
|
|
2023-01-05 13:21:57 +01:00
|
|
|
// Convert function_entry_count attribute to metadata.
|
|
|
|
|
if (std::optional<uint64_t> entryCount = function.getFunctionEntryCount())
|
|
|
|
|
llvmFunc->setEntryCount(entryCount.value());
|
|
|
|
|
|
2022-11-07 12:48:32 -08:00
|
|
|
// Convert result attributes.
|
|
|
|
|
if (ArrayAttr allResultAttrs = function.getAllResultAttrs()) {
|
|
|
|
|
llvm::AttrBuilder retAttrs(llvmFunc->getContext());
|
|
|
|
|
DictionaryAttr resultAttrs = allResultAttrs[0].cast<DictionaryAttr>();
|
|
|
|
|
for (const NamedAttribute &attr : resultAttrs) {
|
|
|
|
|
StringAttr name = attr.getName();
|
|
|
|
|
if (name == LLVMDialect::getAlignAttrName()) {
|
|
|
|
|
auto alignAmount = attr.getValue().cast<IntegerAttr>();
|
|
|
|
|
retAttrs.addAlignmentAttr(llvm::Align(alignAmount.getInt()));
|
|
|
|
|
} else if (name == LLVMDialect::getNoAliasAttrName()) {
|
|
|
|
|
retAttrs.addAttribute(llvm::Attribute::NoAlias);
|
|
|
|
|
} else if (name == LLVMDialect::getNoUndefAttrName()) {
|
|
|
|
|
retAttrs.addAttribute(llvm::Attribute::NoUndef);
|
|
|
|
|
} else if (name == LLVMDialect::getSExtAttrName()) {
|
|
|
|
|
retAttrs.addAttribute(llvm::Attribute::SExt);
|
|
|
|
|
} else if (name == LLVMDialect::getZExtAttrName()) {
|
|
|
|
|
retAttrs.addAttribute(llvm::Attribute::ZExt);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
llvmFunc->addRetAttrs(retAttrs);
|
|
|
|
|
}
|
|
|
|
|
|
2022-11-02 12:47:50 -07:00
|
|
|
// Convert argument attributes.
|
|
|
|
|
unsigned int argIdx = 0;
|
|
|
|
|
for (auto [mlirArgTy, llvmArg] :
|
|
|
|
|
llvm::zip(function.getArgumentTypes(), llvmFunc->args())) {
|
|
|
|
|
if (auto attr = function.getArgAttrOfType<UnitAttr>(
|
|
|
|
|
argIdx, LLVMDialect::getNoAliasAttrName())) {
|
|
|
|
|
// NB: Attribute already verified to be boolean, so check if we can
|
|
|
|
|
// indeed attach the attribute to this argument, based on its type.
|
|
|
|
|
if (!mlirArgTy.isa<LLVM::LLVMPointerType>())
|
|
|
|
|
return function.emitError(
|
|
|
|
|
"llvm.noalias attribute attached to LLVM non-pointer argument");
|
|
|
|
|
llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
|
|
|
|
|
}
|
2022-12-08 17:59:22 +01:00
|
|
|
if (auto attr = function.getArgAttrOfType<UnitAttr>(
|
|
|
|
|
argIdx, LLVMDialect::getReadonlyAttrName())) {
|
|
|
|
|
if (!mlirArgTy.isa<LLVM::LLVMPointerType>())
|
|
|
|
|
return function.emitError(
|
|
|
|
|
"llvm.readonly attribute attached to LLVM non-pointer argument");
|
|
|
|
|
llvmArg.addAttr(llvm::Attribute::AttrKind::ReadOnly);
|
|
|
|
|
}
|
2022-11-02 12:47:50 -07:00
|
|
|
|
|
|
|
|
if (auto attr = function.getArgAttrOfType<IntegerAttr>(
|
|
|
|
|
argIdx, LLVMDialect::getAlignAttrName())) {
|
|
|
|
|
// NB: Attribute already verified to be int, so check if we can indeed
|
|
|
|
|
// attach the attribute to this argument, based on its type.
|
|
|
|
|
if (!mlirArgTy.isa<LLVM::LLVMPointerType>())
|
|
|
|
|
return function.emitError(
|
|
|
|
|
"llvm.align attribute attached to LLVM non-pointer argument");
|
|
|
|
|
llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext())
|
|
|
|
|
.addAlignmentAttr(llvm::Align(attr.getInt())));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (auto attr = function.getArgAttrOfType<TypeAttr>(
|
|
|
|
|
argIdx, LLVMDialect::getStructRetAttrName())) {
|
|
|
|
|
auto argTy = mlirArgTy.dyn_cast<LLVM::LLVMPointerType>();
|
|
|
|
|
if (!argTy)
|
|
|
|
|
return function.emitError(
|
|
|
|
|
"llvm.sret attribute attached to LLVM non-pointer argument");
|
|
|
|
|
if (!argTy.isOpaque() && argTy.getElementType() != attr.getValue())
|
|
|
|
|
return function.emitError(
|
|
|
|
|
"llvm.sret attribute attached to LLVM pointer "
|
|
|
|
|
"argument of a different type");
|
|
|
|
|
llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext())
|
|
|
|
|
.addStructRetAttr(convertType(attr.getValue())));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (auto attr = function.getArgAttrOfType<TypeAttr>(
|
|
|
|
|
argIdx, LLVMDialect::getByValAttrName())) {
|
|
|
|
|
auto argTy = mlirArgTy.dyn_cast<LLVM::LLVMPointerType>();
|
|
|
|
|
if (!argTy)
|
|
|
|
|
return function.emitError(
|
|
|
|
|
"llvm.byval attribute attached to LLVM non-pointer argument");
|
|
|
|
|
if (!argTy.isOpaque() && argTy.getElementType() != attr.getValue())
|
|
|
|
|
return function.emitError(
|
|
|
|
|
"llvm.byval attribute attached to LLVM pointer "
|
|
|
|
|
"argument of a different type");
|
|
|
|
|
llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext())
|
|
|
|
|
.addByValAttr(convertType(attr.getValue())));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (auto attr = function.getArgAttrOfType<TypeAttr>(
|
|
|
|
|
argIdx, LLVMDialect::getByRefAttrName())) {
|
|
|
|
|
auto argTy = mlirArgTy.dyn_cast<LLVM::LLVMPointerType>();
|
|
|
|
|
if (!argTy)
|
|
|
|
|
return function.emitError(
|
|
|
|
|
"llvm.byref attribute attached to LLVM non-pointer argument");
|
|
|
|
|
if (!argTy.isOpaque() && argTy.getElementType() != attr.getValue())
|
|
|
|
|
return function.emitError(
|
|
|
|
|
"llvm.byref attribute attached to LLVM pointer "
|
|
|
|
|
"argument of a different type");
|
|
|
|
|
llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext())
|
|
|
|
|
.addByRefAttr(convertType(attr.getValue())));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (auto attr = function.getArgAttrOfType<TypeAttr>(
|
|
|
|
|
argIdx, LLVMDialect::getInAllocaAttrName())) {
|
|
|
|
|
auto argTy = mlirArgTy.dyn_cast<LLVM::LLVMPointerType>();
|
|
|
|
|
if (!argTy)
|
|
|
|
|
return function.emitError(
|
|
|
|
|
"llvm.inalloca attribute attached to LLVM non-pointer argument");
|
|
|
|
|
if (!argTy.isOpaque() && argTy.getElementType() != attr.getValue())
|
|
|
|
|
return function.emitError(
|
|
|
|
|
"llvm.inalloca attribute attached to LLVM pointer "
|
|
|
|
|
"argument of a different type");
|
|
|
|
|
llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext())
|
|
|
|
|
.addInAllocaAttr(convertType(attr.getValue())));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (auto attr =
|
|
|
|
|
function.getArgAttrOfType<UnitAttr>(argIdx, "llvm.nest")) {
|
|
|
|
|
if (!mlirArgTy.isa<LLVM::LLVMPointerType>())
|
|
|
|
|
return function.emitError(
|
|
|
|
|
"llvm.nest attribute attached to LLVM non-pointer argument");
|
|
|
|
|
llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext())
|
|
|
|
|
.addAttribute(llvm::Attribute::Nest));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (auto attr = function.getArgAttrOfType<UnitAttr>(
|
|
|
|
|
argIdx, LLVMDialect::getNoUndefAttrName())) {
|
|
|
|
|
// llvm.noundef can be added to any argument type.
|
|
|
|
|
llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext())
|
|
|
|
|
.addAttribute(llvm::Attribute::NoUndef));
|
|
|
|
|
}
|
2022-11-03 09:07:44 -07:00
|
|
|
if (auto attr = function.getArgAttrOfType<UnitAttr>(
|
|
|
|
|
argIdx, LLVMDialect::getSExtAttrName())) {
|
|
|
|
|
// llvm.signext can be added to any integer argument type.
|
|
|
|
|
if (!mlirArgTy.isa<mlir::IntegerType>())
|
|
|
|
|
return function.emitError(
|
|
|
|
|
"llvm.signext attribute attached to LLVM non-integer argument");
|
|
|
|
|
llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext())
|
|
|
|
|
.addAttribute(llvm::Attribute::SExt));
|
|
|
|
|
}
|
|
|
|
|
if (auto attr = function.getArgAttrOfType<UnitAttr>(
|
|
|
|
|
argIdx, LLVMDialect::getZExtAttrName())) {
|
|
|
|
|
// llvm.zeroext can be added to any integer argument type.
|
|
|
|
|
if (!mlirArgTy.isa<mlir::IntegerType>())
|
|
|
|
|
return function.emitError(
|
|
|
|
|
"llvm.zeroext attribute attached to LLVM non-integer argument");
|
|
|
|
|
llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext())
|
|
|
|
|
.addAttribute(llvm::Attribute::ZExt));
|
|
|
|
|
}
|
|
|
|
|
|
2022-11-02 12:47:50 -07:00
|
|
|
++argIdx;
|
|
|
|
|
}
|
|
|
|
|
|
2020-03-30 18:50:42 +02:00
|
|
|
// Forward the pass-through attributes to LLVM.
|
2021-10-29 13:29:48 -07:00
|
|
|
if (failed(forwardPassthroughAttributes(
|
|
|
|
|
function.getLoc(), function.getPassthrough(), llvmFunc)))
|
2020-03-30 18:50:42 +02:00
|
|
|
return failure();
|
2019-04-30 06:08:21 -07:00
|
|
|
}
|
|
|
|
|
|
2020-07-06 16:49:52 -07:00
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
LogicalResult ModuleTranslation::convertFunctions() {
|
2019-04-30 06:08:21 -07:00
|
|
|
// Convert functions.
|
2019-12-16 01:35:03 -08:00
|
|
|
for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
|
2019-04-30 06:08:21 -07:00
|
|
|
// Ignore external functions.
|
|
|
|
|
if (function.isExternal())
|
|
|
|
|
continue;
|
|
|
|
|
|
2019-08-09 10:45:15 -07:00
|
|
|
if (failed(convertOneFunction(function)))
|
|
|
|
|
return failure();
|
2019-04-30 06:08:21 -07:00
|
|
|
}
|
|
|
|
|
|
2019-08-09 10:45:15 -07:00
|
|
|
return success();
|
2019-04-30 06:08:21 -07:00
|
|
|
}
|
|
|
|
|
|
2021-03-04 09:00:18 +01:00
|
|
|
llvm::MDNode *
|
|
|
|
|
ModuleTranslation::getAccessGroup(Operation &opInst,
|
|
|
|
|
SymbolRefAttr accessGroupRef) const {
|
|
|
|
|
auto metadataName = accessGroupRef.getRootReference();
|
|
|
|
|
auto accessGroupName = accessGroupRef.getLeafReference();
|
|
|
|
|
auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
|
|
|
|
|
opInst.getParentOp(), metadataName);
|
|
|
|
|
auto *accessGroupOp =
|
|
|
|
|
SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName);
|
|
|
|
|
return accessGroupMetadataMapping.lookup(accessGroupOp);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
LogicalResult ModuleTranslation::createAccessGroupMetadata() {
|
|
|
|
|
mlirModule->walk([&](LLVM::MetadataOp metadatas) {
|
|
|
|
|
metadatas.walk([&](LLVM::AccessGroupMetadataOp op) {
|
|
|
|
|
llvm::LLVMContext &ctx = llvmModule->getContext();
|
|
|
|
|
llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {});
|
|
|
|
|
accessGroupMetadataMapping.insert({op, accessGroup});
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
2021-03-04 18:12:56 +01:00
|
|
|
void ModuleTranslation::setAccessGroupsMetadata(Operation *op,
|
|
|
|
|
llvm::Instruction *inst) {
|
|
|
|
|
auto accessGroups =
|
|
|
|
|
op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName());
|
|
|
|
|
if (accessGroups && !accessGroups.empty()) {
|
|
|
|
|
llvm::Module *module = inst->getModule();
|
|
|
|
|
SmallVector<llvm::Metadata *> metadatas;
|
|
|
|
|
for (SymbolRefAttr accessGroupRef :
|
|
|
|
|
accessGroups.getAsRange<SymbolRefAttr>())
|
|
|
|
|
metadatas.push_back(getAccessGroup(*op, accessGroupRef));
|
|
|
|
|
|
|
|
|
|
llvm::MDNode *unionMD = nullptr;
|
|
|
|
|
if (metadatas.size() == 1)
|
|
|
|
|
unionMD = llvm::cast<llvm::MDNode>(metadatas.front());
|
|
|
|
|
else if (metadatas.size() >= 2)
|
|
|
|
|
unionMD = llvm::MDNode::get(module->getContext(), metadatas);
|
|
|
|
|
|
|
|
|
|
inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-08-24 20:38:32 +02:00
|
|
|
LogicalResult ModuleTranslation::createAliasScopeMetadata() {
|
|
|
|
|
mlirModule->walk([&](LLVM::MetadataOp metadatas) {
|
|
|
|
|
// Create the domains first, so they can be reference below in the scopes.
|
|
|
|
|
DenseMap<Operation *, llvm::MDNode *> aliasScopeDomainMetadataMapping;
|
|
|
|
|
metadatas.walk([&](LLVM::AliasScopeDomainMetadataOp op) {
|
|
|
|
|
llvm::LLVMContext &ctx = llvmModule->getContext();
|
|
|
|
|
llvm::SmallVector<llvm::Metadata *, 2> operands;
|
|
|
|
|
operands.push_back({}); // Placeholder for self-reference
|
2022-12-14 11:39:19 +01:00
|
|
|
if (std::optional<StringRef> description = op.getDescription())
|
2022-06-20 23:20:25 -07:00
|
|
|
operands.push_back(llvm::MDString::get(ctx, *description));
|
2021-08-24 20:38:32 +02:00
|
|
|
llvm::MDNode *domain = llvm::MDNode::get(ctx, operands);
|
|
|
|
|
domain->replaceOperandWith(0, domain); // Self-reference for uniqueness
|
|
|
|
|
aliasScopeDomainMetadataMapping.insert({op, domain});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Now create the scopes, referencing the domains created above.
|
|
|
|
|
metadatas.walk([&](LLVM::AliasScopeMetadataOp op) {
|
|
|
|
|
llvm::LLVMContext &ctx = llvmModule->getContext();
|
|
|
|
|
assert(isa<LLVM::MetadataOp>(op->getParentOp()));
|
|
|
|
|
auto metadataOp = dyn_cast<LLVM::MetadataOp>(op->getParentOp());
|
|
|
|
|
Operation *domainOp =
|
2021-10-24 18:36:33 -07:00
|
|
|
SymbolTable::lookupNearestSymbolFrom(metadataOp, op.getDomainAttr());
|
2021-08-24 20:38:32 +02:00
|
|
|
llvm::MDNode *domain = aliasScopeDomainMetadataMapping.lookup(domainOp);
|
|
|
|
|
assert(domain && "Scope's domain should already be valid");
|
|
|
|
|
llvm::SmallVector<llvm::Metadata *, 3> operands;
|
|
|
|
|
operands.push_back({}); // Placeholder for self-reference
|
|
|
|
|
operands.push_back(domain);
|
2022-12-14 11:39:19 +01:00
|
|
|
if (std::optional<StringRef> description = op.getDescription())
|
2022-06-20 23:20:25 -07:00
|
|
|
operands.push_back(llvm::MDString::get(ctx, *description));
|
2021-08-24 20:38:32 +02:00
|
|
|
llvm::MDNode *scope = llvm::MDNode::get(ctx, operands);
|
|
|
|
|
scope->replaceOperandWith(0, scope); // Self-reference for uniqueness
|
|
|
|
|
aliasScopeMetadataMapping.insert({op, scope});
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
llvm::MDNode *
|
|
|
|
|
ModuleTranslation::getAliasScope(Operation &opInst,
|
|
|
|
|
SymbolRefAttr aliasScopeRef) const {
|
2021-08-29 14:22:24 -07:00
|
|
|
StringAttr metadataName = aliasScopeRef.getRootReference();
|
|
|
|
|
StringAttr scopeName = aliasScopeRef.getLeafReference();
|
2021-08-24 20:38:32 +02:00
|
|
|
auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
|
|
|
|
|
opInst.getParentOp(), metadataName);
|
|
|
|
|
Operation *aliasScopeOp =
|
|
|
|
|
SymbolTable::lookupNearestSymbolFrom(metadataOp, scopeName);
|
|
|
|
|
return aliasScopeMetadataMapping.lookup(aliasScopeOp);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ModuleTranslation::setAliasScopeMetadata(Operation *op,
|
|
|
|
|
llvm::Instruction *inst) {
|
|
|
|
|
auto populateScopeMetadata = [this, op, inst](StringRef attrName,
|
|
|
|
|
StringRef llvmMetadataName) {
|
|
|
|
|
auto scopes = op->getAttrOfType<ArrayAttr>(attrName);
|
|
|
|
|
if (!scopes || scopes.empty())
|
|
|
|
|
return;
|
|
|
|
|
llvm::Module *module = inst->getModule();
|
|
|
|
|
SmallVector<llvm::Metadata *> scopeMDs;
|
|
|
|
|
for (SymbolRefAttr scopeRef : scopes.getAsRange<SymbolRefAttr>())
|
|
|
|
|
scopeMDs.push_back(getAliasScope(*op, scopeRef));
|
2021-09-21 11:39:43 +02:00
|
|
|
llvm::MDNode *unionMD = llvm::MDNode::get(module->getContext(), scopeMDs);
|
2021-08-24 20:38:32 +02:00
|
|
|
inst->setMetadata(module->getMDKindID(llvmMetadataName), unionMD);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
populateScopeMetadata(LLVMDialect::getAliasScopesAttrName(), "alias.scope");
|
|
|
|
|
populateScopeMetadata(LLVMDialect::getNoAliasScopesAttrName(), "noalias");
|
|
|
|
|
}
|
|
|
|
|
|
2022-12-29 15:14:41 -08:00
|
|
|
llvm::MDNode *ModuleTranslation::getTBAANode(Operation &memOp,
|
|
|
|
|
SymbolRefAttr tagRef) const {
|
|
|
|
|
StringAttr metadataName = tagRef.getRootReference();
|
|
|
|
|
StringAttr tagName = tagRef.getLeafReference();
|
|
|
|
|
auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
|
|
|
|
|
memOp.getParentOp(), metadataName);
|
|
|
|
|
Operation *tagOp = SymbolTable::lookupNearestSymbolFrom(metadataOp, tagName);
|
|
|
|
|
return tbaaMetadataMapping.lookup(tagOp);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ModuleTranslation::setTBAAMetadata(Operation *op,
|
|
|
|
|
llvm::Instruction *inst) {
|
|
|
|
|
auto tbaa = op->getAttrOfType<ArrayAttr>(LLVMDialect::getTBAAAttrName());
|
|
|
|
|
if (!tbaa || tbaa.empty())
|
|
|
|
|
return;
|
|
|
|
|
// LLVM IR currently does not support attaching more than one
|
|
|
|
|
// TBAA access tag to a memory accessing instruction.
|
|
|
|
|
// It may be useful to support this in future, but for the time being
|
|
|
|
|
// just ignore the metadata if MLIR operation has multiple access tags.
|
|
|
|
|
if (tbaa.size() > 1) {
|
|
|
|
|
op->emitWarning() << "TBAA access tags were not translated, because LLVM "
|
|
|
|
|
"IR only supports a single tag per instruction";
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
SymbolRefAttr tagRef = tbaa[0].cast<SymbolRefAttr>();
|
|
|
|
|
llvm::MDNode *tagNode = getTBAANode(*op, tagRef);
|
|
|
|
|
inst->setMetadata(llvm::LLVMContext::MD_tbaa, tagNode);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
LogicalResult ModuleTranslation::createTBAAMetadata() {
|
|
|
|
|
llvm::LLVMContext &ctx = llvmModule->getContext();
|
|
|
|
|
llvm::IntegerType *offsetTy = llvm::IntegerType::get(ctx, 64);
|
|
|
|
|
|
|
|
|
|
// Walk TBAA metadata and create MDNode's with placeholder
|
|
|
|
|
// operands for the references of other TBAA nodes.
|
|
|
|
|
for (auto metadata : getModuleBody(mlirModule).getOps<LLVM::MetadataOp>()) {
|
|
|
|
|
for (auto &op : metadata.getBody().getOps()) {
|
|
|
|
|
SmallVector<llvm::Metadata *> operands;
|
|
|
|
|
if (auto rootOp = dyn_cast<LLVM::TBAARootMetadataOp>(op)) {
|
|
|
|
|
operands.push_back(llvm::MDString::get(ctx, rootOp.getIdentity()));
|
|
|
|
|
} else if (auto tdOp = dyn_cast<LLVM::TBAATypeDescriptorOp>(op)) {
|
|
|
|
|
operands.push_back(llvm::MDString::get(
|
|
|
|
|
ctx, tdOp.getIdentity().value_or(llvm::StringRef{})));
|
|
|
|
|
for (int64_t offset : tdOp.getOffsets()) {
|
2023-01-16 12:38:31 -08:00
|
|
|
// Use temporary MDNode as the placeholder for the member type
|
|
|
|
|
// to prevent uniquing the type descriptor nodes until they are
|
|
|
|
|
// finalized.
|
|
|
|
|
operands.push_back(
|
|
|
|
|
llvm::MDNode::getTemporary(ctx, std::nullopt).release());
|
2022-12-29 15:14:41 -08:00
|
|
|
operands.push_back(llvm::ConstantAsMetadata::get(
|
|
|
|
|
llvm::ConstantInt::get(offsetTy, offset)));
|
|
|
|
|
}
|
|
|
|
|
} else if (auto tagOp = dyn_cast<LLVM::TBAATagOp>(op)) {
|
2023-01-16 12:38:31 -08:00
|
|
|
// Use temporary MDNode's as the placeholders for the base and access
|
|
|
|
|
// types to prevent uniquing the tag nodes until they are finalized.
|
|
|
|
|
operands.push_back(
|
|
|
|
|
llvm::MDNode::getTemporary(ctx, std::nullopt).release());
|
|
|
|
|
operands.push_back(
|
|
|
|
|
llvm::MDNode::getTemporary(ctx, std::nullopt).release());
|
2022-12-29 15:14:41 -08:00
|
|
|
operands.push_back(llvm::ConstantAsMetadata::get(
|
|
|
|
|
llvm::ConstantInt::get(offsetTy, tagOp.getOffset())));
|
|
|
|
|
if (tagOp.getConstant())
|
|
|
|
|
operands.push_back(llvm::ConstantAsMetadata::get(
|
|
|
|
|
llvm::ConstantInt::get(offsetTy, 1)));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (operands.empty())
|
|
|
|
|
continue;
|
|
|
|
|
|
|
|
|
|
tbaaMetadataMapping.insert({&op, llvm::MDNode::get(ctx, operands)});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Walk TBAA metadata second time and update the placeholder
|
|
|
|
|
// references.
|
|
|
|
|
for (auto metadata : getModuleBody(mlirModule).getOps<LLVM::MetadataOp>()) {
|
|
|
|
|
for (auto &op : metadata.getBody().getOps()) {
|
|
|
|
|
SmallVector<StringRef> refNames;
|
|
|
|
|
SmallVector<int64_t> operandIndices;
|
|
|
|
|
if (auto tdOp = dyn_cast<LLVM::TBAATypeDescriptorOp>(op)) {
|
|
|
|
|
// The type references are in 1, 3, 5, etc. positions.
|
|
|
|
|
unsigned opNum = 1;
|
|
|
|
|
for (Attribute typeAttr : tdOp.getMembers()) {
|
|
|
|
|
refNames.push_back(typeAttr.cast<FlatSymbolRefAttr>().getValue());
|
|
|
|
|
operandIndices.push_back(opNum);
|
|
|
|
|
opNum += 2;
|
|
|
|
|
}
|
|
|
|
|
} else if (auto tagOp = dyn_cast<LLVM::TBAATagOp>(op)) {
|
|
|
|
|
refNames.push_back(tagOp.getBaseType());
|
|
|
|
|
operandIndices.push_back(0);
|
|
|
|
|
refNames.push_back(tagOp.getAccessType());
|
|
|
|
|
operandIndices.push_back(1);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (refNames.empty())
|
|
|
|
|
continue;
|
|
|
|
|
|
|
|
|
|
llvm::MDNode *descNode = tbaaMetadataMapping.lookup(&op);
|
|
|
|
|
for (auto [refName, opNum] : llvm::zip(refNames, operandIndices)) {
|
|
|
|
|
// refDef availability in the parent MetadataOp
|
|
|
|
|
// is checked by module verifier.
|
|
|
|
|
Operation *refDef = SymbolTable::lookupSymbolIn(metadata, refName);
|
|
|
|
|
llvm::MDNode *refNode = tbaaMetadataMapping.lookup(refDef);
|
|
|
|
|
if (!refNode) {
|
|
|
|
|
op.emitOpError() << "llvm::MDNode missing for the member '@"
|
|
|
|
|
<< refName << "'";
|
|
|
|
|
return failure();
|
|
|
|
|
}
|
|
|
|
|
descNode->replaceOperandWith(opNum, refNode);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
2021-01-05 16:22:53 +01:00
|
|
|
llvm::Type *ModuleTranslation::convertType(Type type) {
|
2020-08-05 14:44:03 +02:00
|
|
|
return typeTranslator.translateType(type);
|
2020-07-23 10:32:12 +02:00
|
|
|
}
|
|
|
|
|
|
2021-08-24 17:53:42 +02:00
|
|
|
/// A helper to look up remapped operands in the value remapping table.
|
|
|
|
|
SmallVector<llvm::Value *> ModuleTranslation::lookupValues(ValueRange values) {
|
|
|
|
|
SmallVector<llvm::Value *> remapped;
|
2019-12-19 11:34:43 -08:00
|
|
|
remapped.reserve(values.size());
|
2021-02-10 19:21:45 +01:00
|
|
|
for (Value v : values)
|
|
|
|
|
remapped.push_back(lookupValue(v));
|
2019-12-19 11:34:43 -08:00
|
|
|
return remapped;
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-11 15:01:43 +01:00
|
|
|
const llvm::DILocation *
|
|
|
|
|
ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) {
|
|
|
|
|
return debugTranslation->translateLoc(loc, scope);
|
|
|
|
|
}
|
|
|
|
|
|
2022-10-22 16:28:32 -07:00
|
|
|
llvm::Metadata *ModuleTranslation::translateDebugInfo(LLVM::DINodeAttr attr) {
|
|
|
|
|
return debugTranslation->translate(attr);
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-12 12:53:27 +01:00
|
|
|
llvm::NamedMDNode *
|
|
|
|
|
ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) {
|
|
|
|
|
return llvmModule->getOrInsertNamedMetadata(name);
|
|
|
|
|
}
|
|
|
|
|
|
2021-05-10 10:02:18 +02:00
|
|
|
void ModuleTranslation::StackFrame::anchor() {}
|
|
|
|
|
|
2021-02-16 17:36:45 +01:00
|
|
|
static std::unique_ptr<llvm::Module>
|
|
|
|
|
prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext,
|
|
|
|
|
StringRef name) {
|
Separate the Registration from Loading dialects in the Context
This changes the behavior of constructing MLIRContext to no longer load globally
registered dialects on construction. Instead Dialects are only loaded explicitly
on demand:
- the Parser is lazily loading Dialects in the context as it encounters them
during parsing. This is the only purpose for registering dialects and not load
them in the context.
- Passes are expected to declare the dialects they will create entity from
(Operations, Attributes, or Types), and the PassManager is loading Dialects into
the Context when starting a pipeline.
This changes simplifies the configuration of the registration: a compiler only
need to load the dialect for the IR it will emit, and the optimizer is
self-contained and load the required Dialects. For example in the Toy tutorial,
the compiler only needs to load the Toy dialect in the Context, all the others
(linalg, affine, std, LLVM, ...) are automatically loaded depending on the
optimization pipeline enabled.
To adjust to this change, stop using the existing dialect registration: the
global registry will be removed soon.
1) For passes, you need to override the method:
virtual void getDependentDialects(DialectRegistry ®istry) const {}
and registery on the provided registry any dialect that this pass can produce.
Passes defined in TableGen can provide this list in the dependentDialects list
field.
2) For dialects, on construction you can register dependent dialects using the
provided MLIRContext: `context.getOrLoadDialect<DialectName>()`
This is useful if a dialect may canonicalize or have interfaces involving
another dialect.
3) For loading IR, dialect that can be in the input file must be explicitly
registered with the context. `MlirOptMain()` is taking an explicit registry for
this purpose. See how the standalone-opt.cpp example is setup:
mlir::DialectRegistry registry;
registry.insert<mlir::standalone::StandaloneDialect>();
registry.insert<mlir::StandardOpsDialect>();
Only operations from these two dialects can be in the input file. To include all
of the dialects in MLIR Core, you can populate the registry this way:
mlir::registerAllDialects(registry);
4) For `mlir-translate` callback, as well as frontend, Dialects can be loaded in
the context before emitting the IR: context.getOrLoadDialect<ToyDialect>()
Differential Revision: https://reviews.llvm.org/D85622
2020-08-18 20:01:19 +00:00
|
|
|
m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>();
|
[mlir] take LLVMContext in MLIR-to-LLVM-IR translation
Due to the original type system implementation, LLVMDialect in MLIR contains an
LLVMContext in which the relevant objects (types, metadata) are created. When
an MLIR module using the LLVM dialect (and related intrinsic-based dialects
NVVM, ROCDL, AVX512) is converted to LLVM IR, it could only live in the
LLVMContext owned by the dialect. The type system no longer relies on the
LLVMContext, so this limitation can be removed. Instead, translation functions
now take a reference to an LLVMContext in which the LLVM IR module should be
constructed. The caller of the translation functions is responsible for
ensuring the same LLVMContext is not used concurrently as the translation no
longer uses a dialect-wide context lock.
As an additional bonus, this change removes the need to recreate the LLVM IR
module in a different LLVMContext through printing and parsing back, decreasing
the compilation overhead in JIT and GPU-kernel-to-blob passes.
Reviewed By: rriddle, mehdi_amini
Differential Revision: https://reviews.llvm.org/D85443
2020-08-06 18:15:47 +02:00
|
|
|
auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext);
|
2020-08-17 13:35:27 +02:00
|
|
|
if (auto dataLayoutAttr =
|
2022-03-01 18:21:38 +01:00
|
|
|
m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) {
|
2020-08-17 13:35:27 +02:00
|
|
|
llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue());
|
2022-03-01 18:21:38 +01:00
|
|
|
} else {
|
|
|
|
|
FailureOr<llvm::DataLayout> llvmDataLayout(llvm::DataLayout(""));
|
|
|
|
|
if (auto iface = dyn_cast<DataLayoutOpInterface>(m)) {
|
|
|
|
|
if (DataLayoutSpecInterface spec = iface.getDataLayoutSpec()) {
|
|
|
|
|
llvmDataLayout =
|
|
|
|
|
translateDataLayout(spec, DataLayout(iface), m->getLoc());
|
|
|
|
|
}
|
|
|
|
|
} else if (auto mod = dyn_cast<ModuleOp>(m)) {
|
|
|
|
|
if (DataLayoutSpecInterface spec = mod.getDataLayoutSpec()) {
|
|
|
|
|
llvmDataLayout =
|
|
|
|
|
translateDataLayout(spec, DataLayout(mod), m->getLoc());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if (failed(llvmDataLayout))
|
|
|
|
|
return nullptr;
|
|
|
|
|
llvmModule->setDataLayout(*llvmDataLayout);
|
|
|
|
|
}
|
2020-11-26 15:58:34 +00:00
|
|
|
if (auto targetTripleAttr =
|
|
|
|
|
m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
|
|
|
|
|
llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue());
|
2019-04-30 06:08:21 -07:00
|
|
|
|
2022-07-18 18:07:36 +00:00
|
|
|
// Inject declarations for `malloc` and `free` functions that can be used in
|
|
|
|
|
// memref allocation/deallocation coming from standard ops lowering.
|
[mlir] take LLVMContext in MLIR-to-LLVM-IR translation
Due to the original type system implementation, LLVMDialect in MLIR contains an
LLVMContext in which the relevant objects (types, metadata) are created. When
an MLIR module using the LLVM dialect (and related intrinsic-based dialects
NVVM, ROCDL, AVX512) is converted to LLVM IR, it could only live in the
LLVMContext owned by the dialect. The type system no longer relies on the
LLVMContext, so this limitation can be removed. Instead, translation functions
now take a reference to an LLVMContext in which the LLVM IR module should be
constructed. The caller of the translation functions is responsible for
ensuring the same LLVMContext is not used concurrently as the translation no
longer uses a dialect-wide context lock.
As an additional bonus, this change removes the need to recreate the LLVM IR
module in a different LLVMContext through printing and parsing back, decreasing
the compilation overhead in JIT and GPU-kernel-to-blob passes.
Reviewed By: rriddle, mehdi_amini
Differential Revision: https://reviews.llvm.org/D85443
2020-08-06 18:15:47 +02:00
|
|
|
llvm::IRBuilder<> builder(llvmContext);
|
2022-07-18 18:07:36 +00:00
|
|
|
llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
|
2019-04-30 06:08:21 -07:00
|
|
|
builder.getInt64Ty());
|
2022-07-18 18:07:36 +00:00
|
|
|
llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
|
2019-04-30 06:08:21 -07:00
|
|
|
builder.getInt8PtrTy());
|
|
|
|
|
|
|
|
|
|
return llvmModule;
|
|
|
|
|
}
|
2021-02-16 17:36:45 +01:00
|
|
|
|
|
|
|
|
std::unique_ptr<llvm::Module>
|
|
|
|
|
mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext,
|
|
|
|
|
StringRef name) {
|
2022-09-27 21:31:16 -04:00
|
|
|
if (!satisfiesLLVMModule(module)) {
|
|
|
|
|
module->emitOpError("can not be translated to an LLVMIR module");
|
2021-02-16 17:36:45 +01:00
|
|
|
return nullptr;
|
2022-09-27 21:31:16 -04:00
|
|
|
}
|
2022-03-01 18:21:38 +01:00
|
|
|
|
2021-02-16 17:36:45 +01:00
|
|
|
std::unique_ptr<llvm::Module> llvmModule =
|
|
|
|
|
prepareLLVMModule(module, llvmContext, name);
|
2022-03-01 18:21:38 +01:00
|
|
|
if (!llvmModule)
|
|
|
|
|
return nullptr;
|
2021-02-16 17:36:45 +01:00
|
|
|
|
|
|
|
|
LLVM::ensureDistinctSuccessors(module);
|
|
|
|
|
|
|
|
|
|
ModuleTranslation translator(module, std::move(llvmModule));
|
|
|
|
|
if (failed(translator.convertFunctionSignatures()))
|
|
|
|
|
return nullptr;
|
|
|
|
|
if (failed(translator.convertGlobals()))
|
|
|
|
|
return nullptr;
|
2021-03-04 09:00:18 +01:00
|
|
|
if (failed(translator.createAccessGroupMetadata()))
|
|
|
|
|
return nullptr;
|
2021-08-24 20:38:32 +02:00
|
|
|
if (failed(translator.createAliasScopeMetadata()))
|
|
|
|
|
return nullptr;
|
2022-12-29 15:14:41 -08:00
|
|
|
if (failed(translator.createTBAAMetadata()))
|
|
|
|
|
return nullptr;
|
2021-02-16 17:36:45 +01:00
|
|
|
if (failed(translator.convertFunctions()))
|
|
|
|
|
return nullptr;
|
2021-08-24 17:53:42 +02:00
|
|
|
|
|
|
|
|
// Convert other top-level operations if possible.
|
|
|
|
|
llvm::IRBuilder<> llvmBuilder(llvmContext);
|
|
|
|
|
for (Operation &o : getModuleBody(module).getOperations()) {
|
2021-10-20 15:14:54 +05:30
|
|
|
if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::GlobalCtorsOp,
|
|
|
|
|
LLVM::GlobalDtorsOp, LLVM::MetadataOp>(&o) &&
|
2021-08-24 17:53:42 +02:00
|
|
|
!o.hasTrait<OpTrait::IsTerminator>() &&
|
|
|
|
|
failed(translator.convertOperation(o, llvmBuilder))) {
|
|
|
|
|
return nullptr;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-16 17:36:45 +01:00
|
|
|
if (llvm::verifyModule(*translator.llvmModule, &llvm::errs()))
|
|
|
|
|
return nullptr;
|
|
|
|
|
|
|
|
|
|
return std::move(translator.llvmModule);
|
|
|
|
|
}
|