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 (!op->hasTrait<OpTrait::ElementwiseMappable>()) 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); 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 op.hasTrait<OpTrait::ElementwiseMappable>()) || 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 genericOp = dyn_cast<linalg::GenericOp>(op); 337 if (!genericOp) 338 return false; 339 if (genericOp.getNumLoops() != genericOp.getNumParallelLoops()) 340 return false; 341 // TODO: relax the restrictions on indexing map. 342 for (unsigned i = 0, e = genericOp.getNumOutputs(); i < e; i++) { 343 if (!genericOp.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 = genericOp.getNumInputs(); i < e; i++) { 350 if (!genericOp.getInputIndexingMap(i).isMinorIdentity()) 351 return false; 352 } 353 return hasOnlyScalarElementwiseOp(genericOp.getRegion()); 354 } 355 356 static Optional<VectorizedLinalgOp> vectorizeContraction(OpBuilder &builder, 357 LinalgOp linalgOp) { 358 assert(isaContractionOpInterface(linalgOp) && 359 "expected vectorizeContraction preconditions to be met"); 360 Location loc = linalgOp.getLoc(); 361 // Vectorize other ops as vector contraction. 362 // TODO: interface. 363 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: " 364 << "Rewrite linalg op as vector.contract: "; 365 linalgOp.dump()); 366 // Special function that describes how to vectorize the multiplication op in a 367 // linalg contraction. 368 CustomVectorizationHook vectorizeContraction = 369 [&](Operation *op, 370 const BlockAndValueMapping &bvm) -> VectorizationResult { 371 if (!isa<MulIOp, MulFOp>(op)) 372 return VectorizationResult{VectorizationStatus::Failure, nullptr}; 373 auto outShape = linalgOp.getOutputShapedType(0).getShape(); 374 auto vType = outShape.empty() 375 ? op->getResult(0).getType() 376 : VectorType::get(outShape, op->getResult(0).getType()); 377 auto zero = 378 builder.create<ConstantOp>(loc, vType, builder.getZeroAttr(vType)); 379 Operation *contract = builder.create<vector::ContractionOp>( 380 loc, bvm.lookup(op->getOperand(0)), bvm.lookup(op->getOperand(1)), zero, 381 linalgOp.indexing_maps(), linalgOp.iterator_types()); 382 return VectorizationResult{VectorizationStatus::NewOp, contract}; 383 }; 384 return vectorizeAsLinalgGeneric(builder, linalgOp, {vectorizeContraction}); 385 } 386 387 LogicalResult mlir::linalg::vectorizeLinalgOpPrecondition(Operation *op) { 388 auto linalgOp = cast<linalg::LinalgOp>(op); 389 // All types must be static shape to go to vector. 390 for (Value operand : linalgOp.getShapedOperands()) 391 if (!operand.getType().cast<ShapedType>().hasStaticShape()) 392 return failure(); 393 for (Type outputTensorType : linalgOp.getOutputTensorTypes()) 394 if (!outputTensorType.cast<ShapedType>().hasStaticShape()) 395 return failure(); 396 397 if (isa<linalg::FillOp, linalg::CopyOp>(op)) 398 return success(); 399 if (isElementwise(op)) 400 return success(); 401 return success(isaContractionOpInterface(linalgOp)); 402 } 403 404 Optional<VectorizedLinalgOp> mlir::linalg::vectorizeLinalgOp(OpBuilder &builder, 405 Operation *op) { 406 if (failed(vectorizeLinalgOpPrecondition(op))) 407 return llvm::None; 408 409 edsc::ScopedContext scope(builder, op->getLoc()); 410 // In the case of 0-D memrefs, return null and special case to scalar load or 411 // store later. 412 if (auto fillOp = dyn_cast<linalg::FillOp>(op)) { 413 // Vectorize fill as a vector.broadcast. 414 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: " 415 << "Rewrite linalg.fill as vector.broadcast: " << *op); 416 VectorizedLinalgOp res; 417 if (Value v = buildVectorWrite(builder, fillOp.value(), fillOp.output())) 418 res.tensorResults.push_back(v); 419 return res; 420 } 421 if (auto copyOp = dyn_cast<linalg::CopyOp>(op)) { 422 // Vectorize copy as a vector.transfer_read+vector.transfer_write. 423 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: " 424 << "Rewrite linalg.copy as vector.transfer_read + " 425 "vector.transfer_write: " 426 << *op); 427 Value vector = buildVectorRead(builder, copyOp.input()); 428 VectorizedLinalgOp res; 429 if (Value v = buildVectorWrite(builder, vector, copyOp.output())) 430 res.tensorResults.push_back(v); 431 return res; 432 } 433 if (isElementwise(op)) { 434 LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: " 435 << "Vectorize linalg op as a generic: " << *op); 436 return vectorizeAsLinalgGeneric(builder, cast<LinalgOp>(op)); 437 } 438 439 // TODO: as soon as Copy and FillOp. get a region builder, replace all the 440 // above by: 441 // if (isa<FillOp, CopyOp>(op) || isElementwise(op)) { 442 // LLVM_DEBUG(dbgs() << "\n[" DEBUG_TYPE "]: " 443 // << "Vectorize linalg op as a generic: " << *op); 444 // return vectorizeAsLinalgGeneric(builder, cast<LinalgOp>(op)); 445 // } 446 447 return vectorizeContraction(builder, cast<LinalgOp>(op)); 448 } 449 450 //----------------------------------------------------------------------------// 451 // Misc. vectorization patterns. 452 //----------------------------------------------------------------------------// 453 454 /// Rewrite a PadTensorOp into a sequence of InitTensorOp, TransferReadOp and 455 /// TransferWriteOp. For now, this only applies when all low and high paddings 456 /// are determined to be zero. 457 LogicalResult PadTensorOpVectorizationPattern::matchAndRewrite( 458 linalg::PadTensorOp padOp, PatternRewriter &rewriter) const { 459 // Helper function to determine whether an OpFoldResult is not a zero Index. 460 auto isNotZeroIndex = [](OpFoldResult ofr) { 461 if (Attribute attr = ofr.dyn_cast<Attribute>()) 462 return attr.cast<IntegerAttr>().getInt() != 0; 463 Value v = ofr.get<Value>(); 464 if (auto constOp = v.getDefiningOp<ConstantIntOp>()) 465 return constOp.getValue() != 0; 466 return true; 467 }; 468 469 auto resultShapedType = padOp.result().getType().cast<ShapedType>(); 470 // Bail on non-static shapes. 471 if (!resultShapedType.hasStaticShape()) 472 return failure(); 473 474 // If any pad_low is not a static 0, needs a mask. Bail for now. 475 if (llvm::any_of(padOp.getMixedLowPad(), isNotZeroIndex)) 476 return failure(); 477 VectorType vectorType = extractVectorTypeFromShapedValue(padOp.result()); 478 if (!vectorType) 479 return failure(); 480 481 // Only support padding with a constant for now, i.e. either: 482 // 1. A BBarg from a different block. 483 // 2. A value defined outside of the current block. 484 Block &block = padOp.region().front(); 485 auto yieldOp = cast<YieldOp>(block.getTerminator()); 486 assert(yieldOp.getNumOperands() == 1 && "expected single operand yield"); 487 Value padValue = yieldOp.values().front(); 488 Operation *definingOp = padValue.getDefiningOp(); 489 if (definingOp && definingOp->getBlock() == &block) 490 return failure(); 491 if (!definingOp && padValue.cast<BlockArgument>().getOwner() == &block) 492 return failure(); 493 494 // TODO: if any pad_high is not a static 0, needs a mask. For now, just bail. 495 if (llvm::any_of(padOp.getMixedHighPad(), 496 [&](OpFoldResult ofr) { return isNotZeroIndex(ofr); })) 497 return failure(); 498 499 // Now we can rewrite as InitTensorOp + TransferReadOp@[0..0] + 500 // TransferWriteOp@[0..0]. 501 SmallVector<Value> indices( 502 resultShapedType.getRank(), 503 rewriter.create<ConstantIndexOp>(padOp.getLoc(), 0)); 504 Value read = rewriter.create<vector::TransferReadOp>( 505 padOp.getLoc(), vectorType, padOp.source(), indices, padValue); 506 Value init = 507 rewriter.create<InitTensorOp>(padOp.getLoc(), resultShapedType.getShape(), 508 resultShapedType.getElementType()); 509 rewriter.replaceOpWithNewOp<vector::TransferWriteOp>(padOp, read, init, 510 indices); 511 512 return success(); 513 } 514 515 // TODO: cleanup all the convolution vectorization patterns. 516 template <class ConvOp, int N> 517 LogicalResult ConvOpVectorization<ConvOp, N>::matchAndRewrite( 518 ConvOp op, PatternRewriter &rewriter) const { 519 Location loc = op.getLoc(); 520 MLIRContext *context = op.getContext(); 521 edsc::ScopedContext scope(rewriter, loc); 522 523 ShapedType inShapeType = op.getInputShapedType(0); 524 ShapedType kShapeType = op.getInputShapedType(1); 525 526 ArrayRef<int64_t> inShape = inShapeType.getShape(); 527 ArrayRef<int64_t> kShape = kShapeType.getShape(); 528 529 if (!inShapeType.hasStaticShape() || !kShapeType.hasStaticShape()) 530 return failure(); 531 532 SmallVector<AffineExpr, 4> mapping; 533 SmallVector<int64_t, 4> vectorDims; 534 // Fail to apply when the size of not vectorized dimension is not 1. 535 for (unsigned i = 0; i < N; i++) { 536 if (!mask[i] && (inShape[i] != 1 || kShape[i] != 1)) 537 return failure(); 538 539 if (mask[i] && inShape[i] != kShape[i]) 540 return failure(); 541 542 if (mask[i]) { 543 mapping.push_back(getAffineDimExpr(i, context)); 544 vectorDims.push_back(inShape[i]); 545 } 546 } 547 548 Value input = op.getInput(0); 549 Value kernel = op.getInput(1); 550 Value output = op.getOutputBuffer(0); 551 552 unsigned rank = inShapeType.getRank(); 553 unsigned numDims = mapping.size(); 554 Type elemType = inShapeType.getElementType(); 555 556 auto map = AffineMap::get(rank, 0, mapping, context); 557 SmallVector<Value, 4> zeros(rank, std_constant_index(0)); 558 auto vecType = VectorType::get(vectorDims, elemType); 559 560 auto inputVec = vector_transfer_read(vecType, input, zeros, map); 561 auto kernelVec = vector_transfer_read(vecType, kernel, zeros, map); 562 563 auto acc = std_constant(elemType, rewriter.getZeroAttr(elemType)); 564 565 std::array<AffineMap, 3> indexingMaps{ 566 AffineMap::getMultiDimIdentityMap(numDims, context), 567 AffineMap::getMultiDimIdentityMap(numDims, context), 568 AffineMap::get(numDims, 0, {}, context)}; 569 570 std::vector<StringRef> iteratorTypes(numDims, "reduction"); 571 572 auto result = rewriter.create<vector::ContractionOp>( 573 loc, inputVec, kernelVec, acc, 574 rewriter.getAffineMapArrayAttr(indexingMaps), 575 rewriter.getStrArrayAttr(iteratorTypes)); 576 577 rewriter.create<StoreOp>(loc, result, output, ValueRange(zeros)); 578 rewriter.eraseOp(op); 579 return success(); 580 } 581 582 using ConvOpConst = ConvOpVectorization<ConvWOp, 1>; 583 584 /// Inserts tiling, promotion and vectorization pattern for ConvOp 585 /// conversion into corresponding pattern lists. 586 template <typename ConvOp, unsigned N> 587 static void 588 populateVectorizationPatterns(OwningRewritePatternList &tilingPatterns, 589 OwningRewritePatternList &promotionPatterns, 590 OwningRewritePatternList &vectorizationPatterns, 591 ArrayRef<int64_t> tileSizes, 592 MLIRContext *context) { 593 if (tileSizes.size() < N) 594 return; 595 596 constexpr static StringRef kTiledMarker = "TILED"; 597 constexpr static StringRef kPromotedMarker = "PROMOTED"; 598 tilingPatterns.insert<LinalgTilingPattern<ConvOp>>( 599 context, LinalgTilingOptions().setTileSizes(tileSizes), 600 LinalgTransformationFilter(ArrayRef<Identifier>{}, 601 Identifier::get(kTiledMarker, context))); 602 603 promotionPatterns.insert<LinalgPromotionPattern<ConvOp>>( 604 context, LinalgPromotionOptions().setUseFullTileBuffersByDefault(true), 605 LinalgTransformationFilter(Identifier::get(kTiledMarker, context), 606 Identifier::get(kPromotedMarker, context))); 607 608 SmallVector<bool, 4> mask(N); 609 int offset = tileSizes.size() - N; 610 std::transform(tileSizes.begin() + offset, tileSizes.end(), mask.begin(), 611 [](int64_t i) -> bool { return i > 1; }); 612 613 vectorizationPatterns.insert<ConvOpVectorization<ConvOp, N>>(context, mask); 614 } 615 616 void mlir::linalg::populateConvVectorizationPatterns( 617 MLIRContext *context, SmallVectorImpl<OwningRewritePatternList> &patterns, 618 ArrayRef<int64_t> tileSizes) { 619 OwningRewritePatternList tiling, promotion, vectorization; 620 populateVectorizationPatterns<ConvWOp, 1>(tiling, promotion, vectorization, 621 tileSizes, context); 622 623 populateVectorizationPatterns<ConvNWCOp, 3>(tiling, promotion, vectorization, 624 tileSizes, context); 625 populateVectorizationPatterns<ConvInputNWCFilterWCFOp, 3>( 626 tiling, promotion, vectorization, tileSizes, context); 627 628 populateVectorizationPatterns<ConvNCWOp, 3>(tiling, promotion, vectorization, 629 tileSizes, context); 630 populateVectorizationPatterns<ConvInputNCWFilterWCFOp, 3>( 631 tiling, promotion, vectorization, tileSizes, context); 632 633 populateVectorizationPatterns<ConvHWOp, 2>(tiling, promotion, vectorization, 634 tileSizes, context); 635 636 populateVectorizationPatterns<ConvNHWCOp, 4>(tiling, promotion, vectorization, 637 tileSizes, context); 638 populateVectorizationPatterns<ConvInputNHWCFilterHWCFOp, 4>( 639 tiling, promotion, vectorization, tileSizes, context); 640 641 populateVectorizationPatterns<ConvNCHWOp, 4>(tiling, promotion, vectorization, 642 tileSizes, context); 643 populateVectorizationPatterns<ConvInputNCHWFilterHWCFOp, 4>( 644 tiling, promotion, vectorization, tileSizes, context); 645 646 populateVectorizationPatterns<ConvDHWOp, 3>(tiling, promotion, vectorization, 647 tileSizes, context); 648 649 populateVectorizationPatterns<ConvNDHWCOp, 5>( 650 tiling, promotion, vectorization, tileSizes, context); 651 populateVectorizationPatterns<ConvInputNDHWCFilterDHWCFOp, 5>( 652 tiling, promotion, vectorization, tileSizes, context); 653 654 populateVectorizationPatterns<ConvNCDHWOp, 5>( 655 tiling, promotion, vectorization, tileSizes, context); 656 populateVectorizationPatterns<ConvInputNCDHWFilterDHWCFOp, 5>( 657 tiling, promotion, vectorization, tileSizes, context); 658 659 patterns.push_back(std::move(tiling)); 660 patterns.push_back(std::move(promotion)); 661 patterns.push_back(std::move(vectorization)); 662 } 663 664 //----------------------------------------------------------------------------// 665 // Forwarding patterns 666 //----------------------------------------------------------------------------// 667 668 /// Check whether there is any interleaved use of any `values` between `firstOp` 669 /// and `secondOp`. Conservatively return `true` if any op or value is in a 670 /// different block. 671 static bool mayExistInterleavedUses(Operation *firstOp, Operation *secondOp, 672 ValueRange values) { 673 if (firstOp->getBlock() != secondOp->getBlock() || 674 !firstOp->isBeforeInBlock(secondOp)) { 675 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 676 << "interleavedUses precondition failed, firstOp: " 677 << *firstOp << ", second op: " << *secondOp); 678 return true; 679 } 680 for (auto v : values) { 681 for (auto &u : v.getUses()) { 682 Operation *owner = u.getOwner(); 683 if (owner == firstOp || owner == secondOp) 684 continue; 685 // TODO: this is too conservative, use dominance info in the future. 686 if (owner->getBlock() == firstOp->getBlock() && 687 (owner->isBeforeInBlock(firstOp) || secondOp->isBeforeInBlock(owner))) 688 continue; 689 LLVM_DEBUG(llvm::dbgs() 690 << "\n[" DEBUG_TYPE "]: " 691 << " found interleaved op " << *owner 692 << ", firstOp: " << *firstOp << ", second op: " << *secondOp); 693 return true; 694 } 695 } 696 return false; 697 } 698 699 /// Return the unique subview use of `v` if it is indeed unique, null otherwise. 700 static SubViewOp getSubViewUseIfUnique(Value v) { 701 SubViewOp subViewOp; 702 for (auto &u : v.getUses()) { 703 if (auto newSubViewOp = dyn_cast<SubViewOp>(u.getOwner())) { 704 if (subViewOp) 705 return SubViewOp(); 706 subViewOp = newSubViewOp; 707 } 708 } 709 return subViewOp; 710 } 711 712 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate, 713 /// when available. 714 LogicalResult LinalgCopyVTRForwardingPattern::matchAndRewrite( 715 vector::TransferReadOp xferOp, PatternRewriter &rewriter) const { 716 717 // Transfer into `view`. 718 Value viewOrAlloc = xferOp.source(); 719 if (!viewOrAlloc.getDefiningOp<ViewOp>() && 720 !viewOrAlloc.getDefiningOp<AllocOp>()) 721 return failure(); 722 723 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " << viewOrAlloc); 724 725 // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`. 726 SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc); 727 if (!subViewOp) 728 return failure(); 729 Value subView = subViewOp.getResult(); 730 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 731 << "with subView " << subView); 732 733 // Find the copy into `subView` without interleaved uses. 734 CopyOp copyOp; 735 for (auto &u : subView.getUses()) { 736 if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) { 737 if (newCopyOp.getOutputBuffer(0) != subView) 738 continue; 739 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 740 << "copy candidate " << *newCopyOp); 741 if (mayExistInterleavedUses(newCopyOp, xferOp, {viewOrAlloc, subView})) 742 continue; 743 copyOp = newCopyOp; 744 break; 745 } 746 } 747 if (!copyOp) 748 return failure(); 749 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 750 << "with copy " << *copyOp); 751 752 // Find the fill into `viewOrAlloc` without interleaved uses before the copy. 753 FillOp maybeFillOp; 754 for (auto &u : viewOrAlloc.getUses()) { 755 if (auto newFillOp = dyn_cast<FillOp>(u.getOwner())) { 756 if (newFillOp.getOutputBuffer(0) != viewOrAlloc) 757 continue; 758 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 759 << "fill candidate " << *newFillOp); 760 if (mayExistInterleavedUses(newFillOp, copyOp, {viewOrAlloc, subView})) 761 continue; 762 maybeFillOp = newFillOp; 763 break; 764 } 765 } 766 // Ensure padding matches. 767 if (maybeFillOp && xferOp.padding() != maybeFillOp.value()) 768 return failure(); 769 if (maybeFillOp) 770 LLVM_DEBUG(llvm::dbgs() << "\n[" DEBUG_TYPE "]: " 771 << "with maybeFillOp " << *maybeFillOp); 772 773 // `in` is the subview that linalg.copy reads. Replace it. 774 Value in = copyOp.getInput(0); 775 776 // linalg.copy + linalg.fill can be used to create a padded local buffer. 777 // The `masked` attribute is only valid on this padded buffer. 778 // When forwarding to vector.transfer_read, the attribute must be reset 779 // conservatively. 780 Value res = rewriter.create<vector::TransferReadOp>( 781 xferOp.getLoc(), xferOp.getVectorType(), in, xferOp.indices(), 782 xferOp.permutation_map(), xferOp.padding(), ArrayAttr()); 783 784 if (maybeFillOp) 785 rewriter.eraseOp(maybeFillOp); 786 rewriter.eraseOp(copyOp); 787 rewriter.replaceOp(xferOp, res); 788 789 return success(); 790 } 791 792 /// TODO: use interfaces, side-effects and aliasing analysis as appropriate, 793 /// when available. 794 LogicalResult LinalgCopyVTWForwardingPattern::matchAndRewrite( 795 vector::TransferWriteOp xferOp, PatternRewriter &rewriter) const { 796 // Transfer into `viewOrAlloc`. 797 Value viewOrAlloc = xferOp.source(); 798 if (!viewOrAlloc.getDefiningOp<ViewOp>() && 799 !viewOrAlloc.getDefiningOp<AllocOp>()) 800 return failure(); 801 802 // Ensure there is exactly one subview of `viewOrAlloc` defining `subView`. 803 SubViewOp subViewOp = getSubViewUseIfUnique(viewOrAlloc); 804 if (!subViewOp) 805 return failure(); 806 Value subView = subViewOp.getResult(); 807 808 // Find the copy from `subView` without interleaved uses. 809 CopyOp copyOp; 810 for (auto &u : subViewOp.getResult().getUses()) { 811 if (auto newCopyOp = dyn_cast<CopyOp>(u.getOwner())) { 812 if (newCopyOp.getInput(0) != subView) 813 continue; 814 if (mayExistInterleavedUses(xferOp, newCopyOp, {viewOrAlloc, subView})) 815 continue; 816 copyOp = newCopyOp; 817 break; 818 } 819 } 820 if (!copyOp) 821 return failure(); 822 823 // `out` is the subview copied into that we replace. 824 Value out = copyOp.getOutputBuffer(0); 825 826 // Forward vector.transfer into copy. 827 // linalg.copy + linalg.fill can be used to create a padded local buffer. 828 // The `masked` attribute is only valid on this padded buffer. 829 // When forwarding to vector.transfer_write, the attribute must be reset 830 // conservatively. 831 rewriter.create<vector::TransferWriteOp>( 832 xferOp.getLoc(), xferOp.vector(), out, xferOp.indices(), 833 xferOp.permutation_map(), ArrayAttr()); 834 835 rewriter.eraseOp(copyOp); 836 rewriter.eraseOp(xferOp); 837 838 return success(); 839 } 840