1 //===- LinalgInterfaces.cpp - Linalg interfaces implementation ------------===// 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 #include "mlir/Dialect/Linalg/IR/LinalgInterfaces.h" 10 11 #include "mlir/Dialect/Affine/IR/AffineOps.h" 12 #include "mlir/Dialect/MemRef/IR/MemRef.h" 13 #include "mlir/IR/AffineExprVisitor.h" 14 #include "mlir/IR/AffineMap.h" 15 #include "llvm/ADT/SmallSet.h" 16 17 using namespace mlir; 18 using namespace mlir::linalg; 19 20 /// Include the definitions of the copy operation interface. 21 #include "mlir/Dialect/Linalg/IR/LinalgInterfaces.cpp.inc" 22 23 //===----------------------------------------------------------------------===// 24 // ContractionOpInterface implementation 25 //===----------------------------------------------------------------------===// 26 27 /// Return true if the use-def chain from `v` to `from` consists of 0 or more 28 /// unary single-operand operations. 29 // TODO: relax to multi-operands with constants, which are technically unary ops 30 // as needed (e.g. add5). 31 static bool isChainOfUnaryOpsFrom(Value v, Value from) { 32 while (true) { 33 if (v == from) 34 return true; 35 Operation *op = v.getDefiningOp(); 36 if (!op || op->getNumOperands() != 1) 37 return false; 38 v = op->getOperand(0); 39 }; 40 } 41 42 /// Return the unique instance of OpType in `block` if it is indeed unique. 43 /// Return null if none or more than 1 instances exist. 44 template <typename OpType> 45 static OpType getSingleOpOfType(Block &block) { 46 OpType res = nullptr; 47 block.walk([&](OpType op) { 48 if (res) { 49 res = nullptr; 50 return WalkResult::interrupt(); 51 } 52 res = op; 53 return WalkResult::advance(); 54 }); 55 return res; 56 } 57 58 /// Detect whether res is any permutation of `u5(u1(c) + u2(u3(a) * u4(b)))` 59 /// on the field (AddOpType, MulOpType), where u1, u2, u3, u4 and u5 represent 60 /// unary operations that may change the type. 61 template <typename AddOpType, typename MulOpType> 62 static bool isAddMul(Block &block) { 63 if (block.getNumArguments() != 3) 64 return false; 65 Operation *yieldOp = block.getTerminator(); 66 if (yieldOp->getNumOperands() != 1) 67 return false; 68 69 AddOpType addOp = getSingleOpOfType<AddOpType>(block); 70 MulOpType mulOp = getSingleOpOfType<MulOpType>(block); 71 if (!addOp || !mulOp) 72 return false; 73 74 Value argA = block.getArgument(0), argB = block.getArgument(1); 75 Value a = mulOp->getOperand(0), b = mulOp->getOperand(1); 76 Value mul = mulOp->getResult(0); 77 Value argC = block.getArgument(2); 78 Value c1 = addOp->getOperand(0), c2 = addOp->getOperand(1); 79 Value add = addOp->getResult(0); 80 Value res = yieldOp->getOperand(0); 81 // Result traces back to add. 82 auto un = isChainOfUnaryOpsFrom; 83 bool success = un(res, add); 84 // One of the operands of add traces back to argC, the other to the mul. 85 success |= (un(c1, argC) && un(c2, mul)) || ((un(c1, mul)) && un(c2, argC)); 86 // One of the operands of mul traces back to argA, the other to argB. 87 success |= (un(a, argA) && un(b, argB)) || ((un(a, argB)) && un(b, argA)); 88 return success; 89 } 90 91 enum MatchContractionResult { 92 Success = 0, 93 NotLinalgOp, 94 WrongNumOperands, 95 NoReduction, 96 NotProjectedPermutations, 97 NotAddMul 98 }; 99 static MatchContractionResult isContractionInterfaceImpl(Operation *op) { 100 auto linalgOp = dyn_cast<linalg::LinalgOp>(op); 101 if (!linalgOp) 102 return MatchContractionResult::NotLinalgOp; 103 if (linalgOp.getNumInputs() != 2 || linalgOp.getNumOutputs() != 1) 104 return MatchContractionResult::WrongNumOperands; 105 auto mapRange = linalgOp.indexing_maps().getAsValueRange<AffineMapAttr>(); 106 if (linalgOp.getNumReductionLoops() == 0) 107 return MatchContractionResult::NoReduction; 108 if (llvm::any_of(mapRange, 109 [](AffineMap m) { return !m.isProjectedPermutation(); })) 110 return MatchContractionResult::NotProjectedPermutations; 111 // TODO: more fields than add/mul. 112 if (!isAddMul<AddFOp, MulFOp>(linalgOp->getRegion(0).front()) && 113 !isAddMul<AddIOp, MulIOp>(linalgOp->getRegion(0).front())) 114 return MatchContractionResult::NotAddMul; 115 return MatchContractionResult::Success; 116 } 117 118 bool mlir::linalg::isaContractionOpInterface(LinalgOp linalgOp) { 119 if (!linalgOp) 120 return false; 121 Operation *op = linalgOp.getOperation(); 122 return isa<ContractionOpInterface>(op) || 123 (isContractionInterfaceImpl(op) == MatchContractionResult::Success); 124 } 125 126 /// Verify that a LinalgOp `op` is a contraction. 127 /// A Linalg contraction is defined in general terms: 128 /// 1. Has 2 input and 1 output shapes. 129 /// 2. Has at least one reduction dimension. 130 /// 3. Has only projected permutation indexing maps. 131 /// 4. its body computes `u5(u1(c) + u2(u3(a) * u4(b)))` on some field 132 /// (AddOpType, MulOpType), where u1, u2, u3, u4 and u5 represent scalar unary 133 /// operations that may change the type (e.g. for mixed-precision). 134 /// As a consequence, when vectorization of such an op occurs, the only special 135 /// behavior is that the (unique) MulOpType is vectorized into a 136 /// `vector.contract`. All other ops are handled in a generic fashion. 137 /// In the future, we may wish to allow more input arguments and elementwise and 138 /// constant operations that do not involve the reduction dimension(s). 139 LogicalResult mlir::linalg::detail::verifyContractionInterface(Operation *op) { 140 auto res = isContractionInterfaceImpl(op); 141 if (res == MatchContractionResult::NotLinalgOp) 142 return op->emitError("expected a LinalgOp"); 143 if (res == MatchContractionResult::WrongNumOperands) 144 return op->emitError("expected op with 2 inputs and 1 outputs"); 145 if (res == MatchContractionResult::NoReduction) 146 return op->emitError("expected at least a reduction loop"); 147 if (res == MatchContractionResult::NotProjectedPermutations) 148 return op->emitError("expected all indexings to be projected permutations"); 149 if (res == MatchContractionResult::NotAddMul) 150 return op->emitError("(add, mul) operations not found"); 151 return success(); 152 } 153 154 //===----------------------------------------------------------------------===// 155 // StructuredOpInterface implementation 156 //===----------------------------------------------------------------------===// 157 158 /// Fully compose map with operands and canonicalize the result. 159 /// Return the `createOrFold`'ed AffineApply op. 160 static Value createFoldedComposedAffineApply(OpBuilder &b, Location loc, 161 AffineMap map, 162 ValueRange operandsRef) { 163 SmallVector<Value, 4> operands(operandsRef.begin(), operandsRef.end()); 164 fullyComposeAffineMapAndOperands(&map, &operands); 165 canonicalizeMapAndOperands(&map, &operands); 166 return b.createOrFold<AffineApplyOp>(loc, map, operands); 167 } 168 169 SmallVector<Value, 4> mlir::linalg::applyMapToValues(OpBuilder &b, Location loc, 170 AffineMap map, 171 ValueRange values) { 172 SmallVector<Value, 4> res; 173 res.reserve(map.getNumResults()); 174 unsigned numDims = map.getNumDims(), numSym = map.getNumSymbols(); 175 // For each `expr` in `map`, applies the `expr` to the values extracted from 176 // ranges. If the resulting application can be folded into a Value, the 177 // folding occurs eagerly. 178 for (auto expr : map.getResults()) { 179 AffineMap map = AffineMap::get(numDims, numSym, expr); 180 res.push_back(createFoldedComposedAffineApply(b, loc, map, values)); 181 } 182 return res; 183 } 184 185 SmallVector<Value, 4> LinalgOp::createFlatListOfOperandDims(OpBuilder &b, 186 Location loc) { 187 SmallVector<Value, 4> res; 188 for (Value v : getShapedOperands()) { 189 ShapedType t = v.getType().template cast<ShapedType>(); 190 for (unsigned i = 0, e = t.getRank(); i < e; ++i) 191 res.push_back(b.create<memref::DimOp>(loc, v, i)); 192 } 193 return res; 194 } 195 196 SmallVector<Range, 4> LinalgOp::createLoopRanges(OpBuilder &b, Location loc) { 197 AffineMap map = getLoopsToShapesMap(); 198 unsigned numDims = map.getNumDims(), numRes = map.getNumResults(); 199 auto viewSizes = createFlatListOfOperandDims(b, loc); 200 SmallVector<Range, 4> res(numDims); 201 Value zeroVal = b.create<ConstantIndexOp>(loc, 0); 202 Value oneVal = b.create<ConstantIndexOp>(loc, 1); 203 for (unsigned idx = 0; idx < numRes; ++idx) { 204 auto result = map.getResult(idx); 205 if (auto d = result.dyn_cast<AffineDimExpr>()) { 206 if (res[d.getPosition()].offset) 207 continue; 208 res[d.getPosition()] = Range{zeroVal, viewSizes[idx], oneVal}; 209 } 210 } 211 return res; 212 } 213 214 /// Visitor to check if any of the given set of positions from AffineDimExprs 215 /// are used within an AffineExpr. 216 struct HasAffineDimExprVisitor 217 : public AffineExprVisitor<HasAffineDimExprVisitor, bool> { 218 HasAffineDimExprVisitor(llvm::SmallSet<unsigned, 4> &positions) 219 : positions(positions) {} 220 221 bool visitAffineBinaryOpExpr(AffineBinaryOpExpr binaryOpExpr) { 222 return visit(binaryOpExpr.getLHS()) || visit(binaryOpExpr.getRHS()); 223 } 224 225 bool visitDimExpr(AffineDimExpr dimExpr) { 226 return positions.count(dimExpr.getPosition()); 227 } 228 229 bool visitConstantExpr(AffineConstantExpr constExpr) { return false; } 230 231 bool visitSymbolExpr(AffineSymbolExpr symbolExpr) { return false; } 232 233 private: 234 llvm::SmallSet<unsigned, 4> positions; 235 }; 236 237 Optional<Value> LinalgOp::inferResultDimFromInputShapes(OpBuilder &b, 238 Location loc, 239 unsigned resultIdx, 240 unsigned dim) { 241 // An example that helps understand the logic below. 242 // Consider the following expression O(i+j, j) += A(i,k) * B(k, j) 243 // We want to express the shape of dim 0 of O in terms of shape of the inputs. 244 // This is achieved as follows. 245 // loopsToShapesMap = (d0, d1, d2) -> (d0, d2, d2, d1, d0 + d1, d1) 246 // subMapOfResultDim = (d0, d1, d2) -> (d0 + d1) 247 // shapesToLoopsMap = (d0, d2, d2, d3, d4, d5) -> (d0, d3, d2) 248 // resultFromFromInputDim = subMapOfResultDim.compose(shapesToLoopMap) 249 // = (d0, d1, d2, d3, d4, d5) -> (d0 + d1) 250 AffineMap loopsToShapesMap = getLoopsToShapesMap(); 251 252 // Find the position in the above map that represents the shape of the 253 // result:dim being inferred. 254 Optional<unsigned> resultDimSubMapPos = 255 getResultValueDimPositionInLoopsToShapeMap(resultIdx, dim); 256 if (!resultDimSubMapPos) 257 return {}; 258 259 /// From loopsToShapesMap extract the submap that represents the shape of the 260 /// (resultIdx, dim) needed 261 AffineMap loopToResultDimShapeMap = 262 loopsToShapesMap.getSubMap(*resultDimSubMapPos); 263 AffineMap operandShapesToResultDimMap = 264 loopToResultDimShapeMap.compose(getShapesToLoopsMap()); 265 266 // Check that the result dim map does not contain the positions corresponding 267 // to the outputs. 268 llvm::SmallSet<unsigned, 4> outputDims; 269 unsigned outputDimPosStart = 270 getResultValueDimPositionInLoopsToShapeMap(0, 0).getValue(); 271 unsigned outputDimPosEnd = 272 getResultValueDimPositionInLoopsToShapeMap(getNumOutputs() - 1, 273 getOutputOpOperands() 274 .back() 275 .get() 276 .getType() 277 .cast<ShapedType>() 278 .getRank() - 279 1) 280 .getValue(); 281 llvm::for_each(llvm::seq<unsigned>(outputDimPosStart, outputDimPosEnd), 282 [&outputDims](unsigned dim) { outputDims.insert(dim); }); 283 HasAffineDimExprVisitor checkDimExpr(outputDims); 284 if (checkDimExpr.visit(operandShapesToResultDimMap.getResult(0))) 285 return llvm::None; 286 return applyMapToValues(b, loc, operandShapesToResultDimMap, 287 createFlatListOfOperandDims(b, loc))[0]; 288 } 289 290 LogicalResult mlir::linalg::detail::verifyStructuredOpInterface(Operation *op) { 291 LinalgOp linalgOp = cast<LinalgOp>(op); 292 // Expect at least one shaped operand. 293 // This means an op that constructs a tensor out of indices cannot be a 294 // LinalgOp at the moment. For now this will have to be a special op until we 295 // have output shape operands that are not tensors. 296 auto nShapedOperands = linalgOp.getNumShapedOperands(); 297 if (nShapedOperands == 0) 298 return linalgOp.emitOpError("expected at least 1 Shaped operand"); 299 if (failed(OpTrait::impl::verifyAtLeastNOperands(op, nShapedOperands))) 300 return failure(); 301 // Should have at least one output tensor per result tensor. 302 // Can also have outbut buffers that do not correspond to results. 303 if (op->getNumResults() > linalgOp.getNumOutputTensors()) 304 return op->emitError("unexpected #results > #outputs"); 305 306 // Before checking indexing maps, we need to make sure the attributes 307 // referenced by it are valid. 308 if (linalgOp.hasDynamicIndexingMaps()) 309 if (failed(linalgOp.verifyIndexingMapRequiredAttributes())) 310 return failure(); 311 312 // All shaped operands must be indexed. 313 if (linalgOp.indexing_maps().size() != linalgOp.getNumShapedOperands()) 314 return linalgOp.emitOpError("expected the number of indexing_map (") 315 << linalgOp.indexing_maps().size() 316 << ") to be equal to the number of shaped operands (" 317 << linalgOp.getNumShapedOperands() << ")"; 318 319 SmallVector<AffineMap, 4> indexingMaps; 320 indexingMaps.reserve(linalgOp.indexing_maps().size()); 321 for (auto en : llvm::enumerate(linalgOp.indexing_maps())) { 322 auto idx = en.index(); 323 auto m = en.value().template cast<AffineMapAttr>().getValue(); 324 indexingMaps.push_back(m); // Save reference to map for further checks. 325 auto shapedValue = linalgOp.getShapedType(idx); 326 327 // Symbols disallowed. 328 if (m.getNumSymbols() != 0) 329 return linalgOp.emitOpError("unexpected symbols in indexing_map #") 330 << idx; 331 332 // Domain must be consistent. 333 auto nLoops = linalgOp.getNumLoops(); 334 if (m.getNumDims() != nLoops) 335 return linalgOp.emitOpError("expected indexing_map #") 336 << idx << " to have " << nLoops 337 << " dim(s) to match the number of loops"; 338 339 if (m.getNumResults() != shapedValue.getRank()) 340 return linalgOp.emitOpError("expected shaped value rank (") 341 << shapedValue.getRank() 342 << ") to match the result rank of indexing_map #" << idx << " (" 343 << m.getNumResults() << ")"; 344 } 345 346 SmallVector<AffineExpr, 4> redDims; 347 linalgOp.getReductionDims(redDims); 348 349 // Simplifying assumption: either full tensor or full buffer mode. 350 // This allows simpler verification of output operands vs result types 351 // without premature tracking of which operand is what in mixed-mode. 352 // TODO: relax when mixed-mode needs to pass verification. 353 if (linalgOp.getNumOutputBuffers() > 0 && linalgOp.getNumOutputTensors() > 0) 354 return op->emitError("expected output operands to all have tensor type or " 355 "all have buffer type"); 356 357 for (auto it : 358 llvm::zip(linalgOp.getOutputOpOperands(), op->getResultTypes())) { 359 if (!std::get<0>(it).get().getType().isa<RankedTensorType>()) 360 continue; 361 if (std::get<0>(it).get().getType() != std::get<1>(it)) 362 return op->emitError("expected type of operand #") 363 << std::get<0>(it).getOperandNumber() << " (" 364 << std::get<0>(it).get().getType() << ")" 365 << " to match type of corresponding result (" << std::get<1>(it) 366 << ")"; 367 } 368 369 // Output tensor indexing map may not depend on reduction indices. 370 for (OpOperand &opOperand : linalgOp.getOutputOpOperands()) { 371 AffineMap outputMap = linalgOp.getIndexingMap(opOperand.getOperandNumber()); 372 for (auto expr : outputMap.getResults()) { 373 for (auto dim : redDims) { 374 unsigned pos = dim.cast<AffineDimExpr>().getPosition(); 375 if (expr.isFunctionOfDim(pos)) { 376 std::string exprStr; 377 { 378 llvm::raw_string_ostream os(exprStr); 379 os << expr; 380 } 381 return op->emitError( 382 "unexpected output tensor expression in indexing map #") 383 << (opOperand.getOperandNumber() - linalgOp.getNumInputs()) 384 << " a.k.a '" << exprStr 385 << "' is function of reduction iterator 'd" << pos << "'"; 386 } 387 } 388 } 389 } 390 391 // Named ops that are defined manually have a region builder but no region at 392 // this time. Assume the region is well-formed by specification. 393 // TODO: use linalg-ods-gen for all ops when we have enough expressive power. 394 if (linalgOp->getNumRegions() == 0) { 395 assert(!linalgOp.getRegionBuilder() && "regionBuilder but no region"); 396 return success(); 397 } 398 399 auto ®ion = linalgOp->getRegion(0); 400 if (linalgOp->getNumRegions() > 1 || !llvm::hasSingleElement(region)) 401 return op->emitOpError("expected 1 region with 1 block"); 402 403 if (!linalgOp.getShapesToLoopsMap()) 404 return op->emitOpError("expected the shape-to-loops map to be non-null"); 405 406 // Simplifying assumption: bbargs match 1-1 with shape operands elemental 407 // types. 408 // TODO: once ranked shape types are plugged in, we may want to drop the 409 // corresponding bbargs, that can never be read from. This will be subject to 410 // consistency discussions (i.e. what to do with output tensors whose bbarg is 411 // not used). 412 Block &block = linalgOp->getRegion(0).front(); 413 unsigned numBBIvs = linalgOp.getNumPayloadInductionVariables(); 414 415 if (linalgOp.getNumShapedOperands() + numBBIvs != block.getNumArguments()) 416 return op->emitError("expected as many non-induction variable region " 417 "arguments as the number of shaped operands"); 418 419 // Note: the number and type of yield values are checked in the YieldOp. 420 for (unsigned i = 0; i < numBBIvs; ++i) 421 if (!block.getArgument(i).getType().isIndex()) 422 return op->emitOpError("expected index block argument #") << i; 423 424 unsigned idx = 0; 425 for (auto it : llvm::zip(linalgOp.getShapedOperandTypes(), 426 block.getArguments().drop_front(numBBIvs))) { 427 if (std::get<0>(it).getElementType() != std::get<1>(it).getType()) 428 return op->emitError("expected type of bb argument #") 429 << (idx + numBBIvs) << " (" << std::get<1>(it).getType() << ")" 430 << " to match element type of corresponding shaped operand (" 431 << std::get<0>(it).getElementType() << ")"; 432 ++idx; 433 } 434 435 return success(); 436 } 437