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