1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
|
//====----- OutlineShapeComputation.cpp -----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/Shape/Analysis/ShapeMappingAnalysis.h"
#include "mlir/Dialect/Shape/IR/Shape.h"
#include "mlir/Dialect/Shape/Transforms/Passes.h"
#include "mlir/Dialect/Tensor/IR/Tensor.h"
#include "mlir/IR/IRMapping.h"
#include "mlir/IR/Matchers.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/Support/Debug.h"
#include <queue>
#include <unordered_set>
#include <vector>
namespace mlir {
#define GEN_PASS_DEF_OUTLINESHAPECOMPUTATION
#include "mlir/Dialect/Shape/Transforms/Passes.h.inc"
} // namespace mlir
#define DEBUG_TYPE "outline-shape-computation"
using namespace mlir;
namespace {
// A Value is an input of the cluster if it is an operand of an operation in the
// cluster and its defining operation is not in the cluster.
SmallVector<Value, 4>
getInputsOfCluster(const llvm::SmallVector<Operation *, 8> &cluster) {
SmallVector<Value, 4> inputs;
llvm::SmallDenseSet<Value> inputSet;
llvm::SmallDenseSet<Operation *> opSet;
for (Operation *op : cluster) {
bool inserted = opSet.insert(op).second;
(void)inserted;
assert(inserted && "cluster contains duplicate operations");
}
for (Operation *op : cluster) {
for (Value operand : op->getOperands()) {
Operation *operandOp = operand.getDefiningOp();
if (opSet.find(operandOp) != opSet.end()) {
// Skip if defining op is in the cluster.
continue;
}
if (inputSet.insert(operand).second)
inputs.push_back(operand);
}
}
return inputs;
}
// Create a shape.func representing the shape computation for `shape`.
std::pair<shape::FuncOp, SmallVector<Value>>
createFuncFromCluster(OpBuilder &b, const SmallVector<Operation *, 8> &cluster,
Value shape, StringRef fnName, Location loc) {
SmallVector<Value, 4> inputs = getInputsOfCluster(cluster);
auto fnType =
cluster.empty()
? b.getFunctionType(shape.getType(), shape.getType())
: b.getFunctionType(ValueRange(inputs).getTypes(), shape.getType());
shape::FuncOp fnOp = b.create<shape::FuncOp>(loc, fnName, fnType);
Block *block = fnOp.addEntryBlock();
b.setInsertionPoint(block, block->end());
IRMapping bvm;
if (cluster.empty()) {
bvm.map(shape, fnOp.getArgument(0));
} else {
for (auto inputAndArg : llvm::zip(inputs, fnOp.getArguments()))
bvm.map(std::get<0>(inputAndArg), std::get<1>(inputAndArg));
}
for (Operation *op : cluster)
b.clone(*op, bvm);
llvm::SmallVector<Value, 4> fnReturns;
fnReturns.push_back(bvm.lookupOrDefault(shape));
b.create<shape::ReturnOp>(loc, fnReturns);
fnOp.setPrivate();
return std::make_pair(fnOp, inputs);
}
// The operations in the cluster might be unsorted, which could be inconvenient
// when creating shape.func op.
DenseMap<Value, SmallVector<Operation *, 8>>
getOrderedClusters(const DenseMap<Value, DenseSet<Operation *>> &clusters,
func::FuncOp funcOp) {
// Compute all clusters that each operation is in
DenseMap<Operation *, SmallVector<Value>> op2Shapes;
for (const auto &it : clusters) {
Value shape = it.first;
const DenseSet<Operation *> &cluster = it.second;
for (Operation *cOp : cluster)
op2Shapes[cOp].push_back(shape);
}
// Iterate through all operations in order. Get all the clusters `cOp` belongs
// to and construct the new ordered cluster as it traverses.
DenseMap<Value, SmallVector<Operation *, 8>> orderedClusters;
funcOp.walk([&](Operation *op) {
auto it = op2Shapes.find(op);
if (it != op2Shapes.end()) {
Operation *cOp = it->first;
for (Value shape : it->second)
orderedClusters[shape].push_back(cOp);
}
});
return orderedClusters;
}
void constructShapeFunc(
const std::vector<shape::WithOp> &allWithOps, MLIRContext *context,
DenseMap<Value, SmallVector<Operation *, 8>> &clusters,
SymbolTable &symbolTable,
DenseMap<Value, shape::ShapeMappingValue> &dynShape2ShapeFunc,
func::FuncOp funcOp, shape::ShapeMappingAnalysis &shapeMappingAnalysis) {
std::string shapeCalculationNamePrefix = "shape_cal_";
int shapeCalculationNameIdx = 0;
OpBuilder builder(context);
// Construct a shape function
for (shape::WithOp withOp : allWithOps) {
Value value = withOp.getOperand();
Value shape = withOp.getShape();
RankedTensorType rankedType = dyn_cast<RankedTensorType>(value.getType());
if (rankedType == nullptr)
continue;
const SmallVector<Operation *, 8> &cluster = clusters[shape];
shape::ShapeMappingValue shapeMappingValue;
auto it = dynShape2ShapeFunc.find(shape);
if (it == dynShape2ShapeFunc.end()) {
std::string name = shapeCalculationNamePrefix +
std::to_string(shapeCalculationNameIdx++);
Location loc = value.getLoc();
builder.setInsertionPointAfter(funcOp);
auto pair = createFuncFromCluster(builder, cluster, shape, name, loc);
const SmallVector<Value> &inputs = pair.second;
shape::FuncOp shapeFuncOp = pair.first;
StringAttr insertedName = symbolTable.insert(shapeFuncOp);
auto symbol = FlatSymbolRefAttr::get(context, insertedName);
shapeMappingValue.funcSymbol = symbol;
shapeMappingValue.inputs = inputs;
} else {
shapeMappingValue = it->second;
}
dynShape2ShapeFunc[shape] = shapeMappingValue;
shapeMappingAnalysis.shapeMapping.insert(
std::make_pair(value, shapeMappingValue));
}
}
struct OutlineShapeComputationPass
: public impl::OutlineShapeComputationBase<OutlineShapeComputationPass> {
void runOnOperation() override;
private:
bool calOnlyUsedByWithShapesRecursively(Operation *op, Value prevOutput);
void getClusterFromValue(Value shape,
DenseMap<Value, DenseSet<Operation *>> &clusters);
DenseMap<Value, SmallVector<Operation *, 8>>
constructClustersForEachShape(const std::vector<shape::WithOp> &allWithOps,
func::FuncOp funcOp);
DenseSet<Operation *> onlyUsedByWithShapes;
};
class TensorDimOpRewriter : public OpRewritePattern<tensor::DimOp> {
using OpRewritePattern<tensor::DimOp>::OpRewritePattern;
LogicalResult matchAndRewrite(tensor::DimOp op,
PatternRewriter &rewriter) const override {
auto shapeOf =
rewriter.create<shape::ShapeOfOp>(op.getLoc(), op.getSource());
rewriter.replaceOpWithNewOp<shape::GetExtentOp>(op, op.getType(), shapeOf,
op.getIndex());
return success();
}
};
void OutlineShapeComputationPass::runOnOperation() {
ModuleOp moduleOp = getOperation();
SymbolTable symbolTable(moduleOp);
DenseMap<Value, shape::ShapeMappingValue> dynShape2ShapeFunc;
auto &shapeMappingAnalysis = getAnalysis<shape::ShapeMappingAnalysis>();
// TODO: This is as we populate this analysis during a pass that mutates. This
// pass currently requires 1 single module being compiled.
shapeMappingAnalysis.shapeMapping.clear();
markAnalysesPreserved<shape::ShapeMappingAnalysis>();
moduleOp.walk([&](func::FuncOp funcOp) {
MLIRContext *context = funcOp.getContext();
RewritePatternSet prevPatterns(context);
prevPatterns.insert<TensorDimOpRewriter>(context);
if (failed(applyPatternsAndFoldGreedily(funcOp, std::move(prevPatterns))))
return signalPassFailure();
// initialize class member `onlyUsedByWithShapes`
onlyUsedByWithShapes.clear();
funcOp.walk([&](Operation *op) {
calOnlyUsedByWithShapesRecursively(op, /*prevOutput=*/nullptr);
});
LLVM_DEBUG({
llvm::dbgs() << "onlyUsedByWithShapes table: \n";
for (auto it : onlyUsedByWithShapes)
llvm::dbgs() << *it << "\n";
});
// collect all the shape.with_shape ops.
std::vector<shape::WithOp> allWithOps;
funcOp.walk([&](shape::WithOp withOp) { allWithOps.push_back(withOp); });
DenseMap<Value, SmallVector<Operation *, 8>> clusters =
constructClustersForEachShape(allWithOps, funcOp);
constructShapeFunc(allWithOps, context, clusters, symbolTable,
dynShape2ShapeFunc, funcOp, shapeMappingAnalysis);
for (shape::WithOp withOp : allWithOps) {
Value value = withOp.getOperand();
for (Operation *user :
llvm::make_early_inc_range(withOp.getResult().getUsers())) {
if (auto valueOf = llvm::dyn_cast<shape::ValueOfOp>(user)) {
// For pattern like
// %1 = shape.with_shape %arg1, %0
// %2 = shape.value_of %1
// because shape.value doesn't care the shape, the shape.with_shape is
// redundant.
// If type of %arg1 and %2 has same type, just
// replaced %2 with %arg1.
// If type of %arg1 has different type like !shape.value_shape,
// transform into
// %2 = shape.value_of %arg1
if (valueOf.getType() == value.getType())
valueOf.replaceAllUsesWith(value);
else
valueOf.setOperand(value);
}
}
}
// Apply patterns, note this also performs DCE.
if (failed(applyPatternsAndFoldGreedily(funcOp, {})))
return signalPassFailure();
});
}
DenseMap<Value, SmallVector<Operation *, 8>>
OutlineShapeComputationPass::constructClustersForEachShape(
const std::vector<shape::WithOp> &allWithOps, func::FuncOp funcOp) {
DenseMap<Value, DenseSet<Operation *>> clusters;
for (shape::WithOp withOp : allWithOps) {
Value shape = withOp.getShape();
if (clusters.count(shape) == 0)
getClusterFromValue(shape, clusters);
}
return getOrderedClusters(clusters, funcOp);
}
// The output of a cluster is the `shape`, and the inputs are the outputs of
// operations who are not in `onlyUsedByWithShapes`
void OutlineShapeComputationPass::getClusterFromValue(
Value shape, DenseMap<Value, DenseSet<Operation *>> &clusters) {
DenseSet<Operation *> cluster;
DenseSet<Operation *> visited;
std::queue<Operation *> queue;
// defOp == nullptr means shape is the argument of the func op
if (Operation *defOp = shape.getDefiningOp()) {
visited.insert(defOp);
queue.push(defOp);
}
while (!queue.empty()) {
Operation *op = queue.front();
queue.pop();
if (onlyUsedByWithShapes.contains(op)) {
cluster.insert(op);
for (Value inp : op->getOperands()) {
Operation *inpDefOp = inp.getDefiningOp();
if (nullptr != inpDefOp && !visited.contains(inpDefOp)) {
visited.insert(inpDefOp);
queue.push(inpDefOp);
}
}
}
}
clusters[shape] = std::move(cluster);
}
// Returns whether `op` is a shape.with_shape, or all the users' of `op`
// eventually point to the shape operand of shape.with_shape ops
bool OutlineShapeComputationPass::calOnlyUsedByWithShapesRecursively(
Operation *op, Value prevOutput) {
if (onlyUsedByWithShapes.contains(op))
return true;
if (auto withOp = llvm::dyn_cast<shape::WithOp>(op))
return withOp.getShape() == prevOutput;
if (op->use_empty())
return false;
for (Value oup : op->getResults())
for (Operation *user : oup.getUsers())
if (!calOnlyUsedByWithShapesRecursively(user, oup))
return false;
onlyUsedByWithShapes.insert(op);
return true;
}
} // namespace
std::unique_ptr<OperationPass<ModuleOp>>
mlir::createOutlineShapeComputationPass() {
return std::make_unique<OutlineShapeComputationPass>();
}
|