Generic dialect conversion pass exercised by LLVM IR lowering
This commit introduces a generic dialect conversion/lowering/legalization pass
and illustrates it on StandardOps->LLVMIR conversion.
It partially reuses the PatternRewriter infrastructure and adds the following
functionality:
- an actual pass;
- non-default pattern constructors;
- one-to-many rewrites;
- rewriting terminators with successors;
- not applying patterns iteratively (unlike the existing greedy rewrite driver);
- ability to change function signature;
- ability to change basic block argument types.
The latter two things required, given the existing API, to create new functions
in the same module. Eventually, this should converge with the rest of
PatternRewriter. However, we may want to keep two pass versions: "heavy" with
function/block argument conversion and "light" that only touches operations.
This pass creates new functions within a module as a means to change function
signature, then creates new blocks with converted argument types in the new
function. Then, it traverses the CFG in DFS-preorder to make sure defs are
converted before uses in the dominated blocks. The generic pass has a minimal
interface with two hooks: one to fill in the set of patterns, and another one
to convert types for functions and blocks. The patterns are defined as
separate classes that can be table-generated in the future.
The LLVM IR lowering pass partially inherits from the existing LLVM IR
translator, in particular for type conversion. It defines a conversion pattern
template, instantiated for different operations, and is a good candidate for
tablegen. The lowering does not yet support loads and stores and is not
connected to the translator as it would have broken the existing flows. Future
patches will add missing support before switching the translator in a single
patch.
PiperOrigin-RevId: 230951202
2019-01-25 12:46:53 -08:00
|
|
|
//===- DialectConversion.cpp - MLIR dialect conversion generic pass -------===//
|
|
|
|
|
//
|
|
|
|
|
// Copyright 2019 The MLIR Authors.
|
|
|
|
|
//
|
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
|
//
|
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
//
|
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
|
// limitations under the License.
|
|
|
|
|
// =============================================================================
|
|
|
|
|
|
|
|
|
|
#include "mlir/Transforms/DialectConversion.h"
|
2019-06-19 13:58:31 -07:00
|
|
|
#include "mlir/IR/Block.h"
|
Generic dialect conversion pass exercised by LLVM IR lowering
This commit introduces a generic dialect conversion/lowering/legalization pass
and illustrates it on StandardOps->LLVMIR conversion.
It partially reuses the PatternRewriter infrastructure and adds the following
functionality:
- an actual pass;
- non-default pattern constructors;
- one-to-many rewrites;
- rewriting terminators with successors;
- not applying patterns iteratively (unlike the existing greedy rewrite driver);
- ability to change function signature;
- ability to change basic block argument types.
The latter two things required, given the existing API, to create new functions
in the same module. Eventually, this should converge with the rest of
PatternRewriter. However, we may want to keep two pass versions: "heavy" with
function/block argument conversion and "light" that only touches operations.
This pass creates new functions within a module as a means to change function
signature, then creates new blocks with converted argument types in the new
function. Then, it traverses the CFG in DFS-preorder to make sure defs are
converted before uses in the dominated blocks. The generic pass has a minimal
interface with two hooks: one to fill in the set of patterns, and another one
to convert types for functions and blocks. The patterns are defined as
separate classes that can be table-generated in the future.
The LLVM IR lowering pass partially inherits from the existing LLVM IR
translator, in particular for type conversion. It defines a conversion pattern
template, instantiated for different operations, and is a good candidate for
tablegen. The lowering does not yet support loads and stores and is not
connected to the translator as it would have broken the existing flows. Future
patches will add missing support before switching the translator in a single
patch.
PiperOrigin-RevId: 230951202
2019-01-25 12:46:53 -08:00
|
|
|
#include "mlir/IR/BlockAndValueMapping.h"
|
|
|
|
|
#include "mlir/IR/Builders.h"
|
|
|
|
|
#include "mlir/IR/Function.h"
|
|
|
|
|
#include "mlir/IR/Module.h"
|
|
|
|
|
#include "mlir/Transforms/Utils.h"
|
2019-06-03 12:49:55 -07:00
|
|
|
#include "llvm/ADT/SetVector.h"
|
|
|
|
|
#include "llvm/ADT/SmallPtrSet.h"
|
|
|
|
|
#include "llvm/Support/Debug.h"
|
Generic dialect conversion pass exercised by LLVM IR lowering
This commit introduces a generic dialect conversion/lowering/legalization pass
and illustrates it on StandardOps->LLVMIR conversion.
It partially reuses the PatternRewriter infrastructure and adds the following
functionality:
- an actual pass;
- non-default pattern constructors;
- one-to-many rewrites;
- rewriting terminators with successors;
- not applying patterns iteratively (unlike the existing greedy rewrite driver);
- ability to change function signature;
- ability to change basic block argument types.
The latter two things required, given the existing API, to create new functions
in the same module. Eventually, this should converge with the rest of
PatternRewriter. However, we may want to keep two pass versions: "heavy" with
function/block argument conversion and "light" that only touches operations.
This pass creates new functions within a module as a means to change function
signature, then creates new blocks with converted argument types in the new
function. Then, it traverses the CFG in DFS-preorder to make sure defs are
converted before uses in the dominated blocks. The generic pass has a minimal
interface with two hooks: one to fill in the set of patterns, and another one
to convert types for functions and blocks. The patterns are defined as
separate classes that can be table-generated in the future.
The LLVM IR lowering pass partially inherits from the existing LLVM IR
translator, in particular for type conversion. It defines a conversion pattern
template, instantiated for different operations, and is a good candidate for
tablegen. The lowering does not yet support loads and stores and is not
connected to the translator as it would have broken the existing flows. Future
patches will add missing support before switching the translator in a single
patch.
PiperOrigin-RevId: 230951202
2019-01-25 12:46:53 -08:00
|
|
|
|
|
|
|
|
using namespace mlir;
|
2019-07-18 12:04:57 -07:00
|
|
|
using namespace mlir::detail;
|
2019-06-03 12:49:55 -07:00
|
|
|
|
|
|
|
|
#define DEBUG_TYPE "dialect-conversion"
|
Generic dialect conversion pass exercised by LLVM IR lowering
This commit introduces a generic dialect conversion/lowering/legalization pass
and illustrates it on StandardOps->LLVMIR conversion.
It partially reuses the PatternRewriter infrastructure and adds the following
functionality:
- an actual pass;
- non-default pattern constructors;
- one-to-many rewrites;
- rewriting terminators with successors;
- not applying patterns iteratively (unlike the existing greedy rewrite driver);
- ability to change function signature;
- ability to change basic block argument types.
The latter two things required, given the existing API, to create new functions
in the same module. Eventually, this should converge with the rest of
PatternRewriter. However, we may want to keep two pass versions: "heavy" with
function/block argument conversion and "light" that only touches operations.
This pass creates new functions within a module as a means to change function
signature, then creates new blocks with converted argument types in the new
function. Then, it traverses the CFG in DFS-preorder to make sure defs are
converted before uses in the dominated blocks. The generic pass has a minimal
interface with two hooks: one to fill in the set of patterns, and another one
to convert types for functions and blocks. The patterns are defined as
separate classes that can be table-generated in the future.
The LLVM IR lowering pass partially inherits from the existing LLVM IR
translator, in particular for type conversion. It defines a conversion pattern
template, instantiated for different operations, and is a good candidate for
tablegen. The lowering does not yet support loads and stores and is not
connected to the translator as it would have broken the existing flows. Future
patches will add missing support before switching the translator in a single
patch.
PiperOrigin-RevId: 230951202
2019-01-25 12:46:53 -08:00
|
|
|
|
2019-10-08 15:44:34 -07:00
|
|
|
/// Recursively collect all of the operations to convert from within 'region'.
|
2019-10-28 10:03:57 -07:00
|
|
|
/// If 'target' is nonnull, operations that are recursively legal have their
|
|
|
|
|
/// regions pre-filtered to avoid considering them for legalization.
|
2019-10-08 15:44:34 -07:00
|
|
|
static LogicalResult
|
2019-12-18 09:28:48 -08:00
|
|
|
computeConversionSet(iterator_range<Region::iterator> region,
|
2019-10-28 10:03:57 -07:00
|
|
|
Location regionLoc, std::vector<Operation *> &toConvert,
|
|
|
|
|
ConversionTarget *target = nullptr) {
|
2019-10-08 15:44:34 -07:00
|
|
|
if (llvm::empty(region))
|
|
|
|
|
return success();
|
|
|
|
|
|
|
|
|
|
// Traverse starting from the entry block.
|
|
|
|
|
SmallVector<Block *, 16> worklist(1, &*region.begin());
|
|
|
|
|
DenseSet<Block *> visitedBlocks;
|
|
|
|
|
visitedBlocks.insert(worklist.front());
|
|
|
|
|
while (!worklist.empty()) {
|
2019-10-28 10:03:57 -07:00
|
|
|
Block *block = worklist.pop_back_val();
|
2019-10-08 15:44:34 -07:00
|
|
|
|
|
|
|
|
// Compute the conversion set of each of the nested operations.
|
2019-10-28 10:03:57 -07:00
|
|
|
for (Operation &op : *block) {
|
2019-10-08 15:44:34 -07:00
|
|
|
toConvert.emplace_back(&op);
|
2019-10-28 10:03:57 -07:00
|
|
|
|
|
|
|
|
// Don't check this operation's children for conversion if the operation
|
|
|
|
|
// is recursively legal.
|
|
|
|
|
auto legalityInfo = target ? target->isLegal(&op)
|
|
|
|
|
: Optional<ConversionTarget::LegalOpDetails>();
|
|
|
|
|
if (legalityInfo && legalityInfo->isRecursivelyLegal)
|
|
|
|
|
continue;
|
2019-10-08 15:44:34 -07:00
|
|
|
for (auto ®ion : op.getRegions())
|
2019-10-28 10:03:57 -07:00
|
|
|
computeConversionSet(region.getBlocks(), region.getLoc(), toConvert,
|
|
|
|
|
target);
|
2019-10-08 15:44:34 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Recurse to children that haven't been visited.
|
|
|
|
|
for (Block *succ : block->getSuccessors())
|
|
|
|
|
if (visitedBlocks.insert(succ).second)
|
|
|
|
|
worklist.push_back(succ);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check that all blocks in the region were visited.
|
|
|
|
|
if (llvm::any_of(llvm::drop_begin(region, 1),
|
|
|
|
|
[&](Block &block) { return !visitedBlocks.count(&block); }))
|
|
|
|
|
return emitError(regionLoc, "unreachable blocks were not converted");
|
|
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
2019-09-16 10:37:48 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
// Multi-Level Value Mapper
|
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
|
/// This class wraps a BlockAndValueMapping to provide recursive lookup
|
|
|
|
|
/// functionality, i.e. we will traverse if the mapped value also has a mapping.
|
|
|
|
|
struct ConversionValueMapping {
|
|
|
|
|
/// Lookup a mapped value within the map. If a mapping for the provided value
|
|
|
|
|
/// does not exist then return the provided value.
|
|
|
|
|
Value *lookupOrDefault(Value *from) const;
|
|
|
|
|
|
|
|
|
|
/// Map a value to the one provided.
|
|
|
|
|
void map(Value *oldVal, Value *newVal) { mapping.map(oldVal, newVal); }
|
|
|
|
|
|
|
|
|
|
/// Drop the last mapping for the given value.
|
|
|
|
|
void erase(Value *value) { mapping.erase(value); }
|
|
|
|
|
|
|
|
|
|
private:
|
|
|
|
|
/// Current value mappings.
|
|
|
|
|
BlockAndValueMapping mapping;
|
|
|
|
|
};
|
|
|
|
|
} // end anonymous namespace
|
|
|
|
|
|
|
|
|
|
/// Lookup a mapped value within the map. If a mapping for the provided value
|
|
|
|
|
/// does not exist then return the provided value.
|
|
|
|
|
Value *ConversionValueMapping::lookupOrDefault(Value *from) const {
|
|
|
|
|
// If this value had a valid mapping, unmap that value as well in the case
|
|
|
|
|
// that it was also replaced.
|
|
|
|
|
while (auto *mappedValue = mapping.lookupOrNull(from))
|
|
|
|
|
from = mappedValue;
|
|
|
|
|
return from;
|
|
|
|
|
}
|
|
|
|
|
|
2019-05-19 20:54:13 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2019-05-22 11:49:04 -07:00
|
|
|
// ArgConverter
|
2019-05-19 20:54:13 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2019-05-17 22:21:13 -07:00
|
|
|
namespace {
|
2019-05-22 11:49:04 -07:00
|
|
|
/// This class provides a simple interface for converting the types of block
|
2019-11-13 10:27:21 -08:00
|
|
|
/// arguments. This is done by creating a new block that contains the new legal
|
|
|
|
|
/// types and extracting the block that contains the old illegal types to allow
|
|
|
|
|
/// for undoing pending rewrites in the case of failure.
|
2019-05-22 11:49:04 -07:00
|
|
|
struct ArgConverter {
|
2019-06-28 11:28:30 -07:00
|
|
|
ArgConverter(TypeConverter *typeConverter, PatternRewriter &rewriter)
|
2019-11-13 10:27:21 -08:00
|
|
|
: loc(rewriter.getUnknownLoc()), typeConverter(typeConverter),
|
2019-06-28 11:28:30 -07:00
|
|
|
rewriter(rewriter) {}
|
2019-05-22 11:49:04 -07:00
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
/// This structure contains the information pertaining to an argument that has
|
|
|
|
|
/// been converted.
|
|
|
|
|
struct ConvertedArgInfo {
|
|
|
|
|
ConvertedArgInfo(unsigned newArgIdx, unsigned newArgSize,
|
|
|
|
|
Value *castValue = nullptr)
|
|
|
|
|
: newArgIdx(newArgIdx), newArgSize(newArgSize), castValue(castValue) {}
|
2019-06-19 13:58:31 -07:00
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
/// The start index of in the new argument list that contains arguments that
|
|
|
|
|
/// replace the original.
|
|
|
|
|
unsigned newArgIdx;
|
2019-05-22 11:49:04 -07:00
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
/// The number of arguments that replaced the original argument.
|
|
|
|
|
unsigned newArgSize;
|
|
|
|
|
|
|
|
|
|
/// The cast value that was created to cast from the new arguments to the
|
|
|
|
|
/// old. This only used if 'newArgSize' > 1.
|
|
|
|
|
Value *castValue;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
/// This structure contains information pertaining to a block that has had its
|
|
|
|
|
/// signature converted.
|
|
|
|
|
struct ConvertedBlockInfo {
|
|
|
|
|
ConvertedBlockInfo(Block *origBlock) : origBlock(origBlock) {}
|
|
|
|
|
|
|
|
|
|
/// The original block that was requested to have its signature converted.
|
|
|
|
|
Block *origBlock;
|
|
|
|
|
|
|
|
|
|
/// The conversion information for each of the arguments. The information is
|
|
|
|
|
/// None if the argument was dropped during conversion.
|
|
|
|
|
SmallVector<Optional<ConvertedArgInfo>, 1> argInfo;
|
|
|
|
|
};
|
2019-06-19 13:58:31 -07:00
|
|
|
|
2019-07-17 14:45:53 -07:00
|
|
|
/// Return if the signature of the given block has already been converted.
|
2019-11-13 10:27:21 -08:00
|
|
|
bool hasBeenConverted(Block *block) const {
|
|
|
|
|
return conversionInfo.count(block);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//===--------------------------------------------------------------------===//
|
|
|
|
|
// Rewrite Application
|
|
|
|
|
//===--------------------------------------------------------------------===//
|
2019-06-19 13:58:31 -07:00
|
|
|
|
2019-12-16 12:09:14 -08:00
|
|
|
/// Erase any rewrites registered for the blocks within the given operation
|
|
|
|
|
/// which is about to be removed. This merely drops the rewrites without
|
|
|
|
|
/// undoing them.
|
|
|
|
|
void notifyOpRemoved(Operation *op);
|
2019-07-17 14:45:53 -07:00
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
/// Cleanup and undo any generated conversions for the arguments of block.
|
|
|
|
|
/// This method replaces the new block with the original, reverting the IR to
|
|
|
|
|
/// its original state.
|
|
|
|
|
void discardRewrites(Block *block);
|
|
|
|
|
|
|
|
|
|
/// Fully replace uses of the old arguments with the new, materializing cast
|
|
|
|
|
/// operations as necessary.
|
|
|
|
|
// FIXME(riverriddle) The 'mapping' parameter is only necessary because the
|
|
|
|
|
// implementation of replaceUsesOfBlockArgument is buggy.
|
|
|
|
|
void applyRewrites(ConversionValueMapping &mapping);
|
|
|
|
|
|
|
|
|
|
//===--------------------------------------------------------------------===//
|
|
|
|
|
// Conversion
|
|
|
|
|
//===--------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
|
|
/// Attempt to convert the signature of the given block, if successful a new
|
|
|
|
|
/// block is returned containing the new arguments. On failure, nullptr is
|
|
|
|
|
/// returned.
|
|
|
|
|
Block *convertSignature(Block *block, ConversionValueMapping &mapping);
|
|
|
|
|
|
|
|
|
|
/// Apply the given signature conversion on the given block. The new block
|
|
|
|
|
/// containing the updated signature is returned.
|
|
|
|
|
Block *applySignatureConversion(
|
2019-07-17 14:45:53 -07:00
|
|
|
Block *block, TypeConverter::SignatureConversion &signatureConversion,
|
2019-09-16 10:37:48 -07:00
|
|
|
ConversionValueMapping &mapping);
|
2019-05-19 17:56:32 -07:00
|
|
|
|
2019-12-16 12:09:14 -08:00
|
|
|
/// Insert a new conversion into the cache.
|
|
|
|
|
void insertConversion(Block *newBlock, ConvertedBlockInfo &&info);
|
|
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
/// A collection of blocks that have had their arguments converted.
|
|
|
|
|
llvm::MapVector<Block *, ConvertedBlockInfo> conversionInfo;
|
|
|
|
|
|
2019-12-16 12:09:14 -08:00
|
|
|
/// A mapping from valid regions, to those containing the original blocks of a
|
|
|
|
|
/// conversion.
|
|
|
|
|
DenseMap<Region *, std::unique_ptr<Region>> regionMapping;
|
|
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
/// An instance of the unknown location that is used when materializing
|
|
|
|
|
/// conversions.
|
2019-06-25 16:57:32 -07:00
|
|
|
Location loc;
|
2019-06-28 11:28:30 -07:00
|
|
|
|
|
|
|
|
/// The type converter to use when changing types.
|
|
|
|
|
TypeConverter *typeConverter;
|
|
|
|
|
|
|
|
|
|
/// The pattern rewriter to use when materializing conversions.
|
|
|
|
|
PatternRewriter &rewriter;
|
2019-05-19 17:56:32 -07:00
|
|
|
};
|
2019-07-18 12:04:57 -07:00
|
|
|
} // end anonymous namespace
|
2019-05-19 17:56:32 -07:00
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
// Rewrite Application
|
2019-05-19 23:09:29 -07:00
|
|
|
|
2019-12-16 12:09:14 -08:00
|
|
|
void ArgConverter::notifyOpRemoved(Operation *op) {
|
|
|
|
|
for (Region ®ion : op->getRegions()) {
|
|
|
|
|
for (Block &block : region) {
|
|
|
|
|
// Drop any rewrites from within.
|
|
|
|
|
for (Operation &nestedOp : block)
|
|
|
|
|
if (nestedOp.getNumRegions())
|
|
|
|
|
notifyOpRemoved(&nestedOp);
|
|
|
|
|
|
|
|
|
|
// Check if this block was converted.
|
|
|
|
|
auto it = conversionInfo.find(&block);
|
|
|
|
|
if (it == conversionInfo.end())
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
// Drop all uses of the original arguments and delete the original block.
|
|
|
|
|
Block *origBlock = it->second.origBlock;
|
|
|
|
|
for (BlockArgument *arg : origBlock->getArguments())
|
|
|
|
|
arg->dropAllUses();
|
|
|
|
|
conversionInfo.erase(it);
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-06-24 17:36:05 -07:00
|
|
|
}
|
|
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
void ArgConverter::discardRewrites(Block *block) {
|
|
|
|
|
auto it = conversionInfo.find(block);
|
|
|
|
|
if (it == conversionInfo.end())
|
2019-07-17 14:45:53 -07:00
|
|
|
return;
|
2019-11-13 10:27:21 -08:00
|
|
|
Block *origBlock = it->second.origBlock;
|
2019-06-24 17:36:05 -07:00
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
// Drop all uses of the new block arguments and replace uses of the new block.
|
|
|
|
|
for (int i = block->getNumArguments() - 1; i >= 0; --i)
|
2019-07-17 14:45:53 -07:00
|
|
|
block->getArgument(i)->dropAllUses();
|
2019-11-13 10:27:21 -08:00
|
|
|
block->replaceAllUsesWith(origBlock);
|
2019-06-24 17:36:05 -07:00
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
// Move the operations back the original block and the delete the new block.
|
|
|
|
|
origBlock->getOperations().splice(origBlock->end(), block->getOperations());
|
2019-12-16 12:09:14 -08:00
|
|
|
origBlock->moveBefore(block);
|
2019-11-13 10:27:21 -08:00
|
|
|
block->erase();
|
2019-06-24 17:36:05 -07:00
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
conversionInfo.erase(it);
|
2019-06-24 17:36:05 -07:00
|
|
|
}
|
|
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
void ArgConverter::applyRewrites(ConversionValueMapping &mapping) {
|
|
|
|
|
for (auto &info : conversionInfo) {
|
|
|
|
|
Block *newBlock = info.first;
|
|
|
|
|
ConvertedBlockInfo &blockInfo = info.second;
|
|
|
|
|
Block *origBlock = blockInfo.origBlock;
|
2019-06-24 17:36:05 -07:00
|
|
|
|
|
|
|
|
// Process the remapping for each of the original arguments.
|
2019-11-13 10:27:21 -08:00
|
|
|
for (unsigned i = 0, e = origBlock->getNumArguments(); i != e; ++i) {
|
|
|
|
|
Optional<ConvertedArgInfo> &argInfo = blockInfo.argInfo[i];
|
|
|
|
|
BlockArgument *origArg = origBlock->getArgument(i);
|
|
|
|
|
|
|
|
|
|
// Handle the case of a 1->0 value mapping.
|
|
|
|
|
if (!argInfo) {
|
2019-11-25 10:38:31 -08:00
|
|
|
// If a replacement value was given for this argument, use that to
|
|
|
|
|
// replace all uses.
|
|
|
|
|
auto argReplacementValue = mapping.lookupOrDefault(origArg);
|
|
|
|
|
if (argReplacementValue != origArg) {
|
|
|
|
|
origArg->replaceAllUsesWith(argReplacementValue);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2019-11-13 10:27:21 -08:00
|
|
|
// If there are any dangling uses then replace the argument with one
|
|
|
|
|
// generated by the type converter. This is necessary as the cast must
|
|
|
|
|
// persist in the IR after conversion.
|
|
|
|
|
if (!origArg->use_empty()) {
|
|
|
|
|
rewriter.setInsertionPointToStart(newBlock);
|
|
|
|
|
auto *newOp = typeConverter->materializeConversion(
|
|
|
|
|
rewriter, origArg->getType(), llvm::None, loc);
|
|
|
|
|
origArg->replaceAllUsesWith(newOp->getResult(0));
|
|
|
|
|
}
|
2019-06-24 17:36:05 -07:00
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
2019-07-15 08:40:11 -07:00
|
|
|
// If mapping is 1-1, replace the remaining uses and drop the cast
|
|
|
|
|
// operation.
|
|
|
|
|
// FIXME(riverriddle) This should check that the result type and operand
|
|
|
|
|
// type are the same, otherwise it should force a conversion to be
|
2019-11-13 10:27:21 -08:00
|
|
|
// materialized.
|
|
|
|
|
if (argInfo->newArgSize == 1) {
|
|
|
|
|
origArg->replaceAllUsesWith(
|
|
|
|
|
mapping.lookupOrDefault(newBlock->getArgument(argInfo->newArgIdx)));
|
2019-07-01 09:52:53 -07:00
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
// Otherwise this is a 1->N value mapping.
|
|
|
|
|
Value *castValue = argInfo->castValue;
|
|
|
|
|
assert(argInfo->newArgSize > 1 && castValue && "expected 1->N mapping");
|
|
|
|
|
|
|
|
|
|
// If the argument is still used, replace it with the generated cast.
|
|
|
|
|
if (!origArg->use_empty())
|
|
|
|
|
origArg->replaceAllUsesWith(mapping.lookupOrDefault(castValue));
|
|
|
|
|
|
|
|
|
|
// If all users of the cast were removed, we can drop it. Otherwise, keep
|
|
|
|
|
// the operation alive and let the user handle any remaining usages.
|
|
|
|
|
if (castValue->use_empty())
|
|
|
|
|
castValue->getDefiningOp()->erase();
|
2019-06-24 17:36:05 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
// Conversion
|
|
|
|
|
|
|
|
|
|
Block *ArgConverter::convertSignature(Block *block,
|
|
|
|
|
ConversionValueMapping &mapping) {
|
2019-07-20 19:05:41 -07:00
|
|
|
if (auto conversion = typeConverter->convertBlockSignature(block))
|
2019-11-13 10:27:21 -08:00
|
|
|
return applySignatureConversion(block, *conversion, mapping);
|
|
|
|
|
return nullptr;
|
2019-07-17 14:45:53 -07:00
|
|
|
}
|
|
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
Block *ArgConverter::applySignatureConversion(
|
2019-06-28 11:28:30 -07:00
|
|
|
Block *block, TypeConverter::SignatureConversion &signatureConversion,
|
2019-09-16 10:37:48 -07:00
|
|
|
ConversionValueMapping &mapping) {
|
2019-11-13 10:27:21 -08:00
|
|
|
// If no arguments are being changed or added, there is nothing to do.
|
2019-06-24 17:36:05 -07:00
|
|
|
unsigned origArgCount = block->getNumArguments();
|
2019-07-20 19:05:41 -07:00
|
|
|
auto convertedTypes = signatureConversion.getConvertedTypes();
|
2019-06-24 17:36:05 -07:00
|
|
|
if (origArgCount == 0 && convertedTypes.empty())
|
2019-11-13 10:27:21 -08:00
|
|
|
return block;
|
|
|
|
|
|
|
|
|
|
// Split the block at the beginning to get a new block to use for the updated
|
|
|
|
|
// signature.
|
|
|
|
|
Block *newBlock = block->splitBlock(block->begin());
|
|
|
|
|
block->replaceAllUsesWith(newBlock);
|
2019-06-24 17:36:05 -07:00
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
SmallVector<Value *, 4> newArgRange(newBlock->addArguments(convertedTypes));
|
|
|
|
|
ArrayRef<Value *> newArgs(newArgRange);
|
2019-06-24 17:36:05 -07:00
|
|
|
|
|
|
|
|
// Remap each of the original arguments as determined by the signature
|
|
|
|
|
// conversion.
|
2019-11-13 10:27:21 -08:00
|
|
|
ConvertedBlockInfo info(block);
|
|
|
|
|
info.argInfo.resize(origArgCount);
|
|
|
|
|
|
2019-10-09 11:32:54 -07:00
|
|
|
OpBuilder::InsertionGuard guard(rewriter);
|
2019-11-13 10:27:21 -08:00
|
|
|
rewriter.setInsertionPointToStart(newBlock);
|
2019-06-24 17:36:05 -07:00
|
|
|
for (unsigned i = 0; i != origArgCount; ++i) {
|
2019-11-13 10:27:21 -08:00
|
|
|
auto inputMap = signatureConversion.getInputMapping(i);
|
|
|
|
|
if (!inputMap)
|
|
|
|
|
continue;
|
|
|
|
|
BlockArgument *origArg = block->getArgument(i);
|
|
|
|
|
|
|
|
|
|
// If inputMap->replacementValue is not nullptr, then the argument is
|
|
|
|
|
// dropped and a replacement value is provided to be the remappedValue.
|
|
|
|
|
if (inputMap->replacementValue) {
|
|
|
|
|
assert(inputMap->size == 0 &&
|
|
|
|
|
"invalid to provide a replacement value when the argument isn't "
|
|
|
|
|
"dropped");
|
|
|
|
|
mapping.map(origArg, inputMap->replacementValue);
|
|
|
|
|
continue;
|
2019-10-16 10:20:31 -07:00
|
|
|
}
|
2019-06-24 17:36:05 -07:00
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
// If this is a 1->1 mapping, then map the argument directly.
|
|
|
|
|
if (inputMap->size == 1) {
|
|
|
|
|
mapping.map(origArg, newArgs[inputMap->inputNo]);
|
|
|
|
|
info.argInfo[i] = ConvertedArgInfo(inputMap->inputNo, inputMap->size);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2019-06-24 17:36:05 -07:00
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
// Otherwise, this is a 1->N mapping. Call into the provided type converter
|
|
|
|
|
// to pack the new values.
|
|
|
|
|
auto replArgs = newArgs.slice(inputMap->inputNo, inputMap->size);
|
|
|
|
|
Operation *cast = typeConverter->materializeConversion(
|
|
|
|
|
rewriter, origArg->getType(), replArgs, loc);
|
|
|
|
|
assert(cast->getNumResults() == 1 &&
|
|
|
|
|
cast->getNumOperands() == replArgs.size());
|
|
|
|
|
mapping.map(origArg, cast->getResult(0));
|
|
|
|
|
info.argInfo[i] =
|
|
|
|
|
ConvertedArgInfo(inputMap->inputNo, inputMap->size, cast->getResult(0));
|
2019-06-24 17:36:05 -07:00
|
|
|
}
|
|
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
// Remove the original block from the region and return the new one.
|
2019-12-16 12:09:14 -08:00
|
|
|
insertConversion(newBlock, std::move(info));
|
2019-11-13 10:27:21 -08:00
|
|
|
return newBlock;
|
2019-06-24 17:36:05 -07:00
|
|
|
}
|
|
|
|
|
|
2019-12-16 12:09:14 -08:00
|
|
|
void ArgConverter::insertConversion(Block *newBlock,
|
|
|
|
|
ConvertedBlockInfo &&info) {
|
|
|
|
|
// Get a region to insert the old block.
|
|
|
|
|
Region *region = newBlock->getParent();
|
|
|
|
|
std::unique_ptr<Region> &mappedRegion = regionMapping[region];
|
|
|
|
|
if (!mappedRegion)
|
|
|
|
|
mappedRegion = std::make_unique<Region>(region->getParentOp());
|
|
|
|
|
|
|
|
|
|
// Move the original block to the mapped region and emplace the conversion.
|
|
|
|
|
mappedRegion->getBlocks().splice(mappedRegion->end(), region->getBlocks(),
|
|
|
|
|
info.origBlock->getIterator());
|
|
|
|
|
conversionInfo.insert({newBlock, std::move(info)});
|
|
|
|
|
}
|
|
|
|
|
|
2019-05-19 20:54:13 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2019-07-18 12:04:57 -07:00
|
|
|
// ConversionPatternRewriterImpl
|
2019-05-19 20:54:13 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2019-07-18 12:04:57 -07:00
|
|
|
namespace {
|
2019-06-05 09:36:32 -07:00
|
|
|
/// This class contains a snapshot of the current conversion rewriter state.
|
|
|
|
|
/// This is useful when saving and undoing a set of rewrites.
|
|
|
|
|
struct RewriterState {
|
2019-06-11 08:33:18 -07:00
|
|
|
RewriterState(unsigned numCreatedOperations, unsigned numReplacements,
|
2019-10-28 10:03:57 -07:00
|
|
|
unsigned numBlockActions, unsigned numIgnoredOperations)
|
2019-06-05 09:36:32 -07:00
|
|
|
: numCreatedOperations(numCreatedOperations),
|
2019-10-10 12:01:45 -07:00
|
|
|
numReplacements(numReplacements), numBlockActions(numBlockActions),
|
2019-10-28 10:03:57 -07:00
|
|
|
numIgnoredOperations(numIgnoredOperations) {}
|
2019-06-05 09:36:32 -07:00
|
|
|
|
|
|
|
|
/// The current number of created operations.
|
|
|
|
|
unsigned numCreatedOperations;
|
|
|
|
|
|
|
|
|
|
/// The current number of replacements queued.
|
|
|
|
|
unsigned numReplacements;
|
2019-06-11 08:33:18 -07:00
|
|
|
|
|
|
|
|
/// The current number of block actions performed.
|
|
|
|
|
unsigned numBlockActions;
|
2019-10-10 12:01:45 -07:00
|
|
|
|
2019-10-28 10:03:57 -07:00
|
|
|
/// The current number of ignored operations.
|
|
|
|
|
unsigned numIgnoredOperations;
|
2019-06-05 09:36:32 -07:00
|
|
|
};
|
2019-07-18 12:04:57 -07:00
|
|
|
} // end anonymous namespace
|
2019-06-05 09:36:32 -07:00
|
|
|
|
2019-07-18 12:04:57 -07:00
|
|
|
namespace mlir {
|
|
|
|
|
namespace detail {
|
|
|
|
|
struct ConversionPatternRewriterImpl {
|
2019-05-22 11:49:04 -07:00
|
|
|
/// This class represents one requested operation replacement via 'replaceOp'.
|
|
|
|
|
struct OpReplacement {
|
|
|
|
|
OpReplacement() = default;
|
2019-12-06 20:06:48 -08:00
|
|
|
OpReplacement(Operation *op, ValueRange newValues)
|
2019-05-22 11:49:04 -07:00
|
|
|
: op(op), newValues(newValues.begin(), newValues.end()) {}
|
|
|
|
|
|
|
|
|
|
Operation *op;
|
|
|
|
|
SmallVector<Value *, 2> newValues;
|
|
|
|
|
};
|
|
|
|
|
|
2019-06-11 08:33:18 -07:00
|
|
|
/// The kind of the block action performed during the rewrite. Actions can be
|
|
|
|
|
/// undone if the conversion fails.
|
2019-10-08 15:44:34 -07:00
|
|
|
enum class BlockActionKind { Create, Move, Split, TypeConversion };
|
2019-06-11 08:33:18 -07:00
|
|
|
|
|
|
|
|
/// Original position of the given block in its parent region. We cannot use
|
|
|
|
|
/// a region iterator because it could have been invalidated by other region
|
|
|
|
|
/// operations since the position was stored.
|
|
|
|
|
struct BlockPosition {
|
|
|
|
|
Region *region;
|
|
|
|
|
Region::iterator::difference_type position;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
/// The storage class for an undoable block action (one of BlockActionKind),
|
|
|
|
|
/// contains the information necessary to undo this action.
|
|
|
|
|
struct BlockAction {
|
2019-10-08 15:44:34 -07:00
|
|
|
static BlockAction getCreate(Block *block) {
|
|
|
|
|
return {BlockActionKind::Create, block, {}};
|
|
|
|
|
}
|
|
|
|
|
static BlockAction getMove(Block *block, BlockPosition originalPos) {
|
|
|
|
|
return {BlockActionKind::Move, block, {originalPos}};
|
|
|
|
|
}
|
2019-07-20 19:05:41 -07:00
|
|
|
static BlockAction getSplit(Block *block, Block *originalBlock) {
|
2019-07-27 11:46:22 -07:00
|
|
|
BlockAction action{BlockActionKind::Split, block, {}};
|
2019-07-20 19:05:41 -07:00
|
|
|
action.originalBlock = originalBlock;
|
|
|
|
|
return action;
|
|
|
|
|
}
|
|
|
|
|
static BlockAction getTypeConversion(Block *block) {
|
2019-07-27 11:46:22 -07:00
|
|
|
return BlockAction{BlockActionKind::TypeConversion, block, {}};
|
2019-07-20 19:05:41 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// The action kind.
|
|
|
|
|
BlockActionKind kind;
|
|
|
|
|
|
2019-06-11 08:33:18 -07:00
|
|
|
// A pointer to the block that was created by the action.
|
|
|
|
|
Block *block;
|
|
|
|
|
|
|
|
|
|
union {
|
|
|
|
|
// In use if kind == BlockActionKind::Move and contains a pointer to the
|
|
|
|
|
// region that originally contained the block as well as the position of
|
|
|
|
|
// the block in that region.
|
|
|
|
|
BlockPosition originalPosition;
|
|
|
|
|
// In use if kind == BlockActionKind::Split and contains a pointer to the
|
|
|
|
|
// block that was split into two parts.
|
|
|
|
|
Block *originalBlock;
|
|
|
|
|
};
|
2019-07-17 14:45:53 -07:00
|
|
|
};
|
|
|
|
|
|
2019-07-18 12:04:57 -07:00
|
|
|
ConversionPatternRewriterImpl(PatternRewriter &rewriter,
|
|
|
|
|
TypeConverter *converter)
|
|
|
|
|
: argConverter(converter, rewriter) {}
|
2019-05-17 22:21:13 -07:00
|
|
|
|
2019-06-05 09:36:32 -07:00
|
|
|
/// Return the current state of the rewriter.
|
2019-07-18 12:04:57 -07:00
|
|
|
RewriterState getCurrentState();
|
2019-06-05 09:36:32 -07:00
|
|
|
|
|
|
|
|
/// Reset the state of the rewriter to a previously saved point.
|
2019-07-18 12:04:57 -07:00
|
|
|
void resetState(RewriterState state);
|
2019-06-11 08:33:18 -07:00
|
|
|
|
|
|
|
|
/// Undo the block actions (motions, splits) one by one in reverse order until
|
|
|
|
|
/// "numActionsToKeep" actions remains.
|
2019-07-18 12:04:57 -07:00
|
|
|
void undoBlockActions(unsigned numActionsToKeep = 0);
|
2019-07-17 14:45:53 -07:00
|
|
|
|
2019-05-22 11:49:04 -07:00
|
|
|
/// Cleanup and destroy any generated rewrite operations. This method is
|
|
|
|
|
/// invoked when the conversion process fails.
|
2019-07-18 12:04:57 -07:00
|
|
|
void discardRewrites();
|
2019-05-22 11:49:04 -07:00
|
|
|
|
|
|
|
|
/// Apply all requested operation rewrites. This method is invoked when the
|
|
|
|
|
/// conversion process succeeds.
|
2019-07-18 12:04:57 -07:00
|
|
|
void applyRewrites();
|
2019-05-22 11:49:04 -07:00
|
|
|
|
2019-07-17 14:45:53 -07:00
|
|
|
/// Convert the signature of the given block.
|
2019-07-18 12:04:57 -07:00
|
|
|
LogicalResult convertBlockSignature(Block *block);
|
2019-07-17 14:45:53 -07:00
|
|
|
|
2019-07-20 19:05:41 -07:00
|
|
|
/// Apply a signature conversion on the given region.
|
2019-11-13 10:27:21 -08:00
|
|
|
Block *
|
|
|
|
|
applySignatureConversion(Region *region,
|
|
|
|
|
TypeConverter::SignatureConversion &conversion);
|
2019-07-20 19:05:41 -07:00
|
|
|
|
2019-05-22 11:49:04 -07:00
|
|
|
/// PatternRewriter hook for replacing the results of an operation.
|
2019-12-06 20:06:48 -08:00
|
|
|
void replaceOp(Operation *op, ValueRange newValues,
|
|
|
|
|
ValueRange valuesToRemoveIfDead);
|
2019-05-22 11:49:04 -07:00
|
|
|
|
2019-07-18 12:04:57 -07:00
|
|
|
/// Notifies that a block was split.
|
|
|
|
|
void notifySplitBlock(Block *block, Block *continuation);
|
2019-05-17 22:21:13 -07:00
|
|
|
|
2019-07-18 12:04:57 -07:00
|
|
|
/// Notifies that the blocks of a region are about to be moved.
|
|
|
|
|
void notifyRegionIsBeingInlinedBefore(Region ®ion, Region &parent,
|
|
|
|
|
Region::iterator before);
|
2019-05-17 22:21:13 -07:00
|
|
|
|
2019-10-08 15:44:34 -07:00
|
|
|
/// Notifies that the blocks of a region were cloned into another.
|
2019-12-18 09:28:48 -08:00
|
|
|
void notifyRegionWasClonedBefore(iterator_range<Region::iterator> &blocks,
|
|
|
|
|
Location origRegionLoc);
|
2019-10-08 15:44:34 -07:00
|
|
|
|
2019-05-22 11:49:04 -07:00
|
|
|
/// Remap the given operands to those with potentially different types.
|
|
|
|
|
void remapValues(Operation::operand_range operands,
|
2019-07-18 12:04:57 -07:00
|
|
|
SmallVectorImpl<Value *> &remapped);
|
2019-05-17 22:21:13 -07:00
|
|
|
|
2019-10-28 10:03:57 -07:00
|
|
|
/// Returns true if the given operation is ignored, and does not need to be
|
2019-10-10 12:01:45 -07:00
|
|
|
/// converted.
|
2019-10-28 10:03:57 -07:00
|
|
|
bool isOpIgnored(Operation *op) const;
|
|
|
|
|
|
|
|
|
|
/// Recursively marks the nested operations under 'op' as ignored. This
|
|
|
|
|
/// removes them from being considered for legalization.
|
|
|
|
|
void markNestedOpsIgnored(Operation *op);
|
2019-10-10 12:01:45 -07:00
|
|
|
|
2019-05-22 11:49:04 -07:00
|
|
|
// Mapping between replaced values that differ in type. This happens when
|
|
|
|
|
// replacing a value with one of a different type.
|
2019-09-16 10:37:48 -07:00
|
|
|
ConversionValueMapping mapping;
|
2019-05-19 17:56:32 -07:00
|
|
|
|
2019-05-22 11:49:04 -07:00
|
|
|
/// Utility used to convert block arguments.
|
|
|
|
|
ArgConverter argConverter;
|
|
|
|
|
|
|
|
|
|
/// Ordered vector of all of the newly created operations during conversion.
|
2019-10-08 15:44:34 -07:00
|
|
|
std::vector<Operation *> createdOps;
|
2019-05-22 11:49:04 -07:00
|
|
|
|
|
|
|
|
/// Ordered vector of any requested operation replacements.
|
|
|
|
|
SmallVector<OpReplacement, 4> replacements;
|
2019-06-11 08:33:18 -07:00
|
|
|
|
|
|
|
|
/// Ordered list of block operations (creations, splits, motions).
|
|
|
|
|
SmallVector<BlockAction, 4> blockActions;
|
2019-10-10 12:01:45 -07:00
|
|
|
|
2019-10-28 10:03:57 -07:00
|
|
|
/// A set of operations that have been erased/replaced/etc that should no
|
|
|
|
|
/// longer be considered for legalization. This is not meant to be an
|
|
|
|
|
/// exhaustive list of all operations, but the minimal set that can be used to
|
|
|
|
|
/// detect if a given operation should be `ignored`. For example, we may add
|
|
|
|
|
/// the operations that define non-empty regions to the set, but not any of
|
|
|
|
|
/// the others. This simplifies the amount of memory needed as we can query if
|
|
|
|
|
/// the parent operation was ignored.
|
|
|
|
|
llvm::SetVector<Operation *> ignoredOps;
|
2019-05-17 22:21:13 -07:00
|
|
|
};
|
2019-07-18 12:04:57 -07:00
|
|
|
} // end namespace detail
|
|
|
|
|
} // end namespace mlir
|
|
|
|
|
|
|
|
|
|
RewriterState ConversionPatternRewriterImpl::getCurrentState() {
|
|
|
|
|
return RewriterState(createdOps.size(), replacements.size(),
|
2019-10-28 10:03:57 -07:00
|
|
|
blockActions.size(), ignoredOps.size());
|
2019-07-18 12:04:57 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ConversionPatternRewriterImpl::resetState(RewriterState state) {
|
2019-07-20 19:05:41 -07:00
|
|
|
// Undo any block actions.
|
2019-07-18 12:04:57 -07:00
|
|
|
undoBlockActions(state.numBlockActions);
|
|
|
|
|
|
|
|
|
|
// Reset any replaced operations and undo any saved mappings.
|
|
|
|
|
for (auto &repl : llvm::drop_begin(replacements, state.numReplacements))
|
|
|
|
|
for (auto *result : repl.op->getResults())
|
|
|
|
|
mapping.erase(result);
|
|
|
|
|
replacements.resize(state.numReplacements);
|
|
|
|
|
|
|
|
|
|
// Pop all of the newly created operations.
|
2019-10-08 15:44:34 -07:00
|
|
|
while (createdOps.size() != state.numCreatedOperations) {
|
|
|
|
|
createdOps.back()->erase();
|
|
|
|
|
createdOps.pop_back();
|
|
|
|
|
}
|
2019-10-10 12:01:45 -07:00
|
|
|
|
2019-10-28 10:03:57 -07:00
|
|
|
// Pop all of the recorded ignored operations that are no longer valid.
|
|
|
|
|
while (ignoredOps.size() != state.numIgnoredOperations)
|
|
|
|
|
ignoredOps.pop_back();
|
2019-07-18 12:04:57 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ConversionPatternRewriterImpl::undoBlockActions(
|
|
|
|
|
unsigned numActionsToKeep) {
|
|
|
|
|
for (auto &action :
|
|
|
|
|
llvm::reverse(llvm::drop_begin(blockActions, numActionsToKeep))) {
|
|
|
|
|
switch (action.kind) {
|
2019-10-08 15:44:34 -07:00
|
|
|
// Delete the created block.
|
|
|
|
|
case BlockActionKind::Create: {
|
|
|
|
|
// Unlink all of the operations within this block, they will be deleted
|
|
|
|
|
// separately.
|
|
|
|
|
auto &blockOps = action.block->getOperations();
|
|
|
|
|
while (!blockOps.empty())
|
|
|
|
|
blockOps.remove(blockOps.begin());
|
|
|
|
|
action.block->dropAllDefinedValueUses();
|
2019-07-18 12:04:57 -07:00
|
|
|
action.block->erase();
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
// Move the block back to its original position.
|
|
|
|
|
case BlockActionKind::Move: {
|
|
|
|
|
Region *originalRegion = action.originalPosition.region;
|
|
|
|
|
originalRegion->getBlocks().splice(
|
|
|
|
|
std::next(originalRegion->begin(), action.originalPosition.position),
|
|
|
|
|
action.block->getParent()->getBlocks(), action.block);
|
|
|
|
|
break;
|
|
|
|
|
}
|
2019-10-08 15:44:34 -07:00
|
|
|
// Merge back the block that was split out.
|
|
|
|
|
case BlockActionKind::Split: {
|
|
|
|
|
action.originalBlock->getOperations().splice(
|
|
|
|
|
action.originalBlock->end(), action.block->getOperations());
|
2019-10-14 09:50:54 -07:00
|
|
|
action.block->dropAllDefinedValueUses();
|
2019-10-08 15:44:34 -07:00
|
|
|
action.block->erase();
|
|
|
|
|
break;
|
|
|
|
|
}
|
2019-07-20 19:05:41 -07:00
|
|
|
// Undo the type conversion.
|
|
|
|
|
case BlockActionKind::TypeConversion: {
|
2019-11-13 10:27:21 -08:00
|
|
|
argConverter.discardRewrites(action.block);
|
2019-07-20 19:05:41 -07:00
|
|
|
break;
|
|
|
|
|
}
|
2019-07-18 12:04:57 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
blockActions.resize(numActionsToKeep);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ConversionPatternRewriterImpl::discardRewrites() {
|
|
|
|
|
undoBlockActions();
|
|
|
|
|
|
|
|
|
|
// Remove any newly created ops.
|
2019-09-16 10:37:48 -07:00
|
|
|
for (auto *op : llvm::reverse(createdOps))
|
2019-07-18 12:04:57 -07:00
|
|
|
op->erase();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ConversionPatternRewriterImpl::applyRewrites() {
|
|
|
|
|
// Apply all of the rewrites replacements requested during conversion.
|
|
|
|
|
for (auto &repl : replacements) {
|
2019-10-16 09:50:28 -07:00
|
|
|
for (unsigned i = 0, e = repl.newValues.size(); i != e; ++i) {
|
|
|
|
|
if (auto *newValue = repl.newValues[i])
|
|
|
|
|
repl.op->getResult(i)->replaceAllUsesWith(
|
|
|
|
|
mapping.lookupOrDefault(newValue));
|
|
|
|
|
}
|
2019-07-18 12:04:57 -07:00
|
|
|
|
|
|
|
|
// If this operation defines any regions, drop any pending argument
|
|
|
|
|
// rewrites.
|
2019-12-16 12:09:14 -08:00
|
|
|
if (argConverter.typeConverter && repl.op->getNumRegions())
|
|
|
|
|
argConverter.notifyOpRemoved(repl.op);
|
2019-07-18 12:04:57 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// In a second pass, erase all of the replaced operations in reverse. This
|
|
|
|
|
// allows processing nested operations before their parent region is
|
|
|
|
|
// destroyed.
|
|
|
|
|
for (auto &repl : llvm::reverse(replacements))
|
|
|
|
|
repl.op->erase();
|
|
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
argConverter.applyRewrites(mapping);
|
2019-07-18 12:04:57 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
LogicalResult
|
2019-07-20 19:05:41 -07:00
|
|
|
ConversionPatternRewriterImpl::convertBlockSignature(Block *block) {
|
|
|
|
|
// Check to see if this block should not be converted:
|
2019-08-16 10:16:09 -07:00
|
|
|
// * There is no type converter.
|
2019-07-20 19:05:41 -07:00
|
|
|
// * The block has already been converted.
|
|
|
|
|
// * This is an entry block, these are converted explicitly via patterns.
|
2019-08-16 10:16:09 -07:00
|
|
|
if (!argConverter.typeConverter || argConverter.hasBeenConverted(block) ||
|
2019-11-13 10:27:21 -08:00
|
|
|
!block->getParent() || block->isEntryBlock())
|
2019-07-20 19:05:41 -07:00
|
|
|
return success();
|
|
|
|
|
|
|
|
|
|
// Otherwise, try to convert the block signature.
|
2019-11-13 10:27:21 -08:00
|
|
|
Block *newBlock = argConverter.convertSignature(block, mapping);
|
|
|
|
|
if (newBlock)
|
|
|
|
|
blockActions.push_back(BlockAction::getTypeConversion(newBlock));
|
|
|
|
|
return success(newBlock);
|
2019-07-18 12:04:57 -07:00
|
|
|
}
|
|
|
|
|
|
2019-11-13 10:27:21 -08:00
|
|
|
Block *ConversionPatternRewriterImpl::applySignatureConversion(
|
2019-07-20 19:05:41 -07:00
|
|
|
Region *region, TypeConverter::SignatureConversion &conversion) {
|
|
|
|
|
if (!region->empty()) {
|
2019-11-13 10:27:21 -08:00
|
|
|
Block *newEntry = argConverter.applySignatureConversion(
|
|
|
|
|
®ion->front(), conversion, mapping);
|
|
|
|
|
blockActions.push_back(BlockAction::getTypeConversion(newEntry));
|
|
|
|
|
return newEntry;
|
2019-07-20 19:05:41 -07:00
|
|
|
}
|
2019-11-13 10:27:21 -08:00
|
|
|
return nullptr;
|
2019-07-18 12:04:57 -07:00
|
|
|
}
|
|
|
|
|
|
2019-12-06 20:06:48 -08:00
|
|
|
void ConversionPatternRewriterImpl::replaceOp(Operation *op,
|
|
|
|
|
ValueRange newValues,
|
|
|
|
|
ValueRange valuesToRemoveIfDead) {
|
2019-07-18 12:04:57 -07:00
|
|
|
assert(newValues.size() == op->getNumResults());
|
|
|
|
|
|
|
|
|
|
// Create mappings for each of the new result values.
|
2019-10-16 09:50:28 -07:00
|
|
|
for (unsigned i = 0, e = newValues.size(); i < e; ++i)
|
|
|
|
|
if (auto *repl = newValues[i])
|
|
|
|
|
mapping.map(op->getResult(i), repl);
|
2019-07-18 12:04:57 -07:00
|
|
|
|
|
|
|
|
// Record the requested operation replacement.
|
|
|
|
|
replacements.emplace_back(op, newValues);
|
2019-10-10 12:01:45 -07:00
|
|
|
|
2019-10-28 10:03:57 -07:00
|
|
|
/// Mark this operation as recursively ignored so that we don't need to
|
|
|
|
|
/// convert any nested operations.
|
|
|
|
|
markNestedOpsIgnored(op);
|
2019-07-18 12:04:57 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ConversionPatternRewriterImpl::notifySplitBlock(Block *block,
|
|
|
|
|
Block *continuation) {
|
2019-07-20 19:05:41 -07:00
|
|
|
blockActions.push_back(BlockAction::getSplit(continuation, block));
|
2019-07-18 12:04:57 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ConversionPatternRewriterImpl::notifyRegionIsBeingInlinedBefore(
|
|
|
|
|
Region ®ion, Region &parent, Region::iterator before) {
|
|
|
|
|
for (auto &pair : llvm::enumerate(region)) {
|
|
|
|
|
Block &block = pair.value();
|
|
|
|
|
unsigned position = pair.index();
|
2019-07-20 19:05:41 -07:00
|
|
|
blockActions.push_back(BlockAction::getMove(&block, {®ion, position}));
|
2019-07-18 12:04:57 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-08 15:44:34 -07:00
|
|
|
void ConversionPatternRewriterImpl::notifyRegionWasClonedBefore(
|
2019-12-18 09:28:48 -08:00
|
|
|
iterator_range<Region::iterator> &blocks, Location origRegionLoc) {
|
2019-10-08 15:44:34 -07:00
|
|
|
for (Block &block : blocks)
|
|
|
|
|
blockActions.push_back(BlockAction::getCreate(&block));
|
|
|
|
|
|
|
|
|
|
// Compute the conversion set for the inlined region.
|
|
|
|
|
auto result = computeConversionSet(blocks, origRegionLoc, createdOps);
|
|
|
|
|
|
|
|
|
|
// This original region has already had its conversion set computed, so there
|
|
|
|
|
// shouldn't be any new failures.
|
|
|
|
|
(void)result;
|
|
|
|
|
assert(succeeded(result) && "expected region to have no unreachable blocks");
|
|
|
|
|
}
|
|
|
|
|
|
2019-07-18 12:04:57 -07:00
|
|
|
void ConversionPatternRewriterImpl::remapValues(
|
|
|
|
|
Operation::operand_range operands, SmallVectorImpl<Value *> &remapped) {
|
|
|
|
|
remapped.reserve(llvm::size(operands));
|
|
|
|
|
for (Value *operand : operands)
|
|
|
|
|
remapped.push_back(mapping.lookupOrDefault(operand));
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-28 10:03:57 -07:00
|
|
|
bool ConversionPatternRewriterImpl::isOpIgnored(Operation *op) const {
|
|
|
|
|
// Check to see if this operation or its parent were ignored.
|
|
|
|
|
return ignoredOps.count(op) || ignoredOps.count(op->getParentOp());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ConversionPatternRewriterImpl::markNestedOpsIgnored(Operation *op) {
|
|
|
|
|
// Walk this operation and collect nested operations that define non-empty
|
|
|
|
|
// regions. We mark such operations as 'ignored' so that we know we don't have
|
|
|
|
|
// to convert them, or their nested ops.
|
|
|
|
|
if (op->getNumRegions() == 0)
|
|
|
|
|
return;
|
|
|
|
|
op->walk([&](Operation *op) {
|
|
|
|
|
if (llvm::any_of(op->getRegions(),
|
|
|
|
|
[](Region ®ion) { return !region.empty(); }))
|
|
|
|
|
ignoredOps.insert(op);
|
|
|
|
|
});
|
2019-10-10 12:01:45 -07:00
|
|
|
}
|
|
|
|
|
|
2019-07-18 12:04:57 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
// ConversionPatternRewriter
|
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
|
|
ConversionPatternRewriter::ConversionPatternRewriter(MLIRContext *ctx,
|
|
|
|
|
TypeConverter *converter)
|
|
|
|
|
: PatternRewriter(ctx),
|
|
|
|
|
impl(new detail::ConversionPatternRewriterImpl(*this, converter)) {}
|
|
|
|
|
ConversionPatternRewriter::~ConversionPatternRewriter() {}
|
|
|
|
|
|
|
|
|
|
/// PatternRewriter hook for replacing the results of an operation.
|
2019-12-06 20:06:48 -08:00
|
|
|
void ConversionPatternRewriter::replaceOp(Operation *op, ValueRange newValues,
|
|
|
|
|
ValueRange valuesToRemoveIfDead) {
|
2019-09-16 10:37:48 -07:00
|
|
|
LLVM_DEBUG(llvm::dbgs() << "** Replacing operation : " << op->getName()
|
|
|
|
|
<< "\n");
|
2019-07-18 12:04:57 -07:00
|
|
|
impl->replaceOp(op, newValues, valuesToRemoveIfDead);
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-16 09:50:28 -07:00
|
|
|
/// PatternRewriter hook for erasing a dead operation. The uses of this
|
|
|
|
|
/// operation *must* be made dead by the end of the conversion process,
|
|
|
|
|
/// otherwise an assert will be issued.
|
|
|
|
|
void ConversionPatternRewriter::eraseOp(Operation *op) {
|
|
|
|
|
LLVM_DEBUG(llvm::dbgs() << "** Erasing operation : " << op->getName()
|
|
|
|
|
<< "\n");
|
|
|
|
|
SmallVector<Value *, 1> nullRepls(op->getNumResults(), nullptr);
|
|
|
|
|
impl->replaceOp(op, nullRepls, /*valuesToRemoveIfDead=*/llvm::None);
|
|
|
|
|
}
|
|
|
|
|
|
2019-07-20 19:05:41 -07:00
|
|
|
/// Apply a signature conversion to the entry block of the given region.
|
2019-11-13 10:27:21 -08:00
|
|
|
Block *ConversionPatternRewriter::applySignatureConversion(
|
2019-07-20 19:05:41 -07:00
|
|
|
Region *region, TypeConverter::SignatureConversion &conversion) {
|
2019-11-13 10:27:21 -08:00
|
|
|
return impl->applySignatureConversion(region, conversion);
|
2019-07-20 19:05:41 -07:00
|
|
|
}
|
|
|
|
|
|
2019-09-27 09:55:38 -07:00
|
|
|
void ConversionPatternRewriter::replaceUsesOfBlockArgument(BlockArgument *from,
|
|
|
|
|
Value *to) {
|
|
|
|
|
for (auto &u : from->getUses()) {
|
|
|
|
|
if (u.getOwner() == to->getDefiningOp())
|
|
|
|
|
continue;
|
|
|
|
|
u.getOwner()->replaceUsesOfWith(from, to);
|
|
|
|
|
}
|
|
|
|
|
impl->mapping.map(impl->mapping.lookupOrDefault(from), to);
|
|
|
|
|
}
|
|
|
|
|
|
2019-11-19 10:15:36 -08:00
|
|
|
/// Return the converted value that replaces 'key'. Return 'key' if there is
|
|
|
|
|
/// no such a converted value.
|
|
|
|
|
Value *ConversionPatternRewriter::getRemappedValue(Value *key) {
|
|
|
|
|
return impl->mapping.lookupOrDefault(key);
|
|
|
|
|
}
|
|
|
|
|
|
2019-07-18 12:04:57 -07:00
|
|
|
/// PatternRewriter hook for splitting a block into two parts.
|
|
|
|
|
Block *ConversionPatternRewriter::splitBlock(Block *block,
|
|
|
|
|
Block::iterator before) {
|
|
|
|
|
auto *continuation = PatternRewriter::splitBlock(block, before);
|
|
|
|
|
impl->notifySplitBlock(block, continuation);
|
|
|
|
|
return continuation;
|
|
|
|
|
}
|
|
|
|
|
|
2019-11-05 11:57:03 -08:00
|
|
|
/// PatternRewriter hook for merging a block into another.
|
|
|
|
|
void ConversionPatternRewriter::mergeBlocks(Block *source, Block *dest,
|
2019-12-06 20:06:48 -08:00
|
|
|
ValueRange argValues) {
|
2019-11-05 11:57:03 -08:00
|
|
|
// TODO(riverriddle) This requires fixing the implementation of
|
|
|
|
|
// 'replaceUsesOfBlockArgument', which currently isn't undoable.
|
|
|
|
|
llvm_unreachable("block merging updates are currently not supported");
|
|
|
|
|
}
|
|
|
|
|
|
2019-07-18 12:04:57 -07:00
|
|
|
/// PatternRewriter hook for moving blocks out of a region.
|
|
|
|
|
void ConversionPatternRewriter::inlineRegionBefore(Region ®ion,
|
|
|
|
|
Region &parent,
|
|
|
|
|
Region::iterator before) {
|
|
|
|
|
impl->notifyRegionIsBeingInlinedBefore(region, parent, before);
|
|
|
|
|
PatternRewriter::inlineRegionBefore(region, parent, before);
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-08 15:44:34 -07:00
|
|
|
/// PatternRewriter hook for cloning blocks of one region into another.
|
|
|
|
|
void ConversionPatternRewriter::cloneRegionBefore(
|
|
|
|
|
Region ®ion, Region &parent, Region::iterator before,
|
|
|
|
|
BlockAndValueMapping &mapping) {
|
|
|
|
|
if (region.empty())
|
|
|
|
|
return;
|
|
|
|
|
PatternRewriter::cloneRegionBefore(region, parent, before, mapping);
|
|
|
|
|
|
|
|
|
|
// Collect the range of the cloned blocks.
|
|
|
|
|
auto clonedBeginIt = mapping.lookup(®ion.front())->getIterator();
|
|
|
|
|
auto clonedBlocks = llvm::make_range(clonedBeginIt, before);
|
|
|
|
|
impl->notifyRegionWasClonedBefore(clonedBlocks, region.getLoc());
|
|
|
|
|
}
|
|
|
|
|
|
2019-07-18 12:04:57 -07:00
|
|
|
/// PatternRewriter hook for creating a new operation.
|
2019-12-11 16:26:08 -08:00
|
|
|
Operation *ConversionPatternRewriter::insert(Operation *op) {
|
|
|
|
|
LLVM_DEBUG(llvm::dbgs() << "** Inserting operation : " << op->getName()
|
|
|
|
|
<< "\n");
|
|
|
|
|
impl->createdOps.push_back(op);
|
|
|
|
|
return OpBuilder::insert(op);
|
2019-07-18 12:04:57 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// PatternRewriter hook for updating the root operation in-place.
|
|
|
|
|
void ConversionPatternRewriter::notifyRootUpdated(Operation *op) {
|
|
|
|
|
// The rewriter caches changes to the IR to allow for operating in-place and
|
|
|
|
|
// backtracking. The rewriter is currently not capable of backtracking
|
|
|
|
|
// in-place modifications.
|
|
|
|
|
llvm_unreachable("in-place operation updates are not supported");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Return a reference to the internal implementation.
|
|
|
|
|
detail::ConversionPatternRewriterImpl &ConversionPatternRewriter::getImpl() {
|
|
|
|
|
return *impl;
|
|
|
|
|
}
|
2019-05-17 22:21:13 -07:00
|
|
|
|
2019-05-19 20:54:13 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2019-07-12 18:11:40 -07:00
|
|
|
// Conversion Patterns
|
2019-05-19 20:54:13 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
2019-06-06 15:38:08 -07:00
|
|
|
/// Attempt to match and rewrite the IR root at the specified operation.
|
|
|
|
|
PatternMatchResult
|
|
|
|
|
ConversionPattern::matchAndRewrite(Operation *op,
|
|
|
|
|
PatternRewriter &rewriter) const {
|
2019-05-17 22:21:13 -07:00
|
|
|
SmallVector<Value *, 4> operands;
|
2019-07-18 12:04:57 -07:00
|
|
|
auto &dialectRewriter = static_cast<ConversionPatternRewriter &>(rewriter);
|
|
|
|
|
dialectRewriter.getImpl().remapValues(op->getOperands(), operands);
|
2019-05-17 22:21:13 -07:00
|
|
|
|
|
|
|
|
// If this operation has no successors, invoke the rewrite directly.
|
|
|
|
|
if (op->getNumSuccessors() == 0)
|
2019-07-18 12:04:57 -07:00
|
|
|
return matchAndRewrite(op, operands, dialectRewriter);
|
2019-05-17 22:21:13 -07:00
|
|
|
|
|
|
|
|
// Otherwise, we need to remap the successors.
|
|
|
|
|
SmallVector<Block *, 2> destinations;
|
|
|
|
|
destinations.reserve(op->getNumSuccessors());
|
|
|
|
|
|
|
|
|
|
SmallVector<ArrayRef<Value *>, 2> operandsPerDestination;
|
|
|
|
|
unsigned firstSuccessorOperand = op->getSuccessorOperandIndex(0);
|
|
|
|
|
for (unsigned i = 0, seen = 0, e = op->getNumSuccessors(); i < e; ++i) {
|
2019-05-19 17:56:32 -07:00
|
|
|
destinations.push_back(op->getSuccessor(i));
|
2019-05-17 22:21:13 -07:00
|
|
|
|
|
|
|
|
// Lookup the successors operands.
|
|
|
|
|
unsigned n = op->getNumSuccessorOperands(i);
|
|
|
|
|
operandsPerDestination.push_back(
|
|
|
|
|
llvm::makeArrayRef(operands.data() + firstSuccessorOperand + seen, n));
|
|
|
|
|
seen += n;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Rewrite the operation.
|
2019-06-06 15:38:08 -07:00
|
|
|
return matchAndRewrite(
|
|
|
|
|
op,
|
|
|
|
|
llvm::makeArrayRef(operands.data(),
|
|
|
|
|
operands.data() + firstSuccessorOperand),
|
2019-07-18 12:04:57 -07:00
|
|
|
destinations, operandsPerDestination, dialectRewriter);
|
2019-05-17 22:21:13 -07:00
|
|
|
}
|
|
|
|
|
|
2019-06-03 12:49:55 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
// OperationLegalizer
|
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
|
|
namespace {
|
2019-06-06 15:48:14 -07:00
|
|
|
/// A set of rewrite patterns that can be used to legalize a given operation.
|
|
|
|
|
using LegalizationPatterns = SmallVector<RewritePattern *, 1>;
|
2019-06-03 12:49:55 -07:00
|
|
|
|
|
|
|
|
/// This class defines a recursive operation legalizer.
|
|
|
|
|
class OperationLegalizer {
|
|
|
|
|
public:
|
2019-07-17 09:26:57 -07:00
|
|
|
using LegalizationAction = ConversionTarget::LegalizationAction;
|
|
|
|
|
|
2019-06-03 12:49:55 -07:00
|
|
|
OperationLegalizer(ConversionTarget &targetInfo,
|
2019-08-11 18:33:42 -07:00
|
|
|
const OwningRewritePatternList &patterns)
|
2019-06-03 12:49:55 -07:00
|
|
|
: target(targetInfo) {
|
|
|
|
|
buildLegalizationGraph(patterns);
|
2019-06-11 15:38:13 -07:00
|
|
|
computeLegalizationGraphBenefit();
|
2019-06-03 12:49:55 -07:00
|
|
|
}
|
|
|
|
|
|
2019-07-17 09:26:57 -07:00
|
|
|
/// Returns if the given operation is known to be illegal on the target.
|
|
|
|
|
bool isIllegal(Operation *op) const;
|
|
|
|
|
|
2019-06-03 12:49:55 -07:00
|
|
|
/// Attempt to legalize the given operation. Returns success if the operation
|
|
|
|
|
/// was legalized, failure otherwise.
|
2019-07-18 12:04:57 -07:00
|
|
|
LogicalResult legalize(Operation *op, ConversionPatternRewriter &rewriter);
|
2019-06-03 12:49:55 -07:00
|
|
|
|
2019-10-28 10:03:57 -07:00
|
|
|
/// Returns the conversion target in use by the legalizer.
|
|
|
|
|
ConversionTarget &getTarget() { return target; }
|
|
|
|
|
|
2019-06-03 12:49:55 -07:00
|
|
|
private:
|
2019-12-13 12:21:42 -08:00
|
|
|
/// Attempt to legalize the given operation by folding it.
|
|
|
|
|
LogicalResult legalizeWithFold(Operation *op,
|
|
|
|
|
ConversionPatternRewriter &rewriter);
|
|
|
|
|
|
2019-06-03 12:49:55 -07:00
|
|
|
/// Attempt to legalize the given operation by applying the provided pattern.
|
|
|
|
|
/// Returns success if the operation was legalized, failure otherwise.
|
|
|
|
|
LogicalResult legalizePattern(Operation *op, RewritePattern *pattern,
|
2019-07-18 12:04:57 -07:00
|
|
|
ConversionPatternRewriter &rewriter);
|
2019-06-03 12:49:55 -07:00
|
|
|
|
|
|
|
|
/// Build an optimistic legalization graph given the provided patterns. This
|
2019-06-06 15:48:14 -07:00
|
|
|
/// function populates 'legalizerPatterns' with the operations that are not
|
|
|
|
|
/// directly legal, but may be transitively legal for the current target given
|
|
|
|
|
/// the provided patterns.
|
2019-08-11 18:33:42 -07:00
|
|
|
void buildLegalizationGraph(const OwningRewritePatternList &patterns);
|
2019-06-03 12:49:55 -07:00
|
|
|
|
2019-06-11 15:38:13 -07:00
|
|
|
/// Compute the benefit of each node within the computed legalization graph.
|
|
|
|
|
/// This orders the patterns within 'legalizerPatterns' based upon two
|
|
|
|
|
/// criteria:
|
|
|
|
|
/// 1) Prefer patterns that have the lowest legalization depth, i.e.
|
|
|
|
|
/// represent the more direct mapping to the target.
|
|
|
|
|
/// 2) When comparing patterns with the same legalization depth, prefer the
|
|
|
|
|
/// pattern with the highest PatternBenefit. This allows for users to
|
|
|
|
|
/// prefer specific legalizations over others.
|
|
|
|
|
void computeLegalizationGraphBenefit();
|
|
|
|
|
|
2019-06-03 12:49:55 -07:00
|
|
|
/// The current set of patterns that have been applied.
|
2019-12-18 09:28:48 -08:00
|
|
|
SmallPtrSet<RewritePattern *, 8> appliedPatterns;
|
2019-06-03 12:49:55 -07:00
|
|
|
|
|
|
|
|
/// The set of legality information for operations transitively supported by
|
|
|
|
|
/// the target.
|
2019-06-06 15:48:14 -07:00
|
|
|
DenseMap<OperationName, LegalizationPatterns> legalizerPatterns;
|
2019-06-03 12:49:55 -07:00
|
|
|
|
|
|
|
|
/// The legalization information provided by the target.
|
|
|
|
|
ConversionTarget ⌖
|
|
|
|
|
};
|
|
|
|
|
} // namespace
|
|
|
|
|
|
2019-07-17 09:26:57 -07:00
|
|
|
bool OperationLegalizer::isIllegal(Operation *op) const {
|
|
|
|
|
// Check if the target explicitly marked this operation as illegal.
|
2019-10-28 10:03:57 -07:00
|
|
|
return target.getOpAction(op->getName()) == LegalizationAction::Illegal;
|
2019-07-17 09:26:57 -07:00
|
|
|
}
|
|
|
|
|
|
2019-06-03 12:49:55 -07:00
|
|
|
LogicalResult
|
|
|
|
|
OperationLegalizer::legalize(Operation *op,
|
2019-07-18 12:04:57 -07:00
|
|
|
ConversionPatternRewriter &rewriter) {
|
2019-06-03 12:49:55 -07:00
|
|
|
LLVM_DEBUG(llvm::dbgs() << "Legalizing operation : " << op->getName()
|
|
|
|
|
<< "\n");
|
|
|
|
|
|
2019-07-18 18:20:03 -07:00
|
|
|
// Check if this operation is legal on the target.
|
2019-10-28 10:03:57 -07:00
|
|
|
if (auto legalityInfo = target.isLegal(op)) {
|
2019-07-18 18:20:03 -07:00
|
|
|
LLVM_DEBUG(llvm::dbgs()
|
|
|
|
|
<< "-- Success : Operation marked legal by the target\n");
|
2019-10-28 10:03:57 -07:00
|
|
|
// If this operation is recursively legal, mark its children as ignored so
|
|
|
|
|
// that we don't consider them for legalization.
|
|
|
|
|
if (legalityInfo->isRecursivelyLegal) {
|
|
|
|
|
LLVM_DEBUG(llvm::dbgs() << "-- Success : Operation is recursively legal; "
|
|
|
|
|
"Skipping internals\n");
|
|
|
|
|
rewriter.getImpl().markNestedOpsIgnored(op);
|
|
|
|
|
}
|
2019-07-18 18:20:03 -07:00
|
|
|
return success();
|
2019-06-03 12:49:55 -07:00
|
|
|
}
|
|
|
|
|
|
2019-10-28 10:03:57 -07:00
|
|
|
// Check to see if the operation is ignored and doesn't need to be converted.
|
|
|
|
|
if (rewriter.getImpl().isOpIgnored(op)) {
|
2019-10-10 12:01:45 -07:00
|
|
|
LLVM_DEBUG(llvm::dbgs()
|
2019-10-28 10:03:57 -07:00
|
|
|
<< "-- Success : Operation marked ignored during conversion\n");
|
2019-10-10 12:01:45 -07:00
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
2019-12-13 12:21:42 -08:00
|
|
|
// If the operation isn't legal, try to fold it in-place.
|
|
|
|
|
// TODO(riverriddle) Should we always try to do this, even if the op is
|
|
|
|
|
// already legal?
|
|
|
|
|
if (succeeded(legalizeWithFold(op, rewriter))) {
|
|
|
|
|
LLVM_DEBUG(llvm::dbgs() << "-- Success : Operation was folded\n");
|
|
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
2019-06-03 12:49:55 -07:00
|
|
|
// Otherwise, we need to apply a legalization pattern to this operation.
|
2019-06-06 15:48:14 -07:00
|
|
|
auto it = legalizerPatterns.find(op->getName());
|
|
|
|
|
if (it == legalizerPatterns.end()) {
|
|
|
|
|
LLVM_DEBUG(llvm::dbgs() << "-- FAIL : no known legalization path.\n");
|
|
|
|
|
return failure();
|
|
|
|
|
}
|
|
|
|
|
|
2019-07-17 09:26:57 -07:00
|
|
|
// The patterns are sorted by expected benefit, so try to apply each in-order.
|
2019-06-06 15:48:14 -07:00
|
|
|
for (auto *pattern : it->second)
|
2019-06-03 12:49:55 -07:00
|
|
|
if (succeeded(legalizePattern(op, pattern, rewriter)))
|
|
|
|
|
return success();
|
|
|
|
|
|
|
|
|
|
LLVM_DEBUG(llvm::dbgs() << "-- FAIL : no matched legalization pattern.\n");
|
|
|
|
|
return failure();
|
|
|
|
|
}
|
|
|
|
|
|
2019-12-13 12:21:42 -08:00
|
|
|
LogicalResult
|
|
|
|
|
OperationLegalizer::legalizeWithFold(Operation *op,
|
|
|
|
|
ConversionPatternRewriter &rewriter) {
|
|
|
|
|
auto &rewriterImpl = rewriter.getImpl();
|
|
|
|
|
RewriterState curState = rewriterImpl.getCurrentState();
|
|
|
|
|
|
|
|
|
|
// Try to fold the operation.
|
|
|
|
|
SmallVector<Value *, 2> replacementValues;
|
|
|
|
|
rewriter.setInsertionPoint(op);
|
|
|
|
|
if (failed(rewriter.tryFold(op, replacementValues)))
|
|
|
|
|
return failure();
|
|
|
|
|
|
|
|
|
|
// Insert a replacement for 'op' with the folded replacement values.
|
|
|
|
|
rewriter.replaceOp(op, replacementValues);
|
|
|
|
|
|
|
|
|
|
// Recursively legalize any new constant operations.
|
|
|
|
|
for (unsigned i = curState.numCreatedOperations,
|
|
|
|
|
e = rewriterImpl.createdOps.size();
|
|
|
|
|
i != e; ++i) {
|
|
|
|
|
Operation *cstOp = rewriterImpl.createdOps[i];
|
|
|
|
|
if (failed(legalize(cstOp, rewriter))) {
|
|
|
|
|
LLVM_DEBUG(llvm::dbgs() << "-- FAIL: Generated folding constant '"
|
|
|
|
|
<< cstOp->getName() << "' was illegal.\n");
|
|
|
|
|
rewriterImpl.resetState(curState);
|
|
|
|
|
return failure();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
2019-06-03 12:49:55 -07:00
|
|
|
LogicalResult
|
|
|
|
|
OperationLegalizer::legalizePattern(Operation *op, RewritePattern *pattern,
|
2019-07-18 12:04:57 -07:00
|
|
|
ConversionPatternRewriter &rewriter) {
|
2019-06-03 12:49:55 -07:00
|
|
|
LLVM_DEBUG({
|
|
|
|
|
llvm::dbgs() << "-* Applying rewrite pattern '" << op->getName() << " -> (";
|
|
|
|
|
interleaveComma(pattern->getGeneratedOps(), llvm::dbgs());
|
|
|
|
|
llvm::dbgs() << ")'.\n";
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Ensure that we don't cycle by not allowing the same pattern to be
|
|
|
|
|
// applied twice in the same recursion stack.
|
|
|
|
|
// TODO(riverriddle) We could eventually converge, but that requires more
|
|
|
|
|
// complicated analysis.
|
|
|
|
|
if (!appliedPatterns.insert(pattern).second) {
|
|
|
|
|
LLVM_DEBUG(llvm::dbgs() << "-- FAIL: Pattern was already applied.\n");
|
|
|
|
|
return failure();
|
|
|
|
|
}
|
|
|
|
|
|
2019-07-18 12:04:57 -07:00
|
|
|
auto &rewriterImpl = rewriter.getImpl();
|
|
|
|
|
RewriterState curState = rewriterImpl.getCurrentState();
|
2019-06-03 12:49:55 -07:00
|
|
|
auto cleanupFailure = [&] {
|
2019-06-05 09:36:32 -07:00
|
|
|
// Reset the rewriter state and pop this pattern.
|
2019-07-18 12:04:57 -07:00
|
|
|
rewriterImpl.resetState(curState);
|
2019-06-03 12:49:55 -07:00
|
|
|
appliedPatterns.erase(pattern);
|
|
|
|
|
return failure();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Try to rewrite with the given pattern.
|
|
|
|
|
rewriter.setInsertionPoint(op);
|
|
|
|
|
if (!pattern->matchAndRewrite(op, rewriter)) {
|
|
|
|
|
LLVM_DEBUG(llvm::dbgs() << "-- FAIL: Pattern failed to match.\n");
|
|
|
|
|
return cleanupFailure();
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-08 15:44:34 -07:00
|
|
|
// If the pattern moved or created any blocks, try to legalize their types.
|
|
|
|
|
// This ensures that the types of the block arguments are legal for the region
|
|
|
|
|
// they were moved into.
|
2019-08-16 10:16:09 -07:00
|
|
|
for (unsigned i = curState.numBlockActions,
|
|
|
|
|
e = rewriterImpl.blockActions.size();
|
|
|
|
|
i != e; ++i) {
|
|
|
|
|
auto &action = rewriterImpl.blockActions[i];
|
2019-10-08 15:44:34 -07:00
|
|
|
if (action.kind ==
|
|
|
|
|
ConversionPatternRewriterImpl::BlockActionKind::TypeConversion)
|
2019-08-16 10:16:09 -07:00
|
|
|
continue;
|
|
|
|
|
|
|
|
|
|
// Convert the block signature.
|
|
|
|
|
if (failed(rewriterImpl.convertBlockSignature(action.block))) {
|
|
|
|
|
LLVM_DEBUG(llvm::dbgs()
|
|
|
|
|
<< "-- FAIL: failed to convert types of moved block.\n");
|
|
|
|
|
return cleanupFailure();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-14 09:50:54 -07:00
|
|
|
// Check all of the replacements to ensure that the pattern actually replaced
|
|
|
|
|
// the root operation. We also mark any other replaced ops as 'dead' so that
|
|
|
|
|
// we don't try to legalize them later.
|
|
|
|
|
bool replacedRoot = false;
|
|
|
|
|
for (unsigned i = curState.numReplacements,
|
|
|
|
|
e = rewriterImpl.replacements.size();
|
|
|
|
|
i != e; ++i) {
|
|
|
|
|
Operation *replacedOp = rewriterImpl.replacements[i].op;
|
|
|
|
|
if (replacedOp == op)
|
|
|
|
|
replacedRoot = true;
|
|
|
|
|
else
|
2019-10-28 10:03:57 -07:00
|
|
|
rewriterImpl.ignoredOps.insert(replacedOp);
|
2019-10-14 09:50:54 -07:00
|
|
|
}
|
|
|
|
|
assert(replacedRoot && "expected pattern to replace the root operation");
|
2019-10-23 14:31:44 -07:00
|
|
|
(void)replacedRoot;
|
2019-10-14 09:50:54 -07:00
|
|
|
|
2019-06-03 12:49:55 -07:00
|
|
|
// Recursively legalize each of the new operations.
|
2019-06-05 09:36:32 -07:00
|
|
|
for (unsigned i = curState.numCreatedOperations,
|
2019-07-18 12:04:57 -07:00
|
|
|
e = rewriterImpl.createdOps.size();
|
2019-06-05 09:36:32 -07:00
|
|
|
i != e; ++i) {
|
2019-09-13 01:37:07 -07:00
|
|
|
Operation *op = rewriterImpl.createdOps[i];
|
|
|
|
|
if (failed(legalize(op, rewriter))) {
|
|
|
|
|
LLVM_DEBUG(llvm::dbgs() << "-- FAIL: Generated operation '"
|
|
|
|
|
<< op->getName() << "' was illegal.\n");
|
2019-06-05 09:36:32 -07:00
|
|
|
return cleanupFailure();
|
|
|
|
|
}
|
2019-06-03 12:49:55 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
appliedPatterns.erase(pattern);
|
|
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void OperationLegalizer::buildLegalizationGraph(
|
2019-08-11 18:33:42 -07:00
|
|
|
const OwningRewritePatternList &patterns) {
|
2019-06-03 12:49:55 -07:00
|
|
|
// A mapping between an operation and a set of operations that can be used to
|
|
|
|
|
// generate it.
|
|
|
|
|
DenseMap<OperationName, SmallPtrSet<OperationName, 2>> parentOps;
|
|
|
|
|
// A mapping between an operation and any currently invalid patterns it has.
|
|
|
|
|
DenseMap<OperationName, SmallPtrSet<RewritePattern *, 2>> invalidPatterns;
|
|
|
|
|
// A worklist of patterns to consider for legality.
|
|
|
|
|
llvm::SetVector<RewritePattern *> patternWorklist;
|
|
|
|
|
|
|
|
|
|
// Build the mapping from operations to the parent ops that may generate them.
|
|
|
|
|
for (auto &pattern : patterns) {
|
|
|
|
|
auto root = pattern->getRootKind();
|
|
|
|
|
|
2019-06-06 15:48:14 -07:00
|
|
|
// Skip operations that are always known to be legal.
|
2019-07-17 09:26:57 -07:00
|
|
|
if (target.getOpAction(root) == LegalizationAction::Legal)
|
2019-06-03 12:49:55 -07:00
|
|
|
continue;
|
|
|
|
|
|
|
|
|
|
// Add this pattern to the invalid set for the root op and record this root
|
|
|
|
|
// as a parent for any generated operations.
|
|
|
|
|
invalidPatterns[root].insert(pattern.get());
|
|
|
|
|
for (auto op : pattern->getGeneratedOps())
|
|
|
|
|
parentOps[op].insert(root);
|
|
|
|
|
|
2019-06-06 15:48:14 -07:00
|
|
|
// Add this pattern to the worklist.
|
|
|
|
|
patternWorklist.insert(pattern.get());
|
2019-06-03 12:49:55 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
while (!patternWorklist.empty()) {
|
|
|
|
|
auto *pattern = patternWorklist.pop_back_val();
|
|
|
|
|
|
|
|
|
|
// Check to see if any of the generated operations are invalid.
|
2019-06-06 15:48:14 -07:00
|
|
|
if (llvm::any_of(pattern->getGeneratedOps(), [&](OperationName op) {
|
2019-10-28 10:03:57 -07:00
|
|
|
Optional<LegalizationAction> action = target.getOpAction(op);
|
2019-07-17 09:26:57 -07:00
|
|
|
return !legalizerPatterns.count(op) &&
|
|
|
|
|
(!action || action == LegalizationAction::Illegal);
|
2019-06-06 15:48:14 -07:00
|
|
|
}))
|
2019-06-03 12:49:55 -07:00
|
|
|
continue;
|
|
|
|
|
|
|
|
|
|
// Otherwise, if all of the generated operation are valid, this op is now
|
|
|
|
|
// legal so add all of the child patterns to the worklist.
|
2019-06-06 15:48:14 -07:00
|
|
|
legalizerPatterns[pattern->getRootKind()].push_back(pattern);
|
2019-06-03 12:49:55 -07:00
|
|
|
invalidPatterns[pattern->getRootKind()].erase(pattern);
|
|
|
|
|
|
|
|
|
|
// Add any invalid patterns of the parent operations to see if they have now
|
|
|
|
|
// become legal.
|
|
|
|
|
for (auto op : parentOps[pattern->getRootKind()])
|
|
|
|
|
patternWorklist.set_union(invalidPatterns[op]);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-06-11 15:38:13 -07:00
|
|
|
void OperationLegalizer::computeLegalizationGraphBenefit() {
|
|
|
|
|
// The smallest pattern depth, when legalizing an operation.
|
|
|
|
|
DenseMap<OperationName, unsigned> minPatternDepth;
|
|
|
|
|
|
|
|
|
|
// Compute the minimum legalization depth for a given operation.
|
|
|
|
|
std::function<unsigned(OperationName)> computeDepth = [&](OperationName op) {
|
|
|
|
|
// Check for existing depth.
|
|
|
|
|
auto depthIt = minPatternDepth.find(op);
|
|
|
|
|
if (depthIt != minPatternDepth.end())
|
|
|
|
|
return depthIt->second;
|
|
|
|
|
|
|
|
|
|
// If a mapping for this operation does not exist, then this operation
|
|
|
|
|
// is always legal. Return 0 as the depth for a directly legal operation.
|
|
|
|
|
auto opPatternsIt = legalizerPatterns.find(op);
|
2019-09-20 16:29:44 -07:00
|
|
|
if (opPatternsIt == legalizerPatterns.end() || opPatternsIt->second.empty())
|
2019-06-11 15:38:13 -07:00
|
|
|
return 0u;
|
|
|
|
|
|
|
|
|
|
// Initialize the depth to the maximum value.
|
2019-09-20 16:29:44 -07:00
|
|
|
unsigned minDepth = std::numeric_limits<unsigned>::max();
|
|
|
|
|
|
|
|
|
|
// Record this initial depth in case we encounter this op again when
|
|
|
|
|
// recursively computing the depth.
|
|
|
|
|
minPatternDepth.try_emplace(op, minDepth);
|
2019-06-11 15:38:13 -07:00
|
|
|
|
|
|
|
|
// Compute the depth for each pattern used to legalize this operation.
|
|
|
|
|
SmallVector<std::pair<RewritePattern *, unsigned>, 4> patternsByDepth;
|
|
|
|
|
patternsByDepth.reserve(opPatternsIt->second.size());
|
|
|
|
|
for (RewritePattern *pattern : opPatternsIt->second) {
|
|
|
|
|
unsigned depth = 0;
|
|
|
|
|
for (auto generatedOp : pattern->getGeneratedOps())
|
|
|
|
|
depth = std::max(depth, computeDepth(generatedOp) + 1);
|
|
|
|
|
patternsByDepth.emplace_back(pattern, depth);
|
|
|
|
|
|
|
|
|
|
// Update the min depth for this operation.
|
|
|
|
|
minDepth = std::min(minDepth, depth);
|
|
|
|
|
}
|
|
|
|
|
|
2019-09-20 16:29:44 -07:00
|
|
|
// Update the pattern depth.
|
|
|
|
|
minPatternDepth[op] = minDepth;
|
|
|
|
|
|
2019-06-11 15:38:13 -07:00
|
|
|
// If the operation only has one legalization pattern, there is no need to
|
|
|
|
|
// sort them.
|
|
|
|
|
if (patternsByDepth.size() == 1)
|
|
|
|
|
return minDepth;
|
|
|
|
|
|
|
|
|
|
// Sort the patterns by those likely to be the most beneficial.
|
|
|
|
|
llvm::array_pod_sort(
|
|
|
|
|
patternsByDepth.begin(), patternsByDepth.end(),
|
|
|
|
|
[](const std::pair<RewritePattern *, unsigned> *lhs,
|
|
|
|
|
const std::pair<RewritePattern *, unsigned> *rhs) {
|
|
|
|
|
// First sort by the smaller pattern legalization depth.
|
|
|
|
|
if (lhs->second != rhs->second)
|
|
|
|
|
return llvm::array_pod_sort_comparator<unsigned>(&lhs->second,
|
|
|
|
|
&rhs->second);
|
|
|
|
|
|
|
|
|
|
// Then sort by the larger pattern benefit.
|
|
|
|
|
auto lhsBenefit = lhs->first->getBenefit();
|
|
|
|
|
auto rhsBenefit = rhs->first->getBenefit();
|
|
|
|
|
return llvm::array_pod_sort_comparator<PatternBenefit>(&rhsBenefit,
|
|
|
|
|
&lhsBenefit);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Update the legalization pattern to use the new sorted list.
|
|
|
|
|
opPatternsIt->second.clear();
|
|
|
|
|
for (auto &patternIt : patternsByDepth)
|
|
|
|
|
opPatternsIt->second.push_back(patternIt.first);
|
|
|
|
|
|
|
|
|
|
return minDepth;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// For each operation that is transitively legal, compute a cost for it.
|
|
|
|
|
for (auto &opIt : legalizerPatterns)
|
|
|
|
|
if (!minPatternDepth.count(opIt.first))
|
|
|
|
|
computeDepth(opIt.first);
|
|
|
|
|
}
|
|
|
|
|
|
2019-05-19 20:54:13 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2019-07-16 11:57:45 -07:00
|
|
|
// OperationConverter
|
2019-05-19 20:54:13 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
namespace {
|
2019-07-16 11:57:45 -07:00
|
|
|
enum OpConversionMode {
|
|
|
|
|
// In this mode, the conversion will ignore failed conversions to allow
|
|
|
|
|
// illegal operations to co-exist in the IR.
|
|
|
|
|
Partial,
|
|
|
|
|
|
|
|
|
|
// In this mode, all operations must be legal for the given target for the
|
2019-10-04 04:37:14 -07:00
|
|
|
// conversion to succeed.
|
2019-07-16 11:57:45 -07:00
|
|
|
Full,
|
2019-07-25 11:30:41 -07:00
|
|
|
|
|
|
|
|
// In this mode, operations are analyzed for legality. No actual rewrites are
|
|
|
|
|
// applied to the operations on success.
|
|
|
|
|
Analysis,
|
2019-07-16 11:57:45 -07:00
|
|
|
};
|
|
|
|
|
|
2019-08-16 10:16:09 -07:00
|
|
|
// This class converts operations to a given conversion target via a set of
|
|
|
|
|
// rewrite patterns. The conversion behaves differently depending on the
|
|
|
|
|
// conversion mode.
|
2019-07-16 11:57:45 -07:00
|
|
|
struct OperationConverter {
|
|
|
|
|
explicit OperationConverter(ConversionTarget &target,
|
2019-08-11 18:33:42 -07:00
|
|
|
const OwningRewritePatternList &patterns,
|
2019-07-25 11:30:41 -07:00
|
|
|
OpConversionMode mode,
|
|
|
|
|
DenseSet<Operation *> *legalizableOps = nullptr)
|
|
|
|
|
: opLegalizer(target, patterns), mode(mode),
|
|
|
|
|
legalizableOps(legalizableOps) {}
|
2019-07-16 11:57:45 -07:00
|
|
|
|
|
|
|
|
/// Converts the given operations to the conversion target.
|
2019-07-17 14:45:53 -07:00
|
|
|
LogicalResult convertOperations(ArrayRef<Operation *> ops,
|
|
|
|
|
TypeConverter *typeConverter);
|
Generic dialect conversion pass exercised by LLVM IR lowering
This commit introduces a generic dialect conversion/lowering/legalization pass
and illustrates it on StandardOps->LLVMIR conversion.
It partially reuses the PatternRewriter infrastructure and adds the following
functionality:
- an actual pass;
- non-default pattern constructors;
- one-to-many rewrites;
- rewriting terminators with successors;
- not applying patterns iteratively (unlike the existing greedy rewrite driver);
- ability to change function signature;
- ability to change basic block argument types.
The latter two things required, given the existing API, to create new functions
in the same module. Eventually, this should converge with the rest of
PatternRewriter. However, we may want to keep two pass versions: "heavy" with
function/block argument conversion and "light" that only touches operations.
This pass creates new functions within a module as a means to change function
signature, then creates new blocks with converted argument types in the new
function. Then, it traverses the CFG in DFS-preorder to make sure defs are
converted before uses in the dominated blocks. The generic pass has a minimal
interface with two hooks: one to fill in the set of patterns, and another one
to convert types for functions and blocks. The patterns are defined as
separate classes that can be table-generated in the future.
The LLVM IR lowering pass partially inherits from the existing LLVM IR
translator, in particular for type conversion. It defines a conversion pattern
template, instantiated for different operations, and is a good candidate for
tablegen. The lowering does not yet support loads and stores and is not
connected to the translator as it would have broken the existing flows. Future
patches will add missing support before switching the translator in a single
patch.
PiperOrigin-RevId: 230951202
2019-01-25 12:46:53 -08:00
|
|
|
|
2019-07-15 08:40:11 -07:00
|
|
|
private:
|
2019-07-17 14:45:53 -07:00
|
|
|
/// Converts an operation with the given rewriter.
|
2019-07-18 12:04:57 -07:00
|
|
|
LogicalResult convert(ConversionPatternRewriter &rewriter, Operation *op);
|
2019-07-17 14:45:53 -07:00
|
|
|
|
2019-08-16 10:16:09 -07:00
|
|
|
/// Converts the type signatures of the blocks nested within 'op'.
|
2019-07-20 19:05:41 -07:00
|
|
|
LogicalResult convertBlockSignatures(ConversionPatternRewriter &rewriter,
|
|
|
|
|
Operation *op);
|
|
|
|
|
|
2019-06-03 12:49:55 -07:00
|
|
|
/// The legalizer to use when converting operations.
|
|
|
|
|
OperationLegalizer opLegalizer;
|
2019-07-16 11:57:45 -07:00
|
|
|
|
|
|
|
|
/// The conversion mode to use when legalizing operations.
|
|
|
|
|
OpConversionMode mode;
|
2019-07-25 11:30:41 -07:00
|
|
|
|
|
|
|
|
/// A set of pre-existing operations that were found to be legalizable to the
|
|
|
|
|
/// target. This field is only used when mode == OpConversionMode::Analysis.
|
|
|
|
|
DenseSet<Operation *> *legalizableOps;
|
Generic dialect conversion pass exercised by LLVM IR lowering
This commit introduces a generic dialect conversion/lowering/legalization pass
and illustrates it on StandardOps->LLVMIR conversion.
It partially reuses the PatternRewriter infrastructure and adds the following
functionality:
- an actual pass;
- non-default pattern constructors;
- one-to-many rewrites;
- rewriting terminators with successors;
- not applying patterns iteratively (unlike the existing greedy rewrite driver);
- ability to change function signature;
- ability to change basic block argument types.
The latter two things required, given the existing API, to create new functions
in the same module. Eventually, this should converge with the rest of
PatternRewriter. However, we may want to keep two pass versions: "heavy" with
function/block argument conversion and "light" that only touches operations.
This pass creates new functions within a module as a means to change function
signature, then creates new blocks with converted argument types in the new
function. Then, it traverses the CFG in DFS-preorder to make sure defs are
converted before uses in the dominated blocks. The generic pass has a minimal
interface with two hooks: one to fill in the set of patterns, and another one
to convert types for functions and blocks. The patterns are defined as
separate classes that can be table-generated in the future.
The LLVM IR lowering pass partially inherits from the existing LLVM IR
translator, in particular for type conversion. It defines a conversion pattern
template, instantiated for different operations, and is a good candidate for
tablegen. The lowering does not yet support loads and stores and is not
connected to the translator as it would have broken the existing flows. Future
patches will add missing support before switching the translator in a single
patch.
PiperOrigin-RevId: 230951202
2019-01-25 12:46:53 -08:00
|
|
|
};
|
2019-05-19 20:54:13 -07:00
|
|
|
} // end anonymous namespace
|
Generic dialect conversion pass exercised by LLVM IR lowering
This commit introduces a generic dialect conversion/lowering/legalization pass
and illustrates it on StandardOps->LLVMIR conversion.
It partially reuses the PatternRewriter infrastructure and adds the following
functionality:
- an actual pass;
- non-default pattern constructors;
- one-to-many rewrites;
- rewriting terminators with successors;
- not applying patterns iteratively (unlike the existing greedy rewrite driver);
- ability to change function signature;
- ability to change basic block argument types.
The latter two things required, given the existing API, to create new functions
in the same module. Eventually, this should converge with the rest of
PatternRewriter. However, we may want to keep two pass versions: "heavy" with
function/block argument conversion and "light" that only touches operations.
This pass creates new functions within a module as a means to change function
signature, then creates new blocks with converted argument types in the new
function. Then, it traverses the CFG in DFS-preorder to make sure defs are
converted before uses in the dominated blocks. The generic pass has a minimal
interface with two hooks: one to fill in the set of patterns, and another one
to convert types for functions and blocks. The patterns are defined as
separate classes that can be table-generated in the future.
The LLVM IR lowering pass partially inherits from the existing LLVM IR
translator, in particular for type conversion. It defines a conversion pattern
template, instantiated for different operations, and is a good candidate for
tablegen. The lowering does not yet support loads and stores and is not
connected to the translator as it would have broken the existing flows. Future
patches will add missing support before switching the translator in a single
patch.
PiperOrigin-RevId: 230951202
2019-01-25 12:46:53 -08:00
|
|
|
|
2019-07-20 19:05:41 -07:00
|
|
|
LogicalResult
|
|
|
|
|
OperationConverter::convertBlockSignatures(ConversionPatternRewriter &rewriter,
|
|
|
|
|
Operation *op) {
|
2019-08-16 10:16:09 -07:00
|
|
|
// Check to see if type signatures need to be converted.
|
|
|
|
|
if (!rewriter.getImpl().argConverter.typeConverter)
|
|
|
|
|
return success();
|
2019-07-20 19:05:41 -07:00
|
|
|
|
2019-08-16 10:16:09 -07:00
|
|
|
for (auto ®ion : op->getRegions()) {
|
2019-11-13 10:27:21 -08:00
|
|
|
for (auto &block : llvm::make_early_inc_range(region))
|
2019-07-20 19:05:41 -07:00
|
|
|
if (failed(rewriter.getImpl().convertBlockSignature(&block)))
|
|
|
|
|
return failure();
|
|
|
|
|
}
|
|
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
2019-07-18 12:04:57 -07:00
|
|
|
LogicalResult OperationConverter::convert(ConversionPatternRewriter &rewriter,
|
2019-07-17 14:45:53 -07:00
|
|
|
Operation *op) {
|
|
|
|
|
// Legalize the given operation.
|
2019-07-17 09:26:57 -07:00
|
|
|
if (failed(opLegalizer.legalize(op, rewriter))) {
|
|
|
|
|
// Handle the case of a failed conversion for each of the different modes.
|
|
|
|
|
/// Full conversions expect all operations to be converted.
|
|
|
|
|
if (mode == OpConversionMode::Full)
|
|
|
|
|
return op->emitError()
|
|
|
|
|
<< "failed to legalize operation '" << op->getName() << "'";
|
|
|
|
|
/// Partial conversions allow conversions to fail iff the operation was not
|
|
|
|
|
/// explicitly marked as illegal.
|
|
|
|
|
if (mode == OpConversionMode::Partial && opLegalizer.isIllegal(op))
|
|
|
|
|
return op->emitError()
|
|
|
|
|
<< "failed to legalize operation '" << op->getName()
|
|
|
|
|
<< "' that was explicitly marked illegal";
|
2019-08-16 10:16:09 -07:00
|
|
|
} else {
|
|
|
|
|
/// Analysis conversions don't fail if any operations fail to legalize,
|
|
|
|
|
/// they are only interested in the operations that were successfully
|
|
|
|
|
/// legalized.
|
|
|
|
|
if (mode == OpConversionMode::Analysis)
|
|
|
|
|
legalizableOps->insert(op);
|
|
|
|
|
|
|
|
|
|
// If legalization succeeded, convert the types any of the blocks within
|
|
|
|
|
// this operation.
|
|
|
|
|
if (failed(convertBlockSignatures(rewriter, op)))
|
|
|
|
|
return failure();
|
2019-07-17 09:26:57 -07:00
|
|
|
}
|
2019-07-16 11:57:45 -07:00
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
|
2019-07-17 14:45:53 -07:00
|
|
|
LogicalResult
|
|
|
|
|
OperationConverter::convertOperations(ArrayRef<Operation *> ops,
|
|
|
|
|
TypeConverter *typeConverter) {
|
2019-07-16 11:57:45 -07:00
|
|
|
if (ops.empty())
|
|
|
|
|
return success();
|
2019-10-28 10:03:57 -07:00
|
|
|
ConversionTarget &target = opLegalizer.getTarget();
|
2019-07-16 11:57:45 -07:00
|
|
|
|
|
|
|
|
/// Compute the set of operations and blocks to convert.
|
2019-07-17 14:45:53 -07:00
|
|
|
std::vector<Operation *> toConvert;
|
2019-07-16 11:57:45 -07:00
|
|
|
for (auto *op : ops) {
|
|
|
|
|
toConvert.emplace_back(op);
|
|
|
|
|
for (auto ®ion : op->getRegions())
|
2019-10-08 15:44:34 -07:00
|
|
|
if (failed(computeConversionSet(region.getBlocks(), region.getLoc(),
|
2019-10-28 10:03:57 -07:00
|
|
|
toConvert, &target)))
|
2019-07-16 11:57:45 -07:00
|
|
|
return failure();
|
2019-05-19 17:56:32 -07:00
|
|
|
}
|
2019-05-22 11:49:04 -07:00
|
|
|
|
2019-07-17 14:45:53 -07:00
|
|
|
// Convert each operation and discard rewrites on failure.
|
2019-07-18 12:04:57 -07:00
|
|
|
ConversionPatternRewriter rewriter(ops.front()->getContext(), typeConverter);
|
2019-07-20 19:05:41 -07:00
|
|
|
for (auto *op : toConvert)
|
|
|
|
|
if (failed(convert(rewriter, op)))
|
|
|
|
|
return rewriter.getImpl().discardRewrites(), failure();
|
|
|
|
|
|
2019-07-25 11:30:41 -07:00
|
|
|
// Otherwise, the body conversion succeeded. Apply rewrites if this is not an
|
|
|
|
|
// analysis conversion.
|
|
|
|
|
if (mode == OpConversionMode::Analysis)
|
|
|
|
|
rewriter.getImpl().discardRewrites();
|
|
|
|
|
else
|
|
|
|
|
rewriter.getImpl().applyRewrites();
|
2019-07-17 14:45:53 -07:00
|
|
|
return success();
|
Generic dialect conversion pass exercised by LLVM IR lowering
This commit introduces a generic dialect conversion/lowering/legalization pass
and illustrates it on StandardOps->LLVMIR conversion.
It partially reuses the PatternRewriter infrastructure and adds the following
functionality:
- an actual pass;
- non-default pattern constructors;
- one-to-many rewrites;
- rewriting terminators with successors;
- not applying patterns iteratively (unlike the existing greedy rewrite driver);
- ability to change function signature;
- ability to change basic block argument types.
The latter two things required, given the existing API, to create new functions
in the same module. Eventually, this should converge with the rest of
PatternRewriter. However, we may want to keep two pass versions: "heavy" with
function/block argument conversion and "light" that only touches operations.
This pass creates new functions within a module as a means to change function
signature, then creates new blocks with converted argument types in the new
function. Then, it traverses the CFG in DFS-preorder to make sure defs are
converted before uses in the dominated blocks. The generic pass has a minimal
interface with two hooks: one to fill in the set of patterns, and another one
to convert types for functions and blocks. The patterns are defined as
separate classes that can be table-generated in the future.
The LLVM IR lowering pass partially inherits from the existing LLVM IR
translator, in particular for type conversion. It defines a conversion pattern
template, instantiated for different operations, and is a good candidate for
tablegen. The lowering does not yet support loads and stores and is not
connected to the translator as it would have broken the existing flows. Future
patches will add missing support before switching the translator in a single
patch.
PiperOrigin-RevId: 230951202
2019-01-25 12:46:53 -08:00
|
|
|
}
|
|
|
|
|
|
2019-05-19 20:54:13 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2019-07-12 18:11:40 -07:00
|
|
|
// Type Conversion
|
2019-05-19 20:54:13 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
2019-06-19 13:58:31 -07:00
|
|
|
/// Remap an input of the original signature with a new set of types. The
|
|
|
|
|
/// new types are appended to the new signature conversion.
|
2019-07-17 14:45:53 -07:00
|
|
|
void TypeConverter::SignatureConversion::addInputs(unsigned origInputNo,
|
|
|
|
|
ArrayRef<Type> types) {
|
2019-06-19 13:58:31 -07:00
|
|
|
assert(!types.empty() && "expected valid types");
|
|
|
|
|
remapInput(origInputNo, /*newInputNo=*/argTypes.size(), types.size());
|
2019-07-17 14:45:53 -07:00
|
|
|
addInputs(types);
|
2019-06-19 13:58:31 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Append new input types to the signature conversion, this should only be
|
|
|
|
|
/// used if the new types are not intended to remap an existing input.
|
2019-07-17 14:45:53 -07:00
|
|
|
void TypeConverter::SignatureConversion::addInputs(ArrayRef<Type> types) {
|
2019-06-19 13:58:31 -07:00
|
|
|
assert(!types.empty() &&
|
|
|
|
|
"1->0 type remappings don't need to be added explicitly");
|
|
|
|
|
argTypes.append(types.begin(), types.end());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Remap an input of the original signature with a range of types in the
|
|
|
|
|
/// new signature.
|
|
|
|
|
void TypeConverter::SignatureConversion::remapInput(unsigned origInputNo,
|
|
|
|
|
unsigned newInputNo,
|
|
|
|
|
unsigned newInputCount) {
|
|
|
|
|
assert(!remappedInputs[origInputNo] && "input has already been remapped");
|
|
|
|
|
assert(newInputCount != 0 && "expected valid input count");
|
2019-10-16 10:20:31 -07:00
|
|
|
remappedInputs[origInputNo] =
|
|
|
|
|
InputMapping{newInputNo, newInputCount, /*replacementValue=*/nullptr};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Remap an input of the original signature to another `replacementValue`
|
|
|
|
|
/// value. This would make the signature converter drop this argument.
|
|
|
|
|
void TypeConverter::SignatureConversion::remapInput(unsigned origInputNo,
|
|
|
|
|
Value *replacementValue) {
|
|
|
|
|
assert(!remappedInputs[origInputNo] && "input has already been remapped");
|
|
|
|
|
remappedInputs[origInputNo] =
|
|
|
|
|
InputMapping{origInputNo, /*size=*/0, replacementValue};
|
2019-06-19 13:58:31 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// This hooks allows for converting a type.
|
|
|
|
|
LogicalResult TypeConverter::convertType(Type t,
|
|
|
|
|
SmallVectorImpl<Type> &results) {
|
|
|
|
|
if (auto newT = convertType(t)) {
|
|
|
|
|
results.push_back(newT);
|
|
|
|
|
return success();
|
|
|
|
|
}
|
|
|
|
|
return failure();
|
|
|
|
|
}
|
|
|
|
|
|
2019-07-20 19:05:41 -07:00
|
|
|
/// Convert the given set of types, filling 'results' as necessary. This
|
|
|
|
|
/// returns failure if the conversion of any of the types fails, success
|
|
|
|
|
/// otherwise.
|
|
|
|
|
LogicalResult TypeConverter::convertTypes(ArrayRef<Type> types,
|
|
|
|
|
SmallVectorImpl<Type> &results) {
|
|
|
|
|
for (auto type : types)
|
|
|
|
|
if (failed(convertType(type, results)))
|
2019-06-19 13:58:31 -07:00
|
|
|
return failure();
|
2019-07-20 19:05:41 -07:00
|
|
|
return success();
|
|
|
|
|
}
|
2019-06-19 13:58:31 -07:00
|
|
|
|
2019-07-20 19:05:41 -07:00
|
|
|
/// Return true if the given type is legal for this type converter, i.e. the
|
|
|
|
|
/// type converts to itself.
|
|
|
|
|
bool TypeConverter::isLegal(Type type) {
|
|
|
|
|
SmallVector<Type, 1> results;
|
|
|
|
|
return succeeded(convertType(type, results)) && results.size() == 1 &&
|
|
|
|
|
results.front() == type;
|
|
|
|
|
}
|
2019-06-19 13:58:31 -07:00
|
|
|
|
2019-07-20 19:05:41 -07:00
|
|
|
/// Return true if the inputs and outputs of the given function type are
|
|
|
|
|
/// legal.
|
|
|
|
|
bool TypeConverter::isSignatureLegal(FunctionType funcType) {
|
|
|
|
|
return llvm::all_of(
|
|
|
|
|
llvm::concat<const Type>(funcType.getInputs(), funcType.getResults()),
|
|
|
|
|
[this](Type type) { return isLegal(type); });
|
2019-06-19 13:58:31 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// This hook allows for converting a specific argument of a signature.
|
|
|
|
|
LogicalResult TypeConverter::convertSignatureArg(unsigned inputNo, Type type,
|
|
|
|
|
SignatureConversion &result) {
|
|
|
|
|
// Try to convert the given input type.
|
|
|
|
|
SmallVector<Type, 1> convertedTypes;
|
|
|
|
|
if (failed(convertType(type, convertedTypes)))
|
|
|
|
|
return failure();
|
|
|
|
|
|
|
|
|
|
// If this argument is being dropped, there is nothing left to do.
|
|
|
|
|
if (convertedTypes.empty())
|
|
|
|
|
return success();
|
|
|
|
|
|
|
|
|
|
// Otherwise, add the new inputs.
|
2019-07-17 14:45:53 -07:00
|
|
|
result.addInputs(inputNo, convertedTypes);
|
2019-06-19 13:58:31 -07:00
|
|
|
return success();
|
Generic dialect conversion pass exercised by LLVM IR lowering
This commit introduces a generic dialect conversion/lowering/legalization pass
and illustrates it on StandardOps->LLVMIR conversion.
It partially reuses the PatternRewriter infrastructure and adds the following
functionality:
- an actual pass;
- non-default pattern constructors;
- one-to-many rewrites;
- rewriting terminators with successors;
- not applying patterns iteratively (unlike the existing greedy rewrite driver);
- ability to change function signature;
- ability to change basic block argument types.
The latter two things required, given the existing API, to create new functions
in the same module. Eventually, this should converge with the rest of
PatternRewriter. However, we may want to keep two pass versions: "heavy" with
function/block argument conversion and "light" that only touches operations.
This pass creates new functions within a module as a means to change function
signature, then creates new blocks with converted argument types in the new
function. Then, it traverses the CFG in DFS-preorder to make sure defs are
converted before uses in the dominated blocks. The generic pass has a minimal
interface with two hooks: one to fill in the set of patterns, and another one
to convert types for functions and blocks. The patterns are defined as
separate classes that can be table-generated in the future.
The LLVM IR lowering pass partially inherits from the existing LLVM IR
translator, in particular for type conversion. It defines a conversion pattern
template, instantiated for different operations, and is a good candidate for
tablegen. The lowering does not yet support loads and stores and is not
connected to the translator as it would have broken the existing flows. Future
patches will add missing support before switching the translator in a single
patch.
PiperOrigin-RevId: 230951202
2019-01-25 12:46:53 -08:00
|
|
|
}
|
|
|
|
|
|
2019-07-20 19:05:41 -07:00
|
|
|
/// Create a default conversion pattern that rewrites the type signature of a
|
|
|
|
|
/// FuncOp.
|
|
|
|
|
namespace {
|
2019-10-17 15:18:31 -07:00
|
|
|
struct FuncOpSignatureConversion : public OpConversionPattern<FuncOp> {
|
2019-07-20 19:05:41 -07:00
|
|
|
FuncOpSignatureConversion(MLIRContext *ctx, TypeConverter &converter)
|
2019-10-17 15:18:31 -07:00
|
|
|
: OpConversionPattern(ctx), converter(converter) {}
|
2019-07-20 19:05:41 -07:00
|
|
|
|
|
|
|
|
/// Hook for derived classes to implement combined matching and rewriting.
|
|
|
|
|
PatternMatchResult
|
2019-10-17 15:18:31 -07:00
|
|
|
matchAndRewrite(FuncOp funcOp, ArrayRef<Value *> operands,
|
2019-07-20 19:05:41 -07:00
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
|
|
|
|
FunctionType type = funcOp.getType();
|
|
|
|
|
|
|
|
|
|
// Convert the original function arguments.
|
|
|
|
|
TypeConverter::SignatureConversion result(type.getNumInputs());
|
|
|
|
|
for (unsigned i = 0, e = type.getNumInputs(); i != e; ++i)
|
|
|
|
|
if (failed(converter.convertSignatureArg(i, type.getInput(i), result)))
|
|
|
|
|
return matchFailure();
|
|
|
|
|
|
|
|
|
|
// Convert the original function results.
|
|
|
|
|
SmallVector<Type, 1> convertedResults;
|
|
|
|
|
if (failed(converter.convertTypes(type.getResults(), convertedResults)))
|
|
|
|
|
return matchFailure();
|
|
|
|
|
|
|
|
|
|
// Create a new function with an updated signature.
|
|
|
|
|
auto newFuncOp = rewriter.cloneWithoutRegions(funcOp);
|
|
|
|
|
rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),
|
|
|
|
|
newFuncOp.end());
|
|
|
|
|
newFuncOp.setType(FunctionType::get(result.getConvertedTypes(),
|
|
|
|
|
convertedResults, funcOp.getContext()));
|
|
|
|
|
|
|
|
|
|
// Tell the rewriter to convert the region signature.
|
|
|
|
|
rewriter.applySignatureConversion(&newFuncOp.getBody(), result);
|
2019-10-17 15:18:31 -07:00
|
|
|
rewriter.eraseOp(funcOp);
|
2019-07-20 19:05:41 -07:00
|
|
|
return matchSuccess();
|
2019-07-17 14:45:53 -07:00
|
|
|
}
|
|
|
|
|
|
2019-07-20 19:05:41 -07:00
|
|
|
/// The type converter to use when rewriting the signature.
|
|
|
|
|
TypeConverter &converter;
|
|
|
|
|
};
|
|
|
|
|
} // end anonymous namespace
|
|
|
|
|
|
|
|
|
|
void mlir::populateFuncOpTypeConversionPattern(
|
|
|
|
|
OwningRewritePatternList &patterns, MLIRContext *ctx,
|
|
|
|
|
TypeConverter &converter) {
|
2019-08-05 18:37:56 -07:00
|
|
|
patterns.insert<FuncOpSignatureConversion>(ctx, converter);
|
2019-07-17 14:45:53 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// This function converts the type signature of the given block, by invoking
|
|
|
|
|
/// 'convertSignatureArg' for each argument. This function should return a valid
|
|
|
|
|
/// conversion for the signature on success, None otherwise.
|
|
|
|
|
auto TypeConverter::convertBlockSignature(Block *block)
|
2019-12-18 09:28:48 -08:00
|
|
|
-> Optional<SignatureConversion> {
|
2019-07-17 14:45:53 -07:00
|
|
|
SignatureConversion conversion(block->getNumArguments());
|
|
|
|
|
for (unsigned i = 0, e = block->getNumArguments(); i != e; ++i)
|
|
|
|
|
if (failed(convertSignatureArg(i, block->getArgument(i)->getType(),
|
|
|
|
|
conversion)))
|
|
|
|
|
return llvm::None;
|
|
|
|
|
return conversion;
|
|
|
|
|
}
|
|
|
|
|
|
2019-06-11 09:51:05 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
// ConversionTarget
|
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
|
|
/// Register a legality action for the given operation.
|
|
|
|
|
void ConversionTarget::setOpAction(OperationName op,
|
|
|
|
|
LegalizationAction action) {
|
2019-11-08 15:06:03 -08:00
|
|
|
legalOperations[op] = {action, /*isRecursivelyLegal=*/false};
|
2019-06-11 09:51:05 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Register a legality action for the given dialects.
|
|
|
|
|
void ConversionTarget::setDialectAction(ArrayRef<StringRef> dialectNames,
|
|
|
|
|
LegalizationAction action) {
|
|
|
|
|
for (StringRef dialect : dialectNames)
|
|
|
|
|
legalDialects[dialect] = action;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Get the legality action for the given operation.
|
|
|
|
|
auto ConversionTarget::getOpAction(OperationName op) const
|
2019-10-28 10:03:57 -07:00
|
|
|
-> Optional<LegalizationAction> {
|
|
|
|
|
Optional<LegalizationInfo> info = getOpInfo(op);
|
|
|
|
|
return info ? info->action : Optional<LegalizationAction>();
|
2019-06-11 09:51:05 -07:00
|
|
|
}
|
|
|
|
|
|
2019-10-28 10:03:57 -07:00
|
|
|
/// If the given operation instance is legal on this target, a structure
|
|
|
|
|
/// containing legality information is returned. If the operation is not legal,
|
|
|
|
|
/// None is returned.
|
|
|
|
|
auto ConversionTarget::isLegal(Operation *op) const
|
|
|
|
|
-> Optional<LegalOpDetails> {
|
|
|
|
|
Optional<LegalizationInfo> info = getOpInfo(op->getName());
|
|
|
|
|
if (!info)
|
|
|
|
|
return llvm::None;
|
|
|
|
|
|
|
|
|
|
// Returns true if this operation instance is known to be legal.
|
|
|
|
|
auto isOpLegal = [&] {
|
|
|
|
|
// Handle dynamic legality.
|
|
|
|
|
if (info->action == LegalizationAction::Dynamic) {
|
|
|
|
|
// Check for callbacks on the operation or dialect.
|
|
|
|
|
auto opFn = opLegalityFns.find(op->getName());
|
|
|
|
|
if (opFn != opLegalityFns.end())
|
|
|
|
|
return opFn->second(op);
|
|
|
|
|
auto dialectFn = dialectLegalityFns.find(op->getName().getDialect());
|
|
|
|
|
if (dialectFn != dialectLegalityFns.end())
|
|
|
|
|
return dialectFn->second(op);
|
|
|
|
|
|
|
|
|
|
// Otherwise, invoke the hook on the derived instance.
|
|
|
|
|
return isDynamicallyLegal(op);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Otherwise, the operation is only legal if it was marked 'Legal'.
|
|
|
|
|
return info->action == LegalizationAction::Legal;
|
|
|
|
|
};
|
|
|
|
|
if (!isOpLegal())
|
|
|
|
|
return llvm::None;
|
2019-07-18 18:20:03 -07:00
|
|
|
|
2019-10-28 10:03:57 -07:00
|
|
|
// This operation is legal, compute any additional legality information.
|
|
|
|
|
LegalOpDetails legalityDetails;
|
|
|
|
|
|
|
|
|
|
if (info->isRecursivelyLegal) {
|
|
|
|
|
auto legalityFnIt = opRecursiveLegalityFns.find(op->getName());
|
|
|
|
|
if (legalityFnIt != opRecursiveLegalityFns.end())
|
|
|
|
|
legalityDetails.isRecursivelyLegal = legalityFnIt->second(op);
|
|
|
|
|
else
|
|
|
|
|
legalityDetails.isRecursivelyLegal = true;
|
|
|
|
|
}
|
|
|
|
|
return legalityDetails;
|
2019-07-18 18:20:03 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Set the dynamic legality callback for the given operation.
|
|
|
|
|
void ConversionTarget::setLegalityCallback(
|
|
|
|
|
OperationName name, const DynamicLegalityCallbackFn &callback) {
|
|
|
|
|
assert(callback && "expected valid legality callback");
|
|
|
|
|
opLegalityFns[name] = callback;
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-28 10:03:57 -07:00
|
|
|
/// Set the recursive legality callback for the given operation and mark the
|
|
|
|
|
/// operation as recursively legal.
|
|
|
|
|
void ConversionTarget::markOpRecursivelyLegal(
|
|
|
|
|
OperationName name, const DynamicLegalityCallbackFn &callback) {
|
|
|
|
|
auto infoIt = legalOperations.find(name);
|
|
|
|
|
assert(infoIt != legalOperations.end() &&
|
|
|
|
|
infoIt->second.action != LegalizationAction::Illegal &&
|
|
|
|
|
"expected operation to already be marked as legal");
|
|
|
|
|
infoIt->second.isRecursivelyLegal = true;
|
|
|
|
|
if (callback)
|
|
|
|
|
opRecursiveLegalityFns[name] = callback;
|
|
|
|
|
else
|
|
|
|
|
opRecursiveLegalityFns.erase(name);
|
|
|
|
|
}
|
|
|
|
|
|
2019-07-18 18:20:03 -07:00
|
|
|
/// Set the dynamic legality callback for the given dialects.
|
|
|
|
|
void ConversionTarget::setLegalityCallback(
|
|
|
|
|
ArrayRef<StringRef> dialects, const DynamicLegalityCallbackFn &callback) {
|
|
|
|
|
assert(callback && "expected valid legality callback");
|
|
|
|
|
for (StringRef dialect : dialects)
|
|
|
|
|
dialectLegalityFns[dialect] = callback;
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-28 10:03:57 -07:00
|
|
|
/// Get the legalization information for the given operation.
|
|
|
|
|
auto ConversionTarget::getOpInfo(OperationName op) const
|
|
|
|
|
-> Optional<LegalizationInfo> {
|
|
|
|
|
// Check for info for this specific operation.
|
|
|
|
|
auto it = legalOperations.find(op);
|
|
|
|
|
if (it != legalOperations.end())
|
|
|
|
|
return it->second;
|
|
|
|
|
// Otherwise, default to checking on the parent dialect.
|
|
|
|
|
auto dialectIt = legalDialects.find(op.getDialect());
|
|
|
|
|
if (dialectIt != legalDialects.end())
|
|
|
|
|
return LegalizationInfo{dialectIt->second, /*isRecursivelyLegal=*/false};
|
|
|
|
|
return llvm::None;
|
|
|
|
|
}
|
|
|
|
|
|
2019-05-23 09:23:33 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
2019-07-16 11:57:45 -07:00
|
|
|
// Op Conversion Entry Points
|
2019-05-23 09:23:33 -07:00
|
|
|
//===----------------------------------------------------------------------===//
|
Generic dialect conversion pass exercised by LLVM IR lowering
This commit introduces a generic dialect conversion/lowering/legalization pass
and illustrates it on StandardOps->LLVMIR conversion.
It partially reuses the PatternRewriter infrastructure and adds the following
functionality:
- an actual pass;
- non-default pattern constructors;
- one-to-many rewrites;
- rewriting terminators with successors;
- not applying patterns iteratively (unlike the existing greedy rewrite driver);
- ability to change function signature;
- ability to change basic block argument types.
The latter two things required, given the existing API, to create new functions
in the same module. Eventually, this should converge with the rest of
PatternRewriter. However, we may want to keep two pass versions: "heavy" with
function/block argument conversion and "light" that only touches operations.
This pass creates new functions within a module as a means to change function
signature, then creates new blocks with converted argument types in the new
function. Then, it traverses the CFG in DFS-preorder to make sure defs are
converted before uses in the dominated blocks. The generic pass has a minimal
interface with two hooks: one to fill in the set of patterns, and another one
to convert types for functions and blocks. The patterns are defined as
separate classes that can be table-generated in the future.
The LLVM IR lowering pass partially inherits from the existing LLVM IR
translator, in particular for type conversion. It defines a conversion pattern
template, instantiated for different operations, and is a good candidate for
tablegen. The lowering does not yet support loads and stores and is not
connected to the translator as it would have broken the existing flows. Future
patches will add missing support before switching the translator in a single
patch.
PiperOrigin-RevId: 230951202
2019-01-25 12:46:53 -08:00
|
|
|
|
2019-07-16 11:57:45 -07:00
|
|
|
/// Apply a partial conversion on the given operations, and all nested
|
|
|
|
|
/// operations. This method converts as many operations to the target as
|
|
|
|
|
/// possible, ignoring operations that failed to legalize.
|
2019-08-11 18:33:42 -07:00
|
|
|
LogicalResult mlir::applyPartialConversion(
|
|
|
|
|
ArrayRef<Operation *> ops, ConversionTarget &target,
|
|
|
|
|
const OwningRewritePatternList &patterns, TypeConverter *converter) {
|
2019-07-17 14:45:53 -07:00
|
|
|
OperationConverter opConverter(target, patterns, OpConversionMode::Partial);
|
|
|
|
|
return opConverter.convertOperations(ops, converter);
|
2019-07-16 11:57:45 -07:00
|
|
|
}
|
2019-08-11 18:33:42 -07:00
|
|
|
LogicalResult
|
|
|
|
|
mlir::applyPartialConversion(Operation *op, ConversionTarget &target,
|
|
|
|
|
const OwningRewritePatternList &patterns,
|
|
|
|
|
TypeConverter *converter) {
|
2019-08-09 17:20:02 -07:00
|
|
|
return applyPartialConversion(llvm::makeArrayRef(op), target, patterns,
|
|
|
|
|
converter);
|
2019-07-16 11:57:45 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Apply a complete conversion on the given operations, and all nested
|
|
|
|
|
/// operations. This method will return failure if the conversion of any
|
|
|
|
|
/// operation fails.
|
2019-08-11 18:33:42 -07:00
|
|
|
LogicalResult
|
|
|
|
|
mlir::applyFullConversion(ArrayRef<Operation *> ops, ConversionTarget &target,
|
|
|
|
|
const OwningRewritePatternList &patterns,
|
|
|
|
|
TypeConverter *converter) {
|
2019-07-17 14:45:53 -07:00
|
|
|
OperationConverter opConverter(target, patterns, OpConversionMode::Full);
|
|
|
|
|
return opConverter.convertOperations(ops, converter);
|
2019-06-04 11:35:21 -07:00
|
|
|
}
|
2019-08-11 18:33:42 -07:00
|
|
|
LogicalResult
|
|
|
|
|
mlir::applyFullConversion(Operation *op, ConversionTarget &target,
|
|
|
|
|
const OwningRewritePatternList &patterns,
|
|
|
|
|
TypeConverter *converter) {
|
2019-08-09 17:20:02 -07:00
|
|
|
return applyFullConversion(llvm::makeArrayRef(op), target, patterns,
|
|
|
|
|
converter);
|
2019-05-23 09:23:33 -07:00
|
|
|
}
|
2019-07-25 11:30:41 -07:00
|
|
|
|
|
|
|
|
/// Apply an analysis conversion on the given operations, and all nested
|
|
|
|
|
/// operations. This method analyzes which operations would be successfully
|
|
|
|
|
/// converted to the target if a conversion was applied. All operations that
|
|
|
|
|
/// were found to be legalizable to the given 'target' are placed within the
|
|
|
|
|
/// provided 'convertedOps' set; note that no actual rewrites are applied to the
|
|
|
|
|
/// operations on success and only pre-existing operations are added to the set.
|
2019-08-11 18:33:42 -07:00
|
|
|
LogicalResult mlir::applyAnalysisConversion(
|
|
|
|
|
ArrayRef<Operation *> ops, ConversionTarget &target,
|
|
|
|
|
const OwningRewritePatternList &patterns,
|
|
|
|
|
DenseSet<Operation *> &convertedOps, TypeConverter *converter) {
|
2019-07-25 11:30:41 -07:00
|
|
|
OperationConverter opConverter(target, patterns, OpConversionMode::Analysis,
|
|
|
|
|
&convertedOps);
|
|
|
|
|
return opConverter.convertOperations(ops, converter);
|
|
|
|
|
}
|
2019-08-11 18:33:42 -07:00
|
|
|
LogicalResult
|
|
|
|
|
mlir::applyAnalysisConversion(Operation *op, ConversionTarget &target,
|
|
|
|
|
const OwningRewritePatternList &patterns,
|
|
|
|
|
DenseSet<Operation *> &convertedOps,
|
|
|
|
|
TypeConverter *converter) {
|
2019-08-09 17:20:02 -07:00
|
|
|
return applyAnalysisConversion(llvm::makeArrayRef(op), target, patterns,
|
|
|
|
|
convertedOps, converter);
|
2019-07-25 11:30:41 -07:00
|
|
|
}
|