1 //===- Vectorization.cpp - Implementation of linalg Vectorization ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the linalg dialect Vectorization transformations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "mlir/Dialect/Linalg/Analysis/DependenceAnalysis.h" 14 #include "mlir/Dialect/Linalg/IR/LinalgOps.h" 15 #include "mlir/Dialect/Linalg/Transforms/Transforms.h" 16 #include "mlir/Dialect/Linalg/Utils/Utils.h" 17 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h" 18 #include "mlir/Dialect/Utils/StructuredOpsUtils.h" 19 #include "mlir/Dialect/Vector/EDSC/Intrinsics.h" 20 #include "mlir/Dialect/Vector/VectorOps.h" 21 #include "mlir/IR/AffineExpr.h" 22 #include "mlir/IR/Matchers.h" 23 #include "mlir/IR/PatternMatch.h" 24 #include "mlir/Pass/Pass.h" 25 #include "mlir/Support/LLVM.h" 26 #include "mlir/Transforms/RegionUtils.h" 27 #include "llvm/ADT/ScopeExit.h" 28 #include "llvm/Support/Debug.h" 29 #include "llvm/Support/raw_ostream.h" 30 #include <type_traits> 31 32 using namespace mlir; 33 using namespace mlir::edsc; 34 using namespace mlir::edsc::intrinsics; 35 using namespace mlir::linalg; 36 37 using llvm::dbgs; 38 39 #define DEBUG_TYPE "linalg-vectorization" 40 41 /// Return the unique instance of OpType in `block` if it is indeed unique. 42 /// Return null if none or more than 1 instances exist. 43 template <typename OpType> 44 static OpType getSingleOpOfType(Block &block) { 45 OpType res; 46 block.walk([&](OpType op) { 47 if (res) { 48 res = nullptr; 49 return WalkResult::interrupt(); 50 } 51 res = op; 52 return WalkResult::advance(); 53 }); 54 return res; 55 } 56 57 /// Helper data structure to represent the result of vectorization. 58 /// In certain specific cases, like terminators, we do not want to propagate/ 59 enum VectorizationStatus { 60 /// Op failed to vectorize. 61 Failure = 0, 62 /// Op vectorized and custom function took care of replacement logic 63 NoReplace, 64 /// Op vectorized into a new Op whose results will replace original Op's 65 /// results. 66 NewOp 67 // TODO: support values if Op vectorized to Many-Ops whose results we need to 68 // aggregate for replacement. 69 }; 70 struct VectorizationResult { 71 /// Return status from vectorizing the current op. 72 enum VectorizationStatus status = VectorizationStatus::Failure; 73 /// New vectorized operation to replace the current op. 74 /// Replacement behavior is specified by `status`. 75 Operation *newOp; 76 }; 77 78 /// Return a vector type of the same shape and element type as the (assumed) 79 /// ShapedType of `v`. 80 static VectorType extractVectorTypeFromShapedValue(Value v) { 81 auto st = v.getType().cast<ShapedType>(); 82 if (st.isa<MemRefType>() && st.getShape().empty()) 83 return VectorType(); 84 return VectorType::get(st.getShape(), st.getElementType()); 85 } 86 87 /// Build a vector.transfer_read from `source` at indices set to all `0`. 88 /// If source has rank zero, build an std.load. 89 /// Return the produced value. 90 static Value buildVectorRead(OpBuilder &builder, Value source) { 91 edsc::ScopedContext scope(builder); 92 auto shapedType = source.getType().cast<ShapedType>(); 93 if (VectorType vectorType = extractVectorTypeFromShapedValue(source)) { 94 SmallVector<Value> indices(shapedType.getRank(), std_constant_index(0)); 95 return vector_transfer_read(vectorType, source, indices); 96 } 97 return std_load(source); 98 } 99 100 /// Build a vector.transfer_write of `value` into `dest` at indices set to all 101 /// `0`. If `dest` has null rank, build an std.store. 102 /// Return the produced value or null if no value is produced. 103 static Value buildVectorWrite(OpBuilder &builder, Value value, Value dest) { 104 edsc::ScopedContext scope(builder); 105 Operation *write; 106 auto shapedType = dest.getType().cast<ShapedType>(); 107 if (VectorType vectorType = extractVectorTypeFromShapedValue(dest)) { 108 SmallVector<Value> indices(shapedType.getRank(), std_constant_index(0)); 109 if (vectorType != value.getType()) 110 value = vector_broadcast(vectorType, value); 111 write = vector_transfer_write(value, dest, indices); 112 } else { 113 write = std_store(value, dest); 114 } 115 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: vectorized op: " << *write); 116 if (!write->getResults().empty()) 117 return write->getResult(0); 118 return Value(); 119 } 120 121 /// If value of assumed VectorType has a shape different than `shape`, buil and 122 /// return a new vector.broadcast to `shape`. 123 /// Otherwise, just return value. 124 static Value broadcastIfNeeded(OpBuilder &builder, Value value, 125 ArrayRef<int64_t> shape) { 126 auto vecType = value.getType().dyn_cast<VectorType>(); 127 if (shape.empty() || (vecType != nullptr && vecType.getShape() == shape)) 128 return value; 129 auto newVecType = VectorType::get(shape, vecType ? vecType.getElementType() 130 : value.getType()); 131 return builder.create<vector::BroadcastOp>( 132 builder.getInsertionPoint()->getLoc(), newVecType, value); 133 } 134 135 // Custom vectorization function type. Produce a vector form of Operation* 136 // assuming all its vectorized operands are already in the BlockAndValueMapping. 137 // Return nullptr if the Operation cannot be vectorized. 138 using CustomVectorizationHook = std::function<VectorizationResult( 139 Operation *, const BlockAndValueMapping &)>; 140 141 /// Helper function to vectorize the terminator of a `linalgOp`. New result 142 /// vector values are appended to `results`. 143 /// Return VectorizationStatus::NoReplace to signal the vectorization algorithm 144 /// that it should not try to map produced operations: this is the purpose of 145 /// the `results` argument to capture such values and make them available for 146 /// RAUW to the vectorization algorithm. 147 /// This function is meant to be used as a CustomVectorizationHook. 148 static VectorizationResult 149 vectorizeLinalgYield(OpBuilder &builder, Operation *op, 150 const BlockAndValueMapping &bvm, LinalgOp linalgOp, 151 SmallVectorImpl<Value> &results) { 152 auto yieldOp = dyn_cast<linalg::YieldOp>(op); 153 if (!yieldOp) 154 return VectorizationResult{VectorizationStatus::Failure, nullptr}; 155 for (auto outputs : llvm::enumerate(yieldOp.values())) { 156 // TODO: Scan for an opportunity for reuse. 157 // TODO: use a map. 158 Value vectorValue = bvm.lookup(outputs.value()); 159 Value result = buildVectorWrite(builder, vectorValue, 160 linalgOp.getOutput(outputs.index())); 161 if (result) 162 results.push_back(result); 163 } 164 return VectorizationResult{VectorizationStatus::NoReplace, nullptr}; 165 } 166 167 /// Generic vectorization for a single operation `op`, given already vectorized 168 /// operands carried by `bvm`. Vectorization occurs as follows: 169 /// 1. Try to apply any of the `customVectorizationHooks` and return its 170 /// result on success. 171 /// 2. Clone any constant in the current scope without vectorization: each 172 /// consumer of the constant will later determine the shape to which the 173 /// constant needs to be broadcast to. 174 /// 3. Fail on any remaining non `ElementwiseMappable` op. It is the purpose 175 /// of the `customVectorizationHooks` to cover such cases. 176 /// 4. Clone `op` in vector form to a vector of shape prescribed by the first 177 /// operand of maximal rank. Other operands have smaller rank and are 178 /// broadcast accordingly. It is assumed this broadcast is always legal, 179 /// otherwise, it means one of the `customVectorizationHooks` is incorrect. 180 /// 181 /// This function assumes all operands of `op` have been vectorized and are in 182 /// the `bvm` mapping. As a consequence, this function is meant to be called on 183 /// a topologically-sorted list of ops. 184 /// This function does not update `bvm` but returns a VectorizationStatus that 185 /// instructs the caller what `bvm` update needs to occur. 186 static VectorizationResult 187 vectorizeOneOp(OpBuilder &builder, Operation *op, 188 const BlockAndValueMapping &bvm, 189 ArrayRef<CustomVectorizationHook> customVectorizationHooks) { 190 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: vectorize op " << *op); 191 192 // 1. Try to apply any CustomVectorizationHook. 193 if (!customVectorizationHooks.empty()) { 194 for (auto &customFunc : customVectorizationHooks) { 195 VectorizationResult result = customFunc(op, bvm); 196 if (result.status == VectorizationStatus::Failure) 197 continue; 198 return result; 199 } 200 } 201 202 // 2. Constant ops don't get vectorized but rather broadcasted at their users. 203 // Clone so that the constant is not confined to the linalgOp block . 204 if (isa<ConstantOp>(op)) 205 return VectorizationResult{VectorizationStatus::NewOp, builder.clone(*op)}; 206 207 // 3. Only ElementwiseMappable are allowed in the generic vectorization. 208 if (!OpTrait::hasElementwiseMappableTraits(op)) 209 return VectorizationResult{VectorizationStatus::Failure, nullptr}; 210 211 // 4. Generic vectorization path for ElementwiseMappable ops. 212 // a. first get the first max ranked shape. 213 SmallVector<int64_t, 4> firstMaxRankedShape; 214 for (Value operand : op->getOperands()) { 215 auto vt = bvm.lookup(operand).getType().dyn_cast<VectorType>(); 216 if (vt && firstMaxRankedShape.size() < vt.getShape().size()) 217 firstMaxRankedShape.assign(vt.getShape().begin(), vt.getShape().end()); 218 } 219 // b. broadcast each op if needed. 220 auto vectorizedOperands = llvm::map_range(op->getOperands(), [&](Value v) { 221 return firstMaxRankedShape.empty() 222 ? bvm.lookup(v) 223 : broadcastIfNeeded(builder, bvm.lookup(v), firstMaxRankedShape); 224 }); 225 // c. for elementwise, the result is the vector with the firstMaxRankedShape 226 auto returnTypes = llvm::map_range(op->getResultTypes(), [&](Type t) { 227 return firstMaxRankedShape.empty() 228 ? t 229 : VectorType::get(firstMaxRankedShape, t); 230 }); 231 232 // Build and return the new op. 233 OperationState state(op->getLoc(), op->getName()); 234 state.addAttributes(op->getAttrs()); 235 state.addOperands(llvm::to_vector<4>(vectorizedOperands)); 236 state.addTypes(llvm::to_vector<4>(returnTypes)); 237 return VectorizationResult{VectorizationStatus::NewOp, 238 builder.createOperation(state)}; 239 } 240 241 /// Generic vectorization function that rewrites the body of a `linalgOp` into 242 /// vector form. Generic vectorization proceeds as follows: 243 /// 1. The region for the linalg op is created if necessary. 244 /// 2. Values defined above the region are mapped to themselves and will be 245 /// broadcasted on a per-need basis by their consumers. 246 /// 3. Each region argument is vectorized into a vector.transfer_read (or 0-d 247 /// load). 248 /// TODO: Reuse opportunities for RAR dependencies. 249 /// 4. Register CustomVectorizationHook for YieldOp to capture the results. 250 /// 5. Iteratively call vectorizeOneOp on the region operations. 251 static Optional<VectorizedLinalgOp> vectorizeAsLinalgGeneric( 252 OpBuilder &builder, LinalgOp linalgOp, 253 ArrayRef<CustomVectorizationHook> customVectorizationHooks = {}) { 254 // 1. Certain Linalg ops do not have a region but only a region builder. 255 // If so, build the region so we can vectorize. 256 std::unique_ptr<Region> owningRegion; 257 Region *region; 258 if (linalgOp->getNumRegions() > 0) { 259 region = &linalgOp->getRegion(0); 260 } else { 261 // RAII avoid remaining in block. 262 OpBuilder::InsertionGuard g(builder); 263 owningRegion = std::make_unique<Region>(); 264 region = owningRegion.get(); 265 Block *block = builder.createBlock(region); 266 auto elementTypes = llvm::to_vector<4>( 267 llvm::map_range(linalgOp.getShapedOperandTypes(), 268 [](ShapedType t) { return t.getElementType(); })); 269 block->addArguments(elementTypes); 270 linalgOp.getRegionBuilder()(*block, /*captures=*/{}); 271 } 272 Block *block = ®ion->front(); 273 274 BlockAndValueMapping bvm; 275 // 2. Values defined above the region can only be broadcast for now. Make them 276 // map to themselves. 277 llvm::SetVector<Value> valuesSet; 278 mlir::getUsedValuesDefinedAbove(*region, valuesSet); 279 bvm.map(valuesSet.getArrayRef(), valuesSet.getArrayRef()); 280 281 // 3. Turn all BBArgs into vector.transfer_read / load. 282 SmallVector<AffineMap> indexings; 283 for (auto bbarg : block->getArguments()) { 284 Value vectorArg = linalgOp.getShapedOperand(bbarg.getArgNumber()); 285 Value vectorRead = buildVectorRead(builder, vectorArg); 286 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vectorized bbarg(" 287 << bbarg.getArgNumber() << "): " << vectorRead); 288 bvm.map(bbarg, vectorRead); 289 bvm.map(vectorArg, vectorRead); 290 } 291 292 // 4. Register CustomVectorizationHook for yieldOp. 293 SmallVector<Value> results; 294 CustomVectorizationHook vectorizeYield = 295 [&](Operation *op, 296 const BlockAndValueMapping &bvm) -> VectorizationResult { 297 return vectorizeLinalgYield(builder, op, bvm, linalgOp, results); 298 }; 299 // Append the vectorizeYield hook. 300 auto hooks = llvm::to_vector<4>(customVectorizationHooks); 301 hooks.push_back(vectorizeYield); 302 303 // 5. Iteratively call `vectorizeOneOp` to each op in the slice. 304 for (Operation &op : block->getOperations()) { 305 VectorizationResult result = vectorizeOneOp(builder, &op, bvm, hooks); 306 if (result.status == VectorizationStatus::Failure) { 307 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: failed to vectorize: " << op); 308 return llvm::None; 309 } 310 if (result.status == VectorizationStatus::NewOp) { 311 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: new vector op: " 312 << *result.newOp;); 313 bvm.map(op.getResults(), result.newOp->getResults()); 314 } 315 } 316 317 return VectorizedLinalgOp{{results}}; 318 } 319 320 /// Detect whether `r` has only ConstantOp, ElementwiseMappable and YieldOp. 321 static bool hasOnlyScalarElementwiseOp(Region &r) { 322 if (!llvm::hasSingleElement(r)) 323 return false; 324 for (Operation &op : r.front()) { 325 if (!(isa<ConstantOp, linalg::YieldOp>(op) || 326 OpTrait::hasElementwiseMappableTraits(&op)) || 327 llvm::any_of(op.getResultTypes(), 328 [](Type type) { return !type.isIntOrIndexOrFloat(); })) 329 return false; 330 } 331 return true; 332 } 333 334 // Return true if the op is an element-wise linalg op. 335 static bool isElementwise(Operation *op) { 336 auto linalgOp = dyn_cast<linalg::LinalgOp>(op); 337 if (!linalgOp) 338 return false; 339 if (linalgOp.getNumLoops() != linalgOp.getNumParallelLoops()) 340 return false; 341 // TODO: relax the restrictions on indexing map. 342 for (unsigned i = 0, e = linalgOp.getNumOutputs(); i < e; i++) { 343 if (!linalgOp.getOutputIndexingMap(i).isIdentity()) 344 return false; 345 } 346 // Currently bound the input indexing map to minor identity as other 347 // permutations might require adding transpose ops to convert the vector read 348 // to the right shape. 349 for (unsigned i = 0, e = linalgOp.getNumInputs(); i < e; i++) { 350 if (!linalgOp.getInputIndexingMap(i).isMinorIdentity()) 351 return false; 352 } 353 if (linalgOp->getNumRegions() != 1) 354 return false; 355 return hasOnlyScalarElementwiseOp(linalgOp->getRegion(0)); 356 } 357 358 static Optional<VectorizedLinalgOp> vectorizeContraction(OpBuilder &builder, 359 LinalgOp linalgOp) { 360 assert(isaContractionOpInterface(linalgOp) && 361 "expected vectorizeContraction preconditions to be met"); 362 Location loc = linalgOp.getLoc(); 363 // Vectorize other ops as vector contraction. 364 // TODO: interface. 365 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: " 366 << "Rewrite linalg op as vector.contract: "; 367 linalgOp.dump()); 368 // Special function that describes how to vectorize the multiplication op in a 369 // linalg contraction. 370 CustomVectorizationHook vectorizeContraction = 371 [&](Operation *op, 372 const BlockAndValueMapping &bvm) -> VectorizationResult { 373 if (!isa<MulIOp, MulFOp>(op)) 374 return VectorizationResult{VectorizationStatus::Failure, nullptr}; 375 auto outShape = linalgOp.getOutputShapedType(0).getShape(); 376 auto vType = outShape.empty() 377 ? op->getResult(0).getType() 378 : VectorType::get(outShape, op->getResult(0).getType()); 379 auto zero = 380 builder.create<ConstantOp>(loc, vType, builder.getZeroAttr(vType)); 381 Operation *contract = builder.create<vector::ContractionOp>( 382 loc, bvm.lookup(op->getOperand(0)), bvm.lookup(op->getOperand(1)), zero, 383 linalgOp.indexing_maps(), linalgOp.iterator_types()); 384 return VectorizationResult{VectorizationStatus::NewOp, contract}; 385 }; 386 return vectorizeAsLinalgGeneric(builder, linalgOp, {vectorizeContraction}); 387 } 388 389 LogicalResult mlir::linalg::vectorizeLinalgOpPrecondition(Operation *op) { 390 auto linalgOp = cast<linalg::LinalgOp>(op); 391 // All types must be static shape to go to vector. 392 for (Value operand : linalgOp.getShapedOperands()) 393 if (!operand.getType().cast<ShapedType>().hasStaticShape()) 394 return failure(); 395 for (Type outputTensorType : linalgOp.getOutputTensorTypes()) 396 if (!outputTensorType.cast<ShapedType>().hasStaticShape()) 397 return failure(); 398 if (isElementwise(op)) 399 return success(); 400 return success(isaContractionOpInterface(linalgOp)); 401 } 402 403 Optional<VectorizedLinalgOp> mlir::linalg::vectorizeLinalgOp(OpBuilder &builder, 404 Operation *op) { 405 if (failed(vectorizeLinalgOpPrecondition(op))) 406 return llvm::None; 407 408 edsc::ScopedContext scope(builder, op->getLoc()); 409 if (isElementwise(op)) { 410 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: " 411 << "Vectorize linalg op as a generic: " << *op); 412 return vectorizeAsLinalgGeneric(builder, cast<LinalgOp>(op)); 413 } 414 415 return vectorizeContraction(builder, cast<LinalgOp>(op)); 416 } 417 418 //----------------------------------------------------------------------------// 419 // Misc. vectorization patterns. 420 //----------------------------------------------------------------------------// 421 422 /// Rewrite a PadTensorOp into a sequence of InitTensorOp, TransferReadOp and 423 /// TransferWriteOp. For now, this only applies when all low and high paddings 424 /// are determined to be zero. 425 LogicalResult PadTensorOpVectorizationPattern::matchAndRewrite( 426 linalg::PadTensorOp padOp, PatternRewriter &rewriter) const { 427 // Helper function to determine whether an OpFoldResult is not a zero Index. 428 auto isNotZeroIndex = [](OpFoldResult ofr) { 429 if (Attribute attr = ofr.dyn_cast<Attribute>()) 430 return attr.cast<IntegerAttr>().getInt() != 0; 431 Value v = ofr.get<Value>(); 432 if (auto constOp = v.getDefiningOp<ConstantOp>()) 433 if (auto intAttr = constOp.getValue().dyn_cast<IntegerAttr>()) 434 return intAttr.getValue().getSExtValue() != 0; 435 return true; 436 }; 437 438 auto resultShapedType = padOp.result().getType().cast<ShapedType>(); 439 // Bail on non-static shapes. 440 if (!resultShapedType.hasStaticShape()) 441 return failure(); 442 443 // If any pad_low is not a static 0, needs a mask. Bail for now. 444 if (llvm::any_of(padOp.getMixedLowPad(), isNotZeroIndex)) 445 return failure(); 446 VectorType vectorType = extractVectorTypeFromShapedValue(padOp.result()); 447 if (!vectorType) 448 return failure(); 449 450 // Only support padding with a constant for now, i.e. either: 451 // 1. A BBarg from a different block. 452 // 2. A value defined outside of the current block. 453 Block &block = padOp.region().front(); 454 auto yieldOp = cast<YieldOp>(block.getTerminator()); 455 assert(yieldOp.getNumOperands() == 1 && "expected single operand yield"); 456 Value padValue = yieldOp.values().front(); 457 Operation *definingOp = padValue.getDefiningOp(); 458 if (definingOp && definingOp->getBlock() == &block) 459 return failure(); 460 if (!definingOp && padValue.cast<BlockArgument>().getOwner() == &block) 461 return failure(); 462 463 // TODO: if any pad_high is not a static 0, needs a mask. For now, just bail. 464 if (llvm::any_of(padOp.getMixedHighPad(), 465 [&](OpFoldResult ofr) { return isNotZeroIndex(ofr); })) 466 return failure(); 467 468 // Now we can rewrite as InitTensorOp + TransferReadOp@[0..0] + 469 // TransferWriteOp@[0..0]. 470 SmallVector<Value> indices( 471 resultShapedType.getRank(), 472 rewriter.create<ConstantIndexOp>(padOp.getLoc(), 0)); 473 Value read = rewriter.create<vector::TransferReadOp>( 474 padOp.getLoc(), vectorType, padOp.source(), indices, padValue); 475 Value init = 476 rewriter.create<InitTensorOp>(padOp.getLoc(), resultShapedType.getShape(), 477 resultShapedType.getElementType()); 478 rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(padOp, read, init, 479 indices); 480 481 return success(); 482 } 483 484 // TODO: cleanup all the convolution vectorization patterns. 485 template <class ConvOp, int N> 486 LogicalResult ConvOpVectorization<ConvOp, N>::matchAndRewrite( 487 ConvOp op, PatternRewriter &rewriter) const { 488 Location loc = op.getLoc(); 489 MLIRContext *context = op.getContext(); 490 edsc::ScopedContext scope(rewriter, loc); 491 492 ShapedType inShapeType = op.getInputShapedType(0); 493 ShapedType kShapeType = op.getInputShapedType(1); 494 495 ArrayRef<int64_t> inShape = inShapeType.getShape(); 496 ArrayRef<int64_t> kShape = kShapeType.getShape(); 497 498 if (!inShapeType.hasStaticShape() || !kShapeType.hasStaticShape()) 499 return failure(); 500 501 SmallVector<AffineExpr, 4> mapping; 502 SmallVector<int64_t, 4> vectorDims; 503 // Fail to apply when the size of not vectorized dimension is not 1. 504 for (unsigned i = 0; i < N; i++) { 505 if (!mask[i] && (inShape[i] != 1 || kShape[i] != 1)) 506 return failure(); 507 508 if (mask[i] && inShape[i] != kShape[i]) 509 return failure(); 510 511 if (mask[i]) { 512 mapping.push_back(getAffineDimExpr(i, context)); 513 vectorDims.push_back(inShape[i]); 514 } 515 } 516 517 Value input = op.getInput(0); 518 Value kernel = op.getInput(1); 519 Value output = op.getOutputBuffer(0); 520 521 unsigned rank = inShapeType.getRank(); 522 unsigned numDims = mapping.size(); 523 Type elemType = inShapeType.getElementType(); 524 525 auto map = AffineMap::get(rank, 0, mapping, context); 526 SmallVector<Value, 4> zeros(rank, std_constant_index(0)); 527 auto vecType = VectorType::get(vectorDims, elemType); 528 529 auto inputVec = vector_transfer_read(vecType, input, zeros, map); 530 auto kernelVec = vector_transfer_read(vecType, kernel, zeros, map); 531 532 auto acc = std_constant(elemType, rewriter.getZeroAttr(elemType)); 533 534 std::array<AffineMap, 3> indexingMaps{ 535 AffineMap::getMultiDimIdentityMap(numDims, context), 536 AffineMap::getMultiDimIdentityMap(numDims, context), 537 AffineMap::get(numDims, 0, {}, context)}; 538 539 std::vector<StringRef> iteratorTypes(numDims, "reduction"); 540 541 auto result = rewriter.create<vector::ContractionOp>( 542 loc, inputVec, kernelVec, acc, 543 rewriter.getAffineMapArrayAttr(indexingMaps), 544 rewriter.getStrArrayAttr(iteratorTypes)); 545 546 rewriter.create<StoreOp>(loc, result, output, ValueRange(zeros)); 547 rewriter.eraseOp(op); 548 return success(); 549 } 550 551 using ConvOpConst = ConvOpVectorization<ConvWOp, 1>; 552 553 /// Inserts tiling, promotion and vectorization pattern for ConvOp 554 /// conversion into corresponding pattern lists. 555 template <typename ConvOp, unsigned N> 556 static void 557 populateVectorizationPatterns(OwningRewritePatternList &tilingPatterns, 558 OwningRewritePatternList &promotionPatterns, 559 OwningRewritePatternList &vectorizationPatterns, 560 ArrayRef<int64_t> tileSizes, 561 MLIRContext *context) { 562 if (tileSizes.size() < N) 563 return; 564 565 constexpr static StringRef kTiledMarker = "TILED"; 566 constexpr static StringRef kPromotedMarker = "PROMOTED"; 567 tilingPatterns.insert<LinalgTilingPattern<ConvOp>>( 568 context, LinalgTilingOptions().setTileSizes(tileSizes), 569 LinalgTransformationFilter(ArrayRef<Identifier>{}, 570 Identifier::get(kTiledMarker, context))); 571 572 promotionPatterns.insert<LinalgPromotionPattern<ConvOp>>( 573 context, LinalgPromotionOptions().setUseFullTileBuffersByDefault(true), 574 LinalgTransformationFilter(Identifier::get(kTiledMarker, context), 575 Identifier::get(kPromotedMarker, context))); 576 577 SmallVector<bool, 4> mask(N); 578 int offset = tileSizes.size() - N; 579 std::transform(tileSizes.begin() + offset, tileSizes.end(), mask.begin(), 580 [](int64_t i) -> bool { return i > 1; }); 581 582 vectorizationPatterns.insert<ConvOpVectorization<ConvOp, N>>(context, mask); 583 } 584 585 void mlir::linalg::populateConvVectorizationPatterns( 586 MLIRContext *context, SmallVectorImpl<OwningRewritePatternList> &patterns, 587 ArrayRef<int64_t> tileSizes) { 588 OwningRewritePatternList tiling, promotion, vectorization; 589 populateVectorizationPatterns<ConvWOp, 1>(tiling, promotion, vectorization, 590 tileSizes, context); 591 592 populateVectorizationPatterns<ConvNWCOp, 3>(tiling, promotion, vectorization, 593 tileSizes, context); 594 populateVectorizationPatterns<ConvInputNWCFilterWCFOp, 3>( 595 tiling, promotion, vectorization, tileSizes, context); 596 597 populateVectorizationPatterns<ConvNCWOp, 3>(tiling, promotion, vectorization, 598 tileSizes, context); 599 populateVectorizationPatterns<ConvInputNCWFilterWCFOp, 3>( 600 tiling, promotion, vectorization, tileSizes, context); 601 602 populateVectorizationPatterns<ConvHWOp, 2>(tiling, promotion, vectorization, 603 tileSizes, context); 604 605 populateVectorizationPatterns<ConvNHWCOp, 4>(tiling, promotion, vectorization, 606 tileSizes, context); 607 populateVectorizationPatterns<ConvInputNHWCFilterHWCFOp, 4>( 608 tiling, promotion, vectorization, tileSizes, context); 609 610 populateVectorizationPatterns<ConvNCHWOp, 4>(tiling, promotion, vectorization, 611 tileSizes, context); 612 populateVectorizationPatterns<ConvInputNCHWFilterHWCFOp, 4>( 613 tiling, promotion, vectorization, tileSizes, context); 614 615 populateVectorizationPatterns<ConvDHWOp, 3>(tiling, promotion, vectorization, 616 tileSizes, context); 617 618 populateVectorizationPatterns<ConvNDHWCOp, 5>( 619 tiling, promotion, vectorization, tileSizes, context); 620 populateVectorizationPatterns<ConvInputNDHWCFilterDHWCFOp, 5>( 621 tiling, promotion, vectorization, tileSizes, context); 622 623 populateVectorizationPatterns<ConvNCDHWOp, 5>( 624 tiling, promotion, vectorization, tileSizes, context); 625 populateVectorizationPatterns<ConvInputNCDHWFilterDHWCFOp, 5>( 626 tiling, promotion, vectorization, tileSizes, context); 627 628 patterns.push_back(std::move(tiling)); 629 patterns.push_back(std::move(promotion)); 630 patterns.push_back(std::move(vectorization)); 631 } 632 633 //----------------------------------------------------------------------------// 634 // Forwarding patterns 635 //----------------------------------------------------------------------------// 636 637 /// Check whether there is any interleaved use of any `values` between `firstOp` 638 /// and `secondOp`. Conservatively return `true` if any op or value is in a 639 /// different block. 640 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp, 641 ValueRange values) { 642 if (firstOp->getBlock() != secondOp->getBlock() || 643 !firstOp->isBeforeInBlock(secondOp)) { 644 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 645 << "interleavedUses precondition failed, firstOp: " 646 << *firstOp << ", second op: " << *secondOp); 647 return true; 648 } 649 for (auto v : values) { 650 for (auto &u : v.getUses()) { 651 Operation *owner = u.getOwner(); 652 if (owner == firstOp || owner == secondOp) 653 continue; 654 // TODO: this is too conservative, use dominance info in the future. 655 if (owner->getBlock() == firstOp->getBlock() && 656 (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner))) 657 continue; 658 LLVM_DEBUG(llvm::dbgs() 659 << "\n[" DEBUG_TYPE "]: " 660 << " found interleaved op " << *owner 661 << ", firstOp: " << *firstOp << ", second op: " << *secondOp); 662 return true; 663 } 664 } 665 return false; 666 } 667 668 /// Return the unique subview use of `v` if it is indeed unique, null otherwise. 669 static SubViewOp getSubViewUseIfUnique(Value v) { 670 SubViewOp subViewOp; 671 for (auto &u : v.getUses()) { 672 if (auto newSubViewOp = dyn_cast<SubViewOp>(u.getOwner())) { 673 if (subViewOp) 674 return SubViewOp(); 675 subViewOp = newSubViewOp; 676 } 677 } 678 return subViewOp; 679 } 680 681 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate, 682 /// when available. 683 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite( 684 vector::TransferReadOp xferOp, PatternRewriter &rewriter) const { 685 686 // Transfer into `view`. 687 Value viewOrAlloc = xferOp.source(); 688 if (!viewOrAlloc.getDefiningOp<ViewOp>() && 689 !viewOrAlloc.getDefiningOp<AllocOp>()) 690 return failure(); 691 692 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " << viewOrAlloc); 693 694 // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`. 695 SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc); 696 if (!subViewOp) 697 return failure(); 698 Value subView = subViewOp.getResult(); 699 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 700 << "with subView " << subView); 701 702 // Find the copy into `subView` without interleaved uses. 703 CopyOp copyOp; 704 for (auto &u : subView.getUses()) { 705 if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) { 706 if (newCopyOp.getOutputBuffer(0) != subView) 707 continue; 708 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 709 << "copy candidate " << *newCopyOp); 710 if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView})) 711 continue; 712 copyOp = newCopyOp; 713 break; 714 } 715 } 716 if (!copyOp) 717 return failure(); 718 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 719 << "with copy " << *copyOp); 720 721 // Find the fill into `viewOrAlloc` without interleaved uses before the copy. 722 FillOp maybeFillOp; 723 for (auto &u : viewOrAlloc.getUses()) { 724 if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) { 725 if (newFillOp.getOutputBuffer(0) != viewOrAlloc) 726 continue; 727 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 728 << "fill candidate " << *newFillOp); 729 if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView})) 730 continue; 731 maybeFillOp = newFillOp; 732 break; 733 } 734 } 735 // Ensure padding matches. 736 if (maybeFillOp && xferOp.padding() != maybeFillOp.value()) 737 return failure(); 738 if (maybeFillOp) 739 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 740 << "with maybeFillOp " << *maybeFillOp); 741 742 // `in` is the subview that linalg.copy reads. Replace it. 743 Value in = copyOp.getInput(0); 744 745 // linalg.copy + linalg.fill can be used to create a padded local buffer. 746 // The `masked` attribute is only valid on this padded buffer. 747 // When forwarding to vector.transfer_read, the attribute must be reset 748 // conservatively. 749 Value res = rewriter.create<vector::TransferReadOp>( 750 xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.indices(), 751 xferOp.permutation_map(), xferOp.padding(), ArrayAttr()); 752 753 if (maybeFillOp) 754 rewriter.eraseOp(maybeFillOp); 755 rewriter.eraseOp(copyOp); 756 rewriter.replaceOp(xferOp, res); 757 758 return success(); 759 } 760 761 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate, 762 /// when available. 763 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite( 764 vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const { 765 // Transfer into `viewOrAlloc`. 766 Value viewOrAlloc = xferOp.source(); 767 if (!viewOrAlloc.getDefiningOp<ViewOp>() && 768 !viewOrAlloc.getDefiningOp<AllocOp>()) 769 return failure(); 770 771 // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`. 772 SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc); 773 if (!subViewOp) 774 return failure(); 775 Value subView = subViewOp.getResult(); 776 777 // Find the copy from `subView` without interleaved uses. 778 CopyOp copyOp; 779 for (auto &u : subViewOp.getResult().getUses()) { 780 if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) { 781 if (newCopyOp.getInput(0) != subView) 782 continue; 783 if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView})) 784 continue; 785 copyOp = newCopyOp; 786 break; 787 } 788 } 789 if (!copyOp) 790 return failure(); 791 792 // `out` is the subview copied into that we replace. 793 Value out = copyOp.getOutputBuffer(0); 794 795 // Forward vector.transfer into copy. 796 // linalg.copy + linalg.fill can be used to create a padded local buffer. 797 // The `masked` attribute is only valid on this padded buffer. 798 // When forwarding to vector.transfer_write, the attribute must be reset 799 // conservatively. 800 rewriter.create<vector::TransferWriteOp>( 801 xferOp.getLoc(), xferOp.vector(), out, xferOp.indices(), 802 xferOp.permutation_map(), ArrayAttr()); 803 804 rewriter.eraseOp(copyOp); 805 rewriter.eraseOp(xferOp); 806 807 return success(); 808 } 809