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"
|
2019-08-19 11:00:47 -07:00
|
|
|
#include "mlir/Dialect/LLVMIR/LLVMDialect.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"
|
2020-08-04 11:37:50 +02:00
|
|
|
#include "mlir/Target/LLVMIR/TypeTranslation.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"
|
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"
|
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"
|
|
|
|
|
|
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"
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
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
|
|
|
|
|
/// attributes and combinations thereof. 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,
|
|
|
|
|
const ModuleTranslation &moduleTranslation) {
|
2019-09-21 01:19:43 -07:00
|
|
|
if (!attr)
|
|
|
|
|
return llvm::UndefValue::get(llvmType);
|
2020-01-16 16:21:14 +01:00
|
|
|
if (llvmType->isStructTy()) {
|
|
|
|
|
emitError(loc, "struct types are not supported in constants");
|
|
|
|
|
return nullptr;
|
|
|
|
|
}
|
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()));
|
2019-04-30 06:08:21 -07:00
|
|
|
if (auto floatAttr = attr.dyn_cast<FloatAttr>())
|
|
|
|
|
return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
|
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;
|
|
|
|
|
if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
|
|
|
|
|
elementType = arrayTy->getElementType();
|
|
|
|
|
numElements = arrayTy->getNumElements();
|
|
|
|
|
} else {
|
[SVE] Remove calls to VectorType::getNumElements from mlir
Reviewers: efriedma, ftynse, rriddle
Reviewed By: ftynse, rriddle
Subscribers: tschuett, rkruppe, psnobl, mehdi_amini, rriddle, jpienaar, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, aartbik, liufengdb, stephenneuendorffer, Joonsoo, grosul1, Kayjukh, jurahul, msifontes
Tags: #mlir
Differential Revision: https://reviews.llvm.org/D82583
2020-06-29 10:15:00 -07:00
|
|
|
auto *vectorTy = cast<llvm::FixedVectorType>(llvmType);
|
2020-04-06 17:03:49 -07:00
|
|
|
elementType = vectorTy->getElementType();
|
|
|
|
|
numElements = vectorTy->getNumElements();
|
|
|
|
|
}
|
[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-02-12 12:53:27 +01:00
|
|
|
elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), 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(
|
2020-08-19 18:46:53 +02:00
|
|
|
llvm::ElementCount::get(numElements, /*Scalable=*/false), 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
|
|
|
|
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.getNumElements() != 0 &&
|
|
|
|
|
"unexpected empty elements attribute");
|
|
|
|
|
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(
|
|
|
|
|
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)),
|
2020-09-28 22:16:12 +00:00
|
|
|
ompDialect(module->getContext()->getLoadedDialect("omp")),
|
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();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// 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);
|
|
|
|
|
|
[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
|
|
|
SuccessorRange successors = terminator.getSuccessors();
|
|
|
|
|
assert(std::adjacent_find(successors.begin(), successors.end()) ==
|
|
|
|
|
successors.end() &&
|
|
|
|
|
"successors with arguments in LLVM branches must be different blocks");
|
2020-12-17 20:35:48 +01:00
|
|
|
(void)successors;
|
[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
|
|
|
|
|
? condBranchOp.trueDestOperands()[index]
|
|
|
|
|
: condBranchOp.falseDestOperands()[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.
|
|
|
|
|
if (switchOp.defaultDestination() == current)
|
|
|
|
|
return switchOp.defaultOperands()[index];
|
|
|
|
|
for (auto i : llvm::enumerate(switchOp.caseDestinations()))
|
|
|
|
|
if (i.value() == current)
|
|
|
|
|
return switchOp.getCaseOperands(i.index())[index];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
llvm_unreachable("only branch or switch 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.
|
2021-02-11 15:01:43 +01:00
|
|
|
for (auto it = std::next(region.begin()), eit = region.end(); it != eit;
|
|
|
|
|
++it) {
|
2020-07-13 23:13:04 +01:00
|
|
|
Block *bb = &*it;
|
2021-02-10 19:21:45 +01:00
|
|
|
llvm::BasicBlock *llvmBB = state.lookupBlock(bb);
|
2020-07-13 23:13:04 +01:00
|
|
|
auto phis = llvmBB->phis();
|
|
|
|
|
auto numArguments = bb->getNumArguments();
|
|
|
|
|
assert(numArguments == std::distance(phis.begin(), phis.end()));
|
|
|
|
|
for (auto &numberedPhiNode : llvm::enumerate(phis)) {
|
|
|
|
|
auto &phiNode = numberedPhiNode.value();
|
|
|
|
|
unsigned index = numberedPhiNode.index();
|
|
|
|
|
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");
|
2021-02-10 19:21:45 +01: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-02-11 15:01:43 +01:00
|
|
|
llvm::SetVector<Block *>
|
|
|
|
|
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.
|
2020-07-13 23:13:04 +01:00
|
|
|
llvm::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`.
|
2019-08-09 10:45:15 -07:00
|
|
|
LogicalResult ModuleTranslation::convertOperation(Operation &opInst,
|
|
|
|
|
llvm::IRBuilder<> &builder) {
|
2021-02-12 12:53:27 +01:00
|
|
|
if (failed(iface.convertOperation(&opInst, builder, *this)))
|
|
|
|
|
return opInst.emitError("unsupported or non-LLVM operation: ")
|
|
|
|
|
<< opInst.getName();
|
2019-08-12 06:10:29 -07:00
|
|
|
|
2021-02-12 12:53:27 +01:00
|
|
|
return convertDialectAttributes(&opInst);
|
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,
|
|
|
|
|
llvm::IRBuilder<> &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
|
|
|
}
|
|
|
|
|
|
2019-12-18 10:46:16 -08:00
|
|
|
/// Create named global variables that correspond to llvm.mlir.global
|
|
|
|
|
/// definitions.
|
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());
|
2019-11-05 15:10:28 -08:00
|
|
|
llvm::Constant *cst = llvm::UndefValue::get(type);
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
} else if (Block *initializer = op.getInitializerBlock()) {
|
|
|
|
|
llvm::IRBuilder<> builder(llvmModule->getContext());
|
|
|
|
|
for (auto &op : initializer->without_terminator()) {
|
|
|
|
|
if (failed(convertOperation(op, builder)) ||
|
2021-02-10 19:21:45 +01:00
|
|
|
!isa<llvm::Constant>(lookupValue(op.getResult(0))))
|
2020-03-02 15:18:41 +01:00
|
|
|
return emitError(op.getLoc(), "unemittable constant value");
|
2019-11-05 15:10:28 -08:00
|
|
|
}
|
|
|
|
|
ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
|
2021-02-10 19:21:45 +01:00
|
|
|
cst = cast<llvm::Constant>(lookupValue(ret.getOperand(0)));
|
2019-08-09 08:59:45 -07:00
|
|
|
}
|
|
|
|
|
|
2020-01-27 14:49:34 +01:00
|
|
|
auto linkage = convertLinkageToLLVM(op.linkage());
|
2019-12-02 03:27:38 -08:00
|
|
|
bool anyExternalLinkage =
|
2020-03-18 14:46:54 -07:00
|
|
|
((linkage == llvm::GlobalVariable::ExternalLinkage &&
|
|
|
|
|
isa<llvm::UndefValue>(cst)) ||
|
2019-12-02 03:27:38 -08:00
|
|
|
linkage == llvm::GlobalVariable::ExternalWeakLinkage);
|
2020-09-01 13:32:14 -07:00
|
|
|
auto addrSpace = op.addr_space();
|
2019-09-19 04:50:17 -07:00
|
|
|
auto *var = new llvm::GlobalVariable(
|
2019-12-02 03:27:38 -08:00
|
|
|
*llvmModule, type, op.constant(), linkage,
|
|
|
|
|
anyExternalLinkage ? nullptr : cst, op.sym_name(),
|
|
|
|
|
/*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace);
|
2019-09-19 04:50:17 -07: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
|
|
|
|
|
|
|
|
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();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (llvm::Attribute::doesAttrKindHaveArgument(kind)) {
|
|
|
|
|
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
|
|
|
|
|
forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes,
|
|
|
|
|
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.
|
|
|
|
|
// If there was noalias info then we decorate each argument accordingly.
|
|
|
|
|
unsigned int argIdx = 0;
|
2020-01-01 15:55:14 -08:00
|
|
|
for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
|
2019-04-30 06:08:21 -07:00
|
|
|
llvm::Argument &llvmArg = std::get<1>(kvp);
|
2019-12-23 14:45:01 -08:00
|
|
|
BlockArgument mlirArg = std::get<0>(kvp);
|
2019-04-30 06:08:21 -07:00
|
|
|
|
2020-11-10 16:59:54 +01:00
|
|
|
if (auto attr = func.getArgAttrOfType<BoolAttr>(
|
|
|
|
|
argIdx, LLVMDialect::getNoAliasAttrName())) {
|
2019-04-30 06:08:21 -07:00
|
|
|
// NB: Attribute already verified to be boolean, so check if we can indeed
|
|
|
|
|
// attach the attribute to this argument, based on its type.
|
2021-01-05 16:22:53 +01:00
|
|
|
auto argTy = mlirArg.getType();
|
2020-12-22 11:22:21 +01:00
|
|
|
if (!argTy.isa<LLVM::LLVMPointerType>())
|
2019-08-09 10:45:15 -07:00
|
|
|
return func.emitError(
|
2019-04-30 06:08:21 -07:00
|
|
|
"llvm.noalias attribute attached to LLVM non-pointer argument");
|
|
|
|
|
if (attr.getValue())
|
|
|
|
|
llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
|
|
|
|
|
}
|
2020-06-19 10:59:07 +02:00
|
|
|
|
2020-11-10 16:59:54 +01:00
|
|
|
if (auto attr = func.getArgAttrOfType<IntegerAttr>(
|
|
|
|
|
argIdx, LLVMDialect::getAlignAttrName())) {
|
2020-06-19 10:59:07 +02:00
|
|
|
// NB: Attribute already verified to be int, so check if we can indeed
|
|
|
|
|
// attach the attribute to this argument, based on its type.
|
2021-01-05 16:22:53 +01:00
|
|
|
auto argTy = mlirArg.getType();
|
2020-12-22 11:22:21 +01:00
|
|
|
if (!argTy.isa<LLVM::LLVMPointerType>())
|
2020-06-19 10:59:07 +02:00
|
|
|
return func.emitError(
|
|
|
|
|
"llvm.align attribute attached to LLVM non-pointer argument");
|
|
|
|
|
llvmArg.addAttrs(
|
|
|
|
|
llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt())));
|
|
|
|
|
}
|
|
|
|
|
|
2021-01-07 12:50:20 -08:00
|
|
|
if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) {
|
|
|
|
|
auto argTy = mlirArg.getType();
|
|
|
|
|
if (!argTy.isa<LLVM::LLVMPointerType>())
|
|
|
|
|
return func.emitError(
|
|
|
|
|
"llvm.sret attribute attached to LLVM non-pointer argument");
|
2021-01-26 10:18:44 -08:00
|
|
|
llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr(
|
|
|
|
|
llvmArg.getType()->getPointerElementType()));
|
2021-01-07 12:50:20 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) {
|
|
|
|
|
auto argTy = mlirArg.getType();
|
|
|
|
|
if (!argTy.isa<LLVM::LLVMPointerType>())
|
|
|
|
|
return func.emitError(
|
|
|
|
|
"llvm.byval attribute attached to LLVM non-pointer argument");
|
2021-01-26 10:18:44 -08:00
|
|
|
llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr(
|
|
|
|
|
llvmArg.getType()->getPointerElementType()));
|
2021-01-07 12:50:20 -08:00
|
|
|
}
|
|
|
|
|
|
2021-02-10 19:21:45 +01:00
|
|
|
mapValue(mlirArg, &llvmArg);
|
2019-04-30 06:08:21 -07:00
|
|
|
argIdx++;
|
|
|
|
|
}
|
|
|
|
|
|
2020-03-19 13:09:31 +01:00
|
|
|
// Check the personality and set it.
|
|
|
|
|
if (func.personality().hasValue()) {
|
|
|
|
|
llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
|
|
|
|
|
if (llvm::Constant *pfunc =
|
2021-02-12 12:53:27 +01:00
|
|
|
getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this))
|
2020-03-19 13:09:31 +01:00
|
|
|
llvmFunc->setPersonalityFn(pfunc);
|
|
|
|
|
}
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
2019-12-16 01:35:03 -08:00
|
|
|
LogicalResult ModuleTranslation::checkSupportedModuleOps(Operation *m) {
|
|
|
|
|
for (Operation &o : getModuleBody(m).getOperations())
|
2021-02-09 11:41:10 -08:00
|
|
|
if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp>(&o) &&
|
|
|
|
|
!o.hasTrait<OpTrait::IsTerminator>())
|
2019-10-10 16:01:41 -07:00
|
|
|
return o.emitOpError("unsupported module-level operation");
|
|
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
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(),
|
2020-07-23 10:32:12 +02:00
|
|
|
cast<llvm::FunctionType>(convertType(function.getType())));
|
2020-03-30 18:50:42 +02:00
|
|
|
llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
|
2020-07-20 13:54:30 +02:00
|
|
|
llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage()));
|
2021-02-10 19:21:45 +01:00
|
|
|
mapFunction(function.getName(), llvmFunc);
|
2020-03-30 18:50:42 +02:00
|
|
|
|
|
|
|
|
// Forward the pass-through attributes to LLVM.
|
|
|
|
|
if (failed(forwardPassthroughAttributes(function.getLoc(),
|
|
|
|
|
function.passthrough(), llvmFunc)))
|
|
|
|
|
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-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
|
|
|
}
|
|
|
|
|
|
2019-12-19 11:34:43 -08:00
|
|
|
/// A helper to look up remapped operands in the value remapping table.`
|
|
|
|
|
SmallVector<llvm::Value *, 8>
|
|
|
|
|
ModuleTranslation::lookupValues(ValueRange values) {
|
|
|
|
|
SmallVector<llvm::Value *, 8> remapped;
|
|
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-12 12:53:27 +01:00
|
|
|
llvm::NamedMDNode *
|
|
|
|
|
ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) {
|
|
|
|
|
return llvmModule->getOrInsertNamedMetadata(name);
|
|
|
|
|
}
|
|
|
|
|
|
[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
|
|
|
std::unique_ptr<llvm::Module> ModuleTranslation::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 =
|
|
|
|
|
m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName()))
|
|
|
|
|
llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue());
|
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
|
|
|
|
|
|
|
|
// 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);
|
2019-04-30 06:08:21 -07:00
|
|
|
llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
|
|
|
|
|
builder.getInt64Ty());
|
|
|
|
|
llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
|
|
|
|
|
builder.getInt8PtrTy());
|
|
|
|
|
|
|
|
|
|
return llvmModule;
|
|
|
|
|
}
|