1 //===----------------------------------------------------------------------===// 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/Arithmetic/IR/Arithmetic.h" 10 #include "mlir/Dialect/Arithmetic/Utils/Utils.h" 11 #include "mlir/Dialect/Complex/IR/Complex.h" 12 #include "mlir/Dialect/Tensor/IR/Tensor.h" 13 #include "mlir/Dialect/Utils/ReshapeOpsUtils.h" 14 #include "mlir/Dialect/Utils/StaticValueUtils.h" 15 #include "mlir/IR/BlockAndValueMapping.h" 16 #include "mlir/IR/Builders.h" 17 #include "mlir/IR/BuiltinAttributeInterfaces.h" 18 #include "mlir/IR/Matchers.h" 19 #include "mlir/IR/PatternMatch.h" 20 #include "mlir/IR/TypeUtilities.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/SmallBitVector.h" 23 24 using namespace mlir; 25 using namespace mlir::tensor; 26 27 /// Materialize a single constant operation from a given attribute value with 28 /// the desired resultant type. 29 Operation *TensorDialect::materializeConstant(OpBuilder &builder, 30 Attribute value, Type type, 31 Location loc) { 32 if (arith::ConstantOp::isBuildableWith(value, type)) 33 return builder.create<arith::ConstantOp>(loc, value, type); 34 if (complex::ConstantOp::isBuildableWith(value, type)) 35 return builder.create<complex::ConstantOp>(loc, type, 36 value.cast<ArrayAttr>()); 37 return nullptr; 38 } 39 40 //===----------------------------------------------------------------------===// 41 // CastOp 42 //===----------------------------------------------------------------------===// 43 44 /// Returns true if `target` is a ranked tensor type that preserves static 45 /// information available in the `source` ranked tensor type. 46 bool mlir::tensor::preservesStaticInformation(Type source, Type target) { 47 auto sourceType = source.dyn_cast<RankedTensorType>(); 48 auto targetType = target.dyn_cast<RankedTensorType>(); 49 50 // Requires RankedTensorType. 51 if (!sourceType || !targetType) 52 return false; 53 54 // Requires same elemental type. 55 if (sourceType.getElementType() != targetType.getElementType()) 56 return false; 57 58 // Requires same rank. 59 if (sourceType.getRank() != targetType.getRank()) 60 return false; 61 62 // If cast is towards more static sizes along any dimension, don't fold. 63 for (auto t : llvm::zip(sourceType.getShape(), targetType.getShape())) { 64 if (!ShapedType::isDynamic(std::get<0>(t)) && 65 ShapedType::isDynamic(std::get<1>(t))) 66 return false; 67 } 68 69 return true; 70 } 71 72 /// Determines whether tensor::CastOp casts to a more dynamic version of the 73 /// source tensor. This is useful to fold a tensor.cast into a consuming op and 74 /// implement canonicalization patterns for ops in different dialects that may 75 /// consume the results of tensor.cast operations. Such foldable tensor.cast 76 /// operations are typically inserted as `slice` ops and are canonicalized, 77 /// to preserve the type compatibility of their uses. 78 /// 79 /// Returns true when all conditions are met: 80 /// 1. source and result are ranked tensors with same element type and rank. 81 /// 2. the tensor type has more static information than the result 82 /// 83 /// Example: 84 /// ```mlir 85 /// %1 = tensor.cast %0 : tensor<8x16xf32> to tensor<?x?xf32> 86 /// %2 = consumer %1 ... : tensor<?x?xf32> ... 87 /// ``` 88 /// 89 /// folds into: 90 /// 91 /// ```mlir 92 /// %2 = consumer %0 ... : tensor<8x16xf32> ... 93 /// ``` 94 bool mlir::tensor::canFoldIntoConsumerOp(CastOp castOp) { 95 if (!castOp) 96 return false; 97 98 // Can fold if the source of cast has at least as much static information as 99 // its results. 100 return preservesStaticInformation(castOp.getType(), 101 castOp.source().getType()); 102 } 103 104 /// Performs folding of any operand of `op` if it comes from a tensor::CastOp 105 /// that can be folded. 106 LogicalResult mlir::tensor::foldTensorCast(Operation *op) { 107 bool folded = false; 108 for (OpOperand &operand : op->getOpOperands()) { 109 auto castOp = operand.get().getDefiningOp<tensor::CastOp>(); 110 if (castOp && tensor::canFoldIntoConsumerOp(castOp)) { 111 operand.set(castOp.getOperand()); 112 folded = true; 113 } 114 } 115 return success(folded); 116 } 117 118 bool CastOp::areCastCompatible(TypeRange inputs, TypeRange outputs) { 119 if (inputs.size() != 1 || outputs.size() != 1) 120 return false; 121 Type a = inputs.front(), b = outputs.front(); 122 auto aT = a.dyn_cast<TensorType>(); 123 auto bT = b.dyn_cast<TensorType>(); 124 if (!aT || !bT) 125 return false; 126 127 if (aT.getElementType() != bT.getElementType()) 128 return false; 129 130 return succeeded(verifyCompatibleShape(aT, bT)); 131 } 132 133 /// Compute a TensorType that has the joined shape knowledge of the two 134 /// given TensorTypes. The element types need to match. 135 static TensorType joinShapes(TensorType one, TensorType two) { 136 assert(one.getElementType() == two.getElementType()); 137 138 if (!one.hasRank()) 139 return two; 140 if (!two.hasRank()) 141 return one; 142 143 int64_t rank = one.getRank(); 144 if (rank != two.getRank()) 145 return {}; 146 147 SmallVector<int64_t, 4> join; 148 join.reserve(rank); 149 for (int64_t i = 0; i < rank; ++i) { 150 if (one.isDynamicDim(i)) { 151 join.push_back(two.getDimSize(i)); 152 continue; 153 } 154 if (two.isDynamicDim(i)) { 155 join.push_back(one.getDimSize(i)); 156 continue; 157 } 158 if (one.getDimSize(i) != two.getDimSize(i)) 159 return {}; 160 join.push_back(one.getDimSize(i)); 161 } 162 return RankedTensorType::get(join, one.getElementType()); 163 } 164 165 namespace { 166 167 /// Replaces chains of two tensor.cast operations by a single tensor.cast 168 /// operation if doing so does not remove runtime constraints. 169 struct ChainedTensorCast : public OpRewritePattern<CastOp> { 170 using OpRewritePattern<CastOp>::OpRewritePattern; 171 172 LogicalResult matchAndRewrite(CastOp tensorCast, 173 PatternRewriter &rewriter) const final { 174 auto tensorCastOperand = tensorCast.getOperand().getDefiningOp<CastOp>(); 175 176 if (!tensorCastOperand) 177 return failure(); 178 179 auto sourceType = 180 tensorCastOperand.getOperand().getType().cast<TensorType>(); 181 auto intermediateType = tensorCastOperand.getType().cast<TensorType>(); 182 auto resultType = tensorCast.getType().cast<TensorType>(); 183 184 // We can remove the intermediate cast if joining all three produces the 185 // same result as just joining the source and result shapes. 186 auto firstJoin = 187 joinShapes(joinShapes(sourceType, intermediateType), resultType); 188 189 // The join might not exist if the cast sequence would fail at runtime. 190 if (!firstJoin) 191 return failure(); 192 193 // The newJoin always exists if the above join exists, it might just contain 194 // less information. If so, we cannot drop the intermediate cast, as doing 195 // so would remove runtime checks. 196 auto newJoin = joinShapes(sourceType, resultType); 197 if (firstJoin != newJoin) 198 return failure(); 199 200 rewriter.replaceOpWithNewOp<CastOp>(tensorCast, resultType, 201 tensorCastOperand.getOperand()); 202 return success(); 203 } 204 }; 205 206 } // namespace 207 208 void CastOp::getCanonicalizationPatterns(RewritePatternSet &results, 209 MLIRContext *context) { 210 results.add<ChainedTensorCast>(context); 211 } 212 213 //===----------------------------------------------------------------------===// 214 // DimOp 215 //===----------------------------------------------------------------------===// 216 217 void DimOp::build(OpBuilder &builder, OperationState &result, Value source, 218 int64_t index) { 219 auto loc = result.location; 220 Value indexValue = builder.create<arith::ConstantIndexOp>(loc, index); 221 build(builder, result, source, indexValue); 222 } 223 224 Optional<int64_t> DimOp::getConstantIndex() { 225 if (auto constantOp = index().getDefiningOp<arith::ConstantOp>()) 226 return constantOp.getValue().cast<IntegerAttr>().getInt(); 227 return {}; 228 } 229 230 LogicalResult DimOp::verify() { 231 // Assume unknown index to be in range. 232 Optional<int64_t> index = getConstantIndex(); 233 if (!index.hasValue()) 234 return success(); 235 236 // Check that constant index is not knowingly out of range. 237 auto type = source().getType(); 238 if (auto tensorType = type.dyn_cast<RankedTensorType>()) { 239 if (index.getValue() >= tensorType.getRank()) 240 return emitOpError("index is out of range"); 241 } else if (type.isa<UnrankedTensorType>()) { 242 // Assume index to be in range. 243 } else { 244 llvm_unreachable("expected operand with tensor type"); 245 } 246 return success(); 247 } 248 249 OpFoldResult DimOp::fold(ArrayRef<Attribute> operands) { 250 // All forms of folding require a known index. 251 auto index = operands[1].dyn_cast_or_null<IntegerAttr>(); 252 if (!index) 253 return {}; 254 255 // Folding for unranked types (UnrankedTensorType) is not supported. 256 auto tensorType = source().getType().dyn_cast<RankedTensorType>(); 257 if (!tensorType) 258 return {}; 259 260 // Fold if the shape extent along the given index is known. 261 if (!tensorType.isDynamicDim(index.getInt())) { 262 Builder builder(getContext()); 263 return builder.getIndexAttr(tensorType.getShape()[index.getInt()]); 264 } 265 266 Operation *definingOp = source().getDefiningOp(); 267 268 // Fold dim to the operand of tensor.generate. 269 if (auto fromElements = dyn_cast_or_null<tensor::GenerateOp>(definingOp)) { 270 auto resultType = 271 fromElements.getResult().getType().cast<RankedTensorType>(); 272 // The case where the type encodes the size of the dimension is handled 273 // above. 274 assert(ShapedType::isDynamic(resultType.getShape()[index.getInt()])); 275 276 // Find the operand of the fromElements that corresponds to this index. 277 auto dynExtents = fromElements.dynamicExtents().begin(); 278 for (auto dim : resultType.getShape().take_front(index.getInt())) 279 if (ShapedType::isDynamic(dim)) 280 dynExtents++; 281 282 return Value{*dynExtents}; 283 } 284 285 // The size at the given index is now known to be a dynamic size. 286 unsigned unsignedIndex = index.getValue().getZExtValue(); 287 288 if (auto sliceOp = dyn_cast_or_null<tensor::ExtractSliceOp>(definingOp)) { 289 // Fold only for non-rank reduced ops. For the rank-reduced version, rely on 290 // `resolve-shaped-type-result-dims` pass. 291 if (sliceOp.getType().getRank() == sliceOp.getSourceType().getRank() && 292 sliceOp.isDynamicSize(unsignedIndex)) { 293 return {sliceOp.getDynamicSize(unsignedIndex)}; 294 } 295 } 296 297 // dim(cast) -> dim 298 if (succeeded(foldTensorCast(*this))) 299 return getResult(); 300 301 return {}; 302 } 303 304 namespace { 305 /// Fold dim of a cast into the dim of the source of the tensor cast. 306 struct DimOfCastOp : public OpRewritePattern<DimOp> { 307 using OpRewritePattern<DimOp>::OpRewritePattern; 308 309 LogicalResult matchAndRewrite(DimOp dimOp, 310 PatternRewriter &rewriter) const override { 311 auto castOp = dimOp.source().getDefiningOp<CastOp>(); 312 if (!castOp) 313 return failure(); 314 Value newSource = castOp.getOperand(); 315 rewriter.replaceOpWithNewOp<DimOp>(dimOp, newSource, dimOp.index()); 316 return success(); 317 } 318 }; 319 } // namespace 320 321 void DimOp::getCanonicalizationPatterns(RewritePatternSet &results, 322 MLIRContext *context) { 323 results.add<DimOfCastOp>(context); 324 } 325 326 //===----------------------------------------------------------------------===// 327 // ExtractOp 328 //===----------------------------------------------------------------------===// 329 330 LogicalResult ExtractOp::verify() { 331 // Verify the # indices match if we have a ranked type. 332 if (auto tensorType = tensor().getType().dyn_cast<RankedTensorType>()) 333 if (tensorType.getRank() != static_cast<int64_t>(indices().size())) 334 return emitOpError("incorrect number of indices for extract_element"); 335 336 return success(); 337 } 338 339 OpFoldResult ExtractOp::fold(ArrayRef<Attribute> operands) { 340 // The tensor operand must be a known constant. 341 Attribute tensor = operands.front(); 342 if (!tensor) 343 return {}; 344 // If this is a splat elements attribute, simply return the value. All of the 345 // elements of a splat attribute are the same. 346 if (auto splatTensor = tensor.dyn_cast<SplatElementsAttr>()) 347 return splatTensor.getSplatValue<Attribute>(); 348 349 // Otherwise, collect the constant indices into the tensor. 350 SmallVector<uint64_t, 8> indices; 351 for (Attribute indice : llvm::drop_begin(operands, 1)) { 352 if (!indice || !indice.isa<IntegerAttr>()) 353 return {}; 354 indices.push_back(indice.cast<IntegerAttr>().getInt()); 355 } 356 357 // If this is an elements attribute, query the value at the given indices. 358 auto elementsAttr = tensor.dyn_cast<ElementsAttr>(); 359 if (elementsAttr && elementsAttr.isValidIndex(indices)) 360 return elementsAttr.getValues<Attribute>()[indices]; 361 return {}; 362 } 363 364 //===----------------------------------------------------------------------===// 365 // FromElementsOp 366 //===----------------------------------------------------------------------===// 367 368 void FromElementsOp::build(OpBuilder &builder, OperationState &result, 369 Type resultType, ValueRange elements) { 370 result.addOperands(elements); 371 result.addTypes(resultType); 372 } 373 374 void FromElementsOp::build(OpBuilder &builder, OperationState &result, 375 ValueRange elements) { 376 assert(!elements.empty() && "expected at least one element"); 377 Type resultType = RankedTensorType::get( 378 {static_cast<int64_t>(elements.size())}, elements.front().getType()); 379 build(builder, result, resultType, elements); 380 } 381 382 OpFoldResult FromElementsOp::fold(ArrayRef<Attribute> operands) { 383 if (!llvm::is_contained(operands, nullptr)) 384 return DenseElementsAttr::get(getType(), operands); 385 return {}; 386 } 387 388 namespace { 389 390 // Canonicalizes the pattern of the form 391 // 392 // %tensor = tensor.from_elements(%element) : (i32) -> tensor<1xi32> 393 // %extracted_element = tensor.extract %tensor[%c0] : tensor<1xi32> 394 // 395 // to just %element. 396 struct ExtractElementFromTensorFromElements 397 : public OpRewritePattern<tensor::ExtractOp> { 398 using OpRewritePattern<tensor::ExtractOp>::OpRewritePattern; 399 400 LogicalResult matchAndRewrite(tensor::ExtractOp extract, 401 PatternRewriter &rewriter) const final { 402 auto tensorFromElements = extract.tensor().getDefiningOp<FromElementsOp>(); 403 if (!tensorFromElements) 404 return failure(); 405 auto tensorType = tensorFromElements.getType().cast<RankedTensorType>(); 406 auto rank = tensorType.getRank(); 407 if (rank == 0) { 408 rewriter.replaceOp(extract, tensorFromElements.getOperand(0)); 409 return success(); 410 } 411 SmallVector<APInt, 3> indices(rank); 412 int64_t flatIndex = 0; 413 int64_t stride = 1; 414 for (int i = rank - 1; i >= 0; --i) { 415 APInt index; 416 if (!matchPattern(extract.indices()[i], m_ConstantInt(&index))) 417 return failure(); 418 if (i < rank - 1) 419 stride *= tensorType.getDimSize(i); 420 flatIndex += index.getSExtValue() * stride; 421 } 422 // Prevent out of bounds accesses. This can happen in invalid code that will 423 // never execute. 424 if (tensorFromElements->getNumOperands() <= flatIndex || flatIndex < 0) 425 return failure(); 426 rewriter.replaceOp(extract, tensorFromElements.getOperand(flatIndex)); 427 return success(); 428 } 429 }; 430 431 // Pushes the index_casts that occur before extractions to after the extract. 432 // This minimizes type conversion in some cases and enables the extract 433 // canonicalizer. This changes: 434 // 435 // %cast = arith.index_cast %tensor : tensor<1xi32> to tensor<1xindex> 436 // %extract = tensor.extract %cast[%index] : tensor<1xindex> 437 // 438 // to the following: 439 // 440 // %extract = tensor.extract %tensor[%index] : tensor<1xindex> 441 // %cast = arith.index_cast %extract : i32 to index 442 // 443 // to just %element. 444 // 445 // Consider expanding this to a template and handle all tensor cast operations. 446 struct ExtractElementFromIndexCast 447 : public OpRewritePattern<tensor::ExtractOp> { 448 using OpRewritePattern<tensor::ExtractOp>::OpRewritePattern; 449 450 LogicalResult matchAndRewrite(tensor::ExtractOp extract, 451 PatternRewriter &rewriter) const final { 452 Location loc = extract.getLoc(); 453 auto indexCast = extract.tensor().getDefiningOp<arith::IndexCastOp>(); 454 if (!indexCast) 455 return failure(); 456 457 Type elementTy = getElementTypeOrSelf(indexCast.getIn()); 458 459 auto newExtract = rewriter.create<tensor::ExtractOp>( 460 loc, elementTy, indexCast.getIn(), extract.indices()); 461 462 rewriter.replaceOpWithNewOp<arith::IndexCastOp>(extract, extract.getType(), 463 newExtract); 464 465 return success(); 466 } 467 }; 468 469 } // namespace 470 471 void FromElementsOp::getCanonicalizationPatterns(RewritePatternSet &results, 472 MLIRContext *context) { 473 results 474 .add<ExtractElementFromIndexCast, ExtractElementFromTensorFromElements>( 475 context); 476 } 477 478 //===----------------------------------------------------------------------===// 479 // InsertOp 480 //===----------------------------------------------------------------------===// 481 482 LogicalResult InsertOp::verify() { 483 // Verify the # indices match if we have a ranked type. 484 if (auto destType = dest().getType().dyn_cast<RankedTensorType>()) 485 if (destType.getRank() != static_cast<int64_t>(indices().size())) 486 return emitOpError("incorrect number of indices"); 487 return success(); 488 } 489 490 OpFoldResult InsertOp::fold(ArrayRef<Attribute> operands) { 491 Attribute scalar = operands[0]; 492 Attribute dest = operands[1]; 493 if (scalar && dest) 494 if (auto splatDest = dest.dyn_cast<SplatElementsAttr>()) 495 if (scalar == splatDest.getSplatValue<Attribute>()) 496 return dest; 497 return {}; 498 } 499 500 //===----------------------------------------------------------------------===// 501 // GenerateOp 502 //===----------------------------------------------------------------------===// 503 504 LogicalResult GenerateOp::verify() { 505 // Ensure that the tensor type has as many dynamic dimensions as are specified 506 // by the operands. 507 RankedTensorType resultTy = getType().cast<RankedTensorType>(); 508 if (getNumOperands() != resultTy.getNumDynamicDims()) 509 return emitError("must have as many index operands as dynamic extents " 510 "in the result type"); 511 512 // Ensure that region arguments span the index space. 513 if (!llvm::all_of(body().getArgumentTypes(), 514 [](Type ty) { return ty.isIndex(); })) 515 return emitError("all body arguments must be index"); 516 if (body().getNumArguments() != resultTy.getRank()) 517 return emitError("must have one body argument per input dimension"); 518 519 // Ensure that the region yields an element of the right type. 520 auto yieldOp = cast<YieldOp>(body().getBlocks().front().getTerminator()); 521 522 if (yieldOp.value().getType() != resultTy.getElementType()) 523 return emitOpError( 524 "body must be terminated with a `yield` operation of the tensor " 525 "element type"); 526 527 return success(); 528 } 529 530 void GenerateOp::build( 531 OpBuilder &b, OperationState &result, Type resultTy, 532 ValueRange dynamicExtents, 533 function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilder) { 534 build(b, result, resultTy, dynamicExtents); 535 536 // Build and populate body. 537 OpBuilder::InsertionGuard guard(b); 538 Region *bodyRegion = result.regions.front().get(); 539 auto rank = resultTy.cast<RankedTensorType>().getRank(); 540 SmallVector<Type, 2> argumentTypes(rank, b.getIndexType()); 541 SmallVector<Location, 2> argumentLocs(rank, result.location); 542 Block *bodyBlock = 543 b.createBlock(bodyRegion, bodyRegion->end(), argumentTypes, argumentLocs); 544 bodyBuilder(b, result.location, bodyBlock->getArguments()); 545 } 546 547 namespace { 548 549 /// Canonicalizes tensor.generate operations with a constant 550 /// operand into the equivalent operation with the operand expressed in the 551 /// result type, instead. We also insert a type cast to make sure that the 552 /// resulting IR is still well-typed. 553 struct StaticTensorGenerate : public OpRewritePattern<GenerateOp> { 554 using OpRewritePattern<GenerateOp>::OpRewritePattern; 555 556 LogicalResult matchAndRewrite(GenerateOp tensorFromElements, 557 PatternRewriter &rewriter) const final { 558 auto resultType = 559 tensorFromElements.getResult().getType().cast<RankedTensorType>(); 560 561 if (resultType.hasStaticShape()) 562 return failure(); 563 564 SmallVector<Value, 4> newOperands; 565 SmallVector<int64_t, 4> newShape; 566 auto operandsIt = tensorFromElements.dynamicExtents().begin(); 567 568 for (int64_t dim : resultType.getShape()) { 569 if (!ShapedType::isDynamic(dim)) { 570 newShape.push_back(dim); 571 continue; 572 } 573 APInt index; 574 if (!matchPattern(*operandsIt, m_ConstantInt(&index))) { 575 newShape.push_back(ShapedType::kDynamicSize); 576 newOperands.push_back(*operandsIt++); 577 continue; 578 } 579 newShape.push_back(index.getSExtValue()); 580 operandsIt++; 581 } 582 583 if (newOperands.size() == tensorFromElements.dynamicExtents().size()) 584 return failure(); 585 586 auto loc = tensorFromElements.getLoc(); 587 auto newOp = rewriter.create<GenerateOp>( 588 loc, RankedTensorType::get(newShape, resultType.getElementType()), 589 newOperands); 590 rewriter.inlineRegionBefore(tensorFromElements.body(), newOp.body(), 591 newOp.body().begin()); 592 rewriter.replaceOpWithNewOp<tensor::CastOp>(tensorFromElements, resultType, 593 newOp); 594 return success(); 595 } 596 }; 597 598 /// Canonicalizes the pattern of the form 599 /// 600 /// %tensor = tensor.generate %x { 601 /// ^bb0(%arg0: index): 602 /// <computation> 603 /// yield %1 : index 604 /// } : tensor<?xindex> 605 /// %extracted_element = tensor.extract %tensor[%c0] : tensor<?xi32> 606 /// 607 /// to just <computation> with %arg0 replaced by %c0. We only do this if the 608 /// tensor.generate operation has no side-effects. 609 struct ExtractFromTensorGenerate : public OpRewritePattern<tensor::ExtractOp> { 610 using OpRewritePattern<tensor::ExtractOp>::OpRewritePattern; 611 612 LogicalResult matchAndRewrite(tensor::ExtractOp extract, 613 PatternRewriter &rewriter) const final { 614 auto tensorFromElements = extract.tensor().getDefiningOp<GenerateOp>(); 615 if (!tensorFromElements || !wouldOpBeTriviallyDead(tensorFromElements)) 616 return failure(); 617 618 BlockAndValueMapping mapping; 619 Block *body = tensorFromElements.getBody(); 620 mapping.map(body->getArguments(), extract.indices()); 621 for (auto &op : body->without_terminator()) 622 rewriter.clone(op, mapping); 623 624 auto yield = cast<YieldOp>(body->getTerminator()); 625 626 rewriter.replaceOp(extract, mapping.lookupOrDefault(yield.value())); 627 return success(); 628 } 629 }; 630 631 /// Canonicalizes the pattern of the form 632 /// 633 /// %val = tensor.cast %source : : tensor<?xi32> to tensor<2xi32> 634 /// %extracted_element = tensor.extract %val[%c0] : tensor<2xi32> 635 /// 636 /// to 637 /// 638 /// %extracted_element = tensor.extract %source[%c0] : tensor<?xi32> 639 struct ExtractFromTensorCast : public OpRewritePattern<tensor::ExtractOp> { 640 using OpRewritePattern<tensor::ExtractOp>::OpRewritePattern; 641 642 LogicalResult matchAndRewrite(tensor::ExtractOp extract, 643 PatternRewriter &rewriter) const final { 644 auto tensorCast = extract.tensor().getDefiningOp<tensor::CastOp>(); 645 if (!tensorCast) 646 return failure(); 647 648 rewriter.replaceOpWithNewOp<tensor::ExtractOp>(extract, tensorCast.source(), 649 extract.indices()); 650 return success(); 651 } 652 }; 653 654 } // namespace 655 656 void GenerateOp::getCanonicalizationPatterns(RewritePatternSet &results, 657 MLIRContext *context) { 658 // TODO: Move extract patterns to tensor::ExtractOp. 659 results.add<ExtractFromTensorGenerate, ExtractFromTensorCast, 660 StaticTensorGenerate>(context); 661 } 662 663 //===----------------------------------------------------------------------===// 664 // RankOp 665 //===----------------------------------------------------------------------===// 666 667 OpFoldResult RankOp::fold(ArrayRef<Attribute> operands) { 668 // Constant fold rank when the rank of the operand is known. 669 auto type = getOperand().getType(); 670 auto shapedType = type.dyn_cast<ShapedType>(); 671 if (shapedType && shapedType.hasRank()) 672 return IntegerAttr::get(IndexType::get(getContext()), shapedType.getRank()); 673 return IntegerAttr(); 674 } 675 676 //===----------------------------------------------------------------------===// 677 // ReshapeOp 678 //===----------------------------------------------------------------------===// 679 680 static int64_t getNumElements(ShapedType type) { 681 int64_t numElements = 1; 682 for (auto dim : type.getShape()) 683 numElements *= dim; 684 return numElements; 685 } 686 687 LogicalResult ReshapeOp::verify() { 688 TensorType operandType = source().getType().cast<TensorType>(); 689 TensorType resultType = result().getType().cast<TensorType>(); 690 691 if (operandType.getElementType() != resultType.getElementType()) 692 return emitOpError("element types of source and destination tensor " 693 "types should be the same"); 694 695 int64_t shapeSize = shape().getType().cast<RankedTensorType>().getDimSize(0); 696 auto resultRankedType = resultType.dyn_cast<RankedTensorType>(); 697 auto operandRankedType = operandType.dyn_cast<RankedTensorType>(); 698 699 if (resultRankedType) { 700 if (operandRankedType && resultRankedType.hasStaticShape() && 701 operandRankedType.hasStaticShape()) { 702 if (getNumElements(operandRankedType) != getNumElements(resultRankedType)) 703 return emitOpError("source and destination tensor should have the " 704 "same number of elements"); 705 } 706 if (ShapedType::isDynamic(shapeSize)) 707 return emitOpError("cannot use shape operand with dynamic length to " 708 "reshape to statically-ranked tensor type"); 709 if (shapeSize != resultRankedType.getRank()) 710 return emitOpError( 711 "length of shape operand differs from the result's tensor rank"); 712 } 713 return success(); 714 } 715 716 //===----------------------------------------------------------------------===// 717 // Reassociative reshape ops 718 //===----------------------------------------------------------------------===// 719 720 SmallVector<AffineMap, 4> CollapseShapeOp::getReassociationMaps() { 721 return getSymbolLessAffineMaps(getReassociationExprs()); 722 } 723 SmallVector<ReassociationExprs, 4> CollapseShapeOp::getReassociationExprs() { 724 return convertReassociationIndicesToExprs(getContext(), 725 getReassociationIndices()); 726 } 727 728 SmallVector<AffineMap, 4> ExpandShapeOp::getReassociationMaps() { 729 return getSymbolLessAffineMaps(getReassociationExprs()); 730 } 731 SmallVector<ReassociationExprs, 4> ExpandShapeOp::getReassociationExprs() { 732 return convertReassociationIndicesToExprs(getContext(), 733 getReassociationIndices()); 734 } 735 736 /// Compute the RankedTensorType obtained by applying `reassociation` to `type`. 737 static RankedTensorType 738 computeTensorReshapeCollapsedType(RankedTensorType type, 739 ArrayRef<AffineMap> reassociation) { 740 auto shape = type.getShape(); 741 SmallVector<int64_t, 4> newShape; 742 newShape.reserve(reassociation.size()); 743 744 // Use the fact that reassociation is valid to simplify the logic: only use 745 // each map's rank. 746 assert(isReassociationValid(reassociation) && "invalid reassociation"); 747 unsigned currentDim = 0; 748 for (AffineMap m : reassociation) { 749 unsigned dim = m.getNumResults(); 750 auto band = shape.slice(currentDim, dim); 751 int64_t size = 1; 752 if (llvm::is_contained(band, ShapedType::kDynamicSize)) 753 size = ShapedType::kDynamicSize; 754 else 755 for (unsigned d = 0; d < dim; ++d) 756 size *= shape[currentDim + d]; 757 newShape.push_back(size); 758 currentDim += dim; 759 } 760 761 return RankedTensorType::get(newShape, type.getElementType()); 762 } 763 764 void CollapseShapeOp::build(OpBuilder &b, OperationState &result, Value src, 765 ArrayRef<ReassociationIndices> reassociation, 766 ArrayRef<NamedAttribute> attrs) { 767 auto resultType = computeTensorReshapeCollapsedType( 768 src.getType().cast<RankedTensorType>(), 769 getSymbolLessAffineMaps( 770 convertReassociationIndicesToExprs(b.getContext(), reassociation))); 771 build(b, result, resultType, src, attrs); 772 result.addAttribute(getReassociationAttrName(), 773 getReassociationIndicesAttribute(b, reassociation)); 774 } 775 776 void ExpandShapeOp::build(OpBuilder &b, OperationState &result, Value src, 777 ArrayRef<ReassociationIndices> reassociation, 778 ArrayRef<NamedAttribute> attrs) { 779 auto resultType = computeTensorReshapeCollapsedType( 780 src.getType().cast<RankedTensorType>(), 781 getSymbolLessAffineMaps( 782 convertReassociationIndicesToExprs(b.getContext(), reassociation))); 783 build(b, result, resultType, src, attrs); 784 result.addAttribute(getReassociationAttrName(), 785 getReassociationIndicesAttribute(b, reassociation)); 786 } 787 788 template <typename TensorReshapeOp, bool isExpansion = std::is_same< 789 TensorReshapeOp, ExpandShapeOp>::value> 790 static LogicalResult verifyTensorReshapeOp(TensorReshapeOp op, 791 RankedTensorType expandedType, 792 RankedTensorType collapsedType) { 793 if (failed( 794 verifyReshapeLikeTypes(op, expandedType, collapsedType, isExpansion))) 795 return failure(); 796 797 auto maps = op.getReassociationMaps(); 798 RankedTensorType expectedType = 799 computeTensorReshapeCollapsedType(expandedType, maps); 800 if (collapsedType != expectedType) 801 return op.emitOpError("expected collapsed type to be ") 802 << expectedType << ", but got " << collapsedType; 803 return success(); 804 } 805 806 LogicalResult ExpandShapeOp::verify() { 807 return verifyTensorReshapeOp(*this, getResultType(), getSrcType()); 808 } 809 810 LogicalResult CollapseShapeOp::verify() { 811 return verifyTensorReshapeOp(*this, getSrcType(), getResultType()); 812 } 813 814 namespace { 815 /// Reshape of a splat constant can be replaced with a constant of the result 816 /// type. 817 template <typename TensorReshapeOp> 818 struct FoldReshapeWithConstant : OpRewritePattern<TensorReshapeOp> { 819 using OpRewritePattern<TensorReshapeOp>::OpRewritePattern; 820 LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp, 821 PatternRewriter &rewriter) const override { 822 DenseElementsAttr attr; 823 if (!matchPattern(reshapeOp.src(), m_Constant(&attr))) 824 return failure(); 825 if (!attr || !attr.isSplat()) 826 return failure(); 827 DenseElementsAttr newAttr = DenseElementsAttr::getFromRawBuffer( 828 reshapeOp.getResultType(), attr.getRawData(), true); 829 rewriter.replaceOpWithNewOp<arith::ConstantOp>(reshapeOp, newAttr); 830 return success(); 831 } 832 }; 833 834 /// Reshape of a FromElements can be replaced with a FromElements of the result 835 /// type 836 template <typename TensorReshapeOp> 837 struct FoldReshapeWithFromElements : OpRewritePattern<TensorReshapeOp> { 838 using OpRewritePattern<TensorReshapeOp>::OpRewritePattern; 839 LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp, 840 PatternRewriter &rewriter) const override { 841 auto fromElements = 842 reshapeOp.src().template getDefiningOp<FromElementsOp>(); 843 if (!fromElements) 844 return failure(); 845 846 auto shapedTy = reshapeOp.getType().template cast<ShapedType>(); 847 848 if (!shapedTy.hasStaticShape()) 849 return failure(); 850 851 rewriter.replaceOpWithNewOp<FromElementsOp>(reshapeOp, reshapeOp.getType(), 852 fromElements.elements()); 853 return success(); 854 } 855 }; 856 857 } // namespace 858 859 void ExpandShapeOp::getCanonicalizationPatterns(RewritePatternSet &results, 860 MLIRContext *context) { 861 results.add<CollapseReshapeOps<ExpandShapeOp>, 862 CollapseMixedReshapeOps<ExpandShapeOp, CollapseShapeOp>, 863 FoldReshapeWithConstant<ExpandShapeOp>, 864 FoldReshapeWithFromElements<ExpandShapeOp>>(context); 865 } 866 867 void CollapseShapeOp::getCanonicalizationPatterns(RewritePatternSet &results, 868 MLIRContext *context) { 869 results.add<CollapseReshapeOps<CollapseShapeOp>, 870 CollapseMixedReshapeOps<CollapseShapeOp, ExpandShapeOp>, 871 FoldReshapeWithConstant<CollapseShapeOp>, 872 FoldReshapeWithFromElements<CollapseShapeOp>>(context); 873 } 874 875 OpFoldResult ExpandShapeOp::fold(ArrayRef<Attribute> operands) { 876 return foldReshapeOp<ExpandShapeOp, CollapseShapeOp>(*this, operands); 877 } 878 OpFoldResult CollapseShapeOp::fold(ArrayRef<Attribute> operands) { 879 return foldReshapeOp<CollapseShapeOp, ExpandShapeOp>(*this, operands); 880 } 881 882 //===----------------------------------------------------------------------===// 883 // ExtractSliceOp 884 //===----------------------------------------------------------------------===// 885 886 /// An extract_slice op result type can be fully inferred from the source type 887 /// and the static representation of offsets, sizes and strides. Special 888 /// sentinels encode the dynamic case. 889 RankedTensorType ExtractSliceOp::inferResultType( 890 RankedTensorType sourceRankedTensorType, ArrayRef<int64_t> staticOffsets, 891 ArrayRef<int64_t> staticSizes, ArrayRef<int64_t> staticStrides) { 892 // An extract_slice op may specify only a leading subset of offset/sizes/ 893 // strides in which case we complete with offset=0, sizes from memref type and 894 // strides=1. 895 unsigned rank = sourceRankedTensorType.getRank(); 896 (void)rank; 897 assert(staticSizes.size() == rank && 898 "unexpected staticSizes not equal to rank of source"); 899 return RankedTensorType::get(staticSizes, 900 sourceRankedTensorType.getElementType()); 901 } 902 903 RankedTensorType ExtractSliceOp::inferResultType( 904 RankedTensorType sourceRankedTensorType, ArrayRef<OpFoldResult> offsets, 905 ArrayRef<OpFoldResult> sizes, ArrayRef<OpFoldResult> strides) { 906 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 907 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 908 dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets, 909 ShapedType::kDynamicStrideOrOffset); 910 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 911 ShapedType::kDynamicSize); 912 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 913 ShapedType::kDynamicStrideOrOffset); 914 return ExtractSliceOp::inferResultType(sourceRankedTensorType, staticOffsets, 915 staticSizes, staticStrides); 916 } 917 918 /// An extract_slice op result type can be fully inferred from the source type 919 /// and the static representation of offsets, sizes and strides. Special 920 /// sentinels encode the dynamic case. 921 RankedTensorType ExtractSliceOp::inferRankReducedResultType( 922 unsigned resultRank, RankedTensorType sourceRankedTensorType, 923 ArrayRef<int64_t> offsets, ArrayRef<int64_t> sizes, 924 ArrayRef<int64_t> strides) { 925 auto inferredType = 926 inferResultType(sourceRankedTensorType, offsets, sizes, strides) 927 .cast<RankedTensorType>(); 928 int rankDiff = inferredType.getRank() - resultRank; 929 if (rankDiff > 0) { 930 auto shape = inferredType.getShape(); 931 llvm::SmallBitVector dimsToProject = 932 getPositionsOfShapeOne(rankDiff, shape); 933 SmallVector<int64_t> projectedShape; 934 for (unsigned pos = 0, e = shape.size(); pos < e; ++pos) 935 if (!dimsToProject.test(pos)) 936 projectedShape.push_back(shape[pos]); 937 inferredType = 938 RankedTensorType::get(projectedShape, inferredType.getElementType()); 939 } 940 return inferredType; 941 } 942 943 RankedTensorType ExtractSliceOp::inferRankReducedResultType( 944 unsigned resultRank, RankedTensorType sourceRankedTensorType, 945 ArrayRef<OpFoldResult> offsets, ArrayRef<OpFoldResult> sizes, 946 ArrayRef<OpFoldResult> strides) { 947 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 948 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 949 dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets, 950 ShapedType::kDynamicStrideOrOffset); 951 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 952 ShapedType::kDynamicSize); 953 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 954 ShapedType::kDynamicStrideOrOffset); 955 return ExtractSliceOp::inferRankReducedResultType( 956 resultRank, sourceRankedTensorType, staticOffsets, staticSizes, 957 staticStrides); 958 } 959 960 /// Build an ExtractSliceOp with mixed static and dynamic entries and custom 961 /// result type. If the type passed is nullptr, it is inferred. 962 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, 963 RankedTensorType resultType, Value source, 964 ArrayRef<OpFoldResult> offsets, 965 ArrayRef<OpFoldResult> sizes, 966 ArrayRef<OpFoldResult> strides, 967 ArrayRef<NamedAttribute> attrs) { 968 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 969 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 970 dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets, 971 ShapedType::kDynamicStrideOrOffset); 972 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 973 ShapedType::kDynamicSize); 974 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 975 ShapedType::kDynamicStrideOrOffset); 976 auto sourceRankedTensorType = source.getType().cast<RankedTensorType>(); 977 // Structuring implementation this way avoids duplication between builders. 978 if (!resultType) { 979 resultType = 980 ExtractSliceOp::inferResultType(sourceRankedTensorType, staticOffsets, 981 staticSizes, staticStrides) 982 .cast<RankedTensorType>(); 983 } 984 build(b, result, resultType, source, dynamicOffsets, dynamicSizes, 985 dynamicStrides, b.getI64ArrayAttr(staticOffsets), 986 b.getI64ArrayAttr(staticSizes), b.getI64ArrayAttr(staticStrides)); 987 result.addAttributes(attrs); 988 } 989 990 /// Build an ExtractSliceOp with mixed static and dynamic entries and inferred 991 /// result type. 992 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, Value source, 993 ArrayRef<OpFoldResult> offsets, 994 ArrayRef<OpFoldResult> sizes, 995 ArrayRef<OpFoldResult> strides, 996 ArrayRef<NamedAttribute> attrs) { 997 build(b, result, RankedTensorType(), source, offsets, sizes, strides, attrs); 998 } 999 1000 /// Build an ExtractSliceOp with dynamic entries and custom result type. If the 1001 /// type passed is nullptr, it is inferred. 1002 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, 1003 RankedTensorType resultType, Value source, 1004 ValueRange offsets, ValueRange sizes, 1005 ValueRange strides, ArrayRef<NamedAttribute> attrs) { 1006 SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>( 1007 llvm::map_range(offsets, [](Value v) -> OpFoldResult { return v; })); 1008 SmallVector<OpFoldResult> sizeValues = llvm::to_vector<4>( 1009 llvm::map_range(sizes, [](Value v) -> OpFoldResult { return v; })); 1010 SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>( 1011 llvm::map_range(strides, [](Value v) -> OpFoldResult { return v; })); 1012 build(b, result, resultType, source, offsetValues, sizeValues, strideValues); 1013 } 1014 1015 /// Build an ExtractSliceOp with dynamic entries and inferred result type. 1016 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, Value source, 1017 ValueRange offsets, ValueRange sizes, 1018 ValueRange strides, ArrayRef<NamedAttribute> attrs) { 1019 build(b, result, RankedTensorType(), source, offsets, sizes, strides, attrs); 1020 } 1021 1022 template <typename OpTy> 1023 static LogicalResult produceSliceErrorMsg(SliceVerificationResult result, 1024 OpTy op, Type expectedType) { 1025 auto memrefType = expectedType.cast<ShapedType>(); 1026 switch (result) { 1027 case SliceVerificationResult::Success: 1028 return success(); 1029 case SliceVerificationResult::RankTooLarge: 1030 return op.emitError("expected rank to be smaller or equal to ") 1031 << "the other rank. "; 1032 case SliceVerificationResult::SizeMismatch: 1033 return op.emitError("expected type to be ") 1034 << expectedType << " or a rank-reduced version. (size mismatch) "; 1035 case SliceVerificationResult::ElemTypeMismatch: 1036 return op.emitError("expected element type to be ") 1037 << memrefType.getElementType(); 1038 default: 1039 llvm_unreachable("unexpected extract_slice op verification result"); 1040 } 1041 } 1042 1043 /// Verifier for ExtractSliceOp. 1044 LogicalResult ExtractSliceOp::verify() { 1045 // Verify result type against inferred type. 1046 auto expectedType = ExtractSliceOp::inferResultType( 1047 getSourceType(), getMixedOffsets(), getMixedSizes(), getMixedStrides()); 1048 auto result = isRankReducedType(expectedType.cast<ShapedType>(), getType()); 1049 return produceSliceErrorMsg(result, *this, expectedType); 1050 } 1051 1052 /// Infer the canonical type of the result of an extract_slice op. Returns a 1053 /// type with rank `resultRank` that is either the rank of the rank-reduced 1054 /// type, or the non-rank-reduced type. 1055 static RankedTensorType 1056 getCanonicalSliceResultType(unsigned resultRank, RankedTensorType sourceType, 1057 ArrayRef<OpFoldResult> mixedOffsets, 1058 ArrayRef<OpFoldResult> mixedSizes, 1059 ArrayRef<OpFoldResult> mixedStrides) { 1060 auto resultType = 1061 ExtractSliceOp::inferRankReducedResultType( 1062 resultRank, sourceType, mixedOffsets, mixedSizes, mixedStrides) 1063 .cast<RankedTensorType>(); 1064 if (resultType.getRank() != resultRank) { 1065 resultType = ExtractSliceOp::inferResultType(sourceType, mixedOffsets, 1066 mixedSizes, mixedStrides) 1067 .cast<RankedTensorType>(); 1068 } 1069 return resultType; 1070 } 1071 1072 llvm::SmallBitVector ExtractSliceOp::getDroppedDims() { 1073 ArrayRef<int64_t> resultShape = getType().getShape(); 1074 SmallVector<OpFoldResult> mixedSizes = getMixedSizes(); 1075 llvm::SmallBitVector droppedDims(mixedSizes.size()); 1076 unsigned shapePos = 0; 1077 for (const auto &size : enumerate(mixedSizes)) { 1078 Optional<int64_t> sizeVal = getConstantIntValue(size.value()); 1079 // If the size is not 1, or if the current matched dimension of the result 1080 // is the same static shape as the size value (which is 1), then the 1081 // dimension is preserved. 1082 if (!sizeVal || sizeVal.getValue() != 1 || 1083 (shapePos < resultShape.size() && resultShape[shapePos] == 1)) { 1084 shapePos++; 1085 continue; 1086 } 1087 droppedDims.set(size.index()); 1088 } 1089 return droppedDims; 1090 } 1091 1092 LogicalResult ExtractSliceOp::reifyResultShapes( 1093 OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) { 1094 reifiedReturnShapes.resize(1); 1095 reifiedReturnShapes[0].reserve(getType().getRank()); 1096 SmallVector<OpFoldResult> mixedSizes = getMixedSizes(); 1097 llvm::SmallBitVector droppedDims = getDroppedDims(); 1098 Location loc = getLoc(); 1099 for (const auto &size : enumerate(mixedSizes)) { 1100 if (droppedDims.test(size.index())) 1101 continue; 1102 if (auto attr = size.value().dyn_cast<Attribute>()) { 1103 reifiedReturnShapes[0].push_back(builder.create<arith::ConstantIndexOp>( 1104 loc, attr.cast<IntegerAttr>().getInt())); 1105 continue; 1106 } 1107 reifiedReturnShapes[0].push_back(size.value().get<Value>()); 1108 } 1109 return success(); 1110 } 1111 1112 namespace { 1113 /// Pattern to rewrite an extract_slice op with tensor::Cast arguments. 1114 /// This essentially pushes memref_cast past its consuming slice when 1115 /// `canFoldIntoConsumerOp` is true. 1116 /// 1117 /// Example: 1118 /// ``` 1119 /// %0 = tensor.cast %V : tensor<16x16xf32> to tensor<?x?xf32> 1120 /// %1 = tensor.extract_slice %0[0, 0][3, 4][1, 1] : tensor<?x?xf32> to 1121 /// tensor<3x4xf32> 1122 /// ``` 1123 /// is rewritten into: 1124 /// ``` 1125 /// %0 = tensor.extract_slice %V[0, 0][3, 4][1, 1] : tensor<16x16xf32> to 1126 /// tensor<3x4xf32> %1 = tensor.cast %0: tensor<3x4xf32> to tensor<3x4xf32> 1127 /// ``` 1128 class ExtractSliceOpCastFolder final : public OpRewritePattern<ExtractSliceOp> { 1129 public: 1130 using OpRewritePattern<ExtractSliceOp>::OpRewritePattern; 1131 1132 LogicalResult matchAndRewrite(ExtractSliceOp sliceOp, 1133 PatternRewriter &rewriter) const override { 1134 // Any constant operand, just return to let SubViewOpConstantFolder kick in. 1135 if (llvm::any_of(sliceOp.getOperands(), [](Value operand) { 1136 return matchPattern(operand, matchConstantIndex()); 1137 })) 1138 return failure(); 1139 1140 auto castOp = sliceOp.source().getDefiningOp<tensor::CastOp>(); 1141 if (!castOp) 1142 return failure(); 1143 1144 if (!canFoldIntoConsumerOp(castOp)) 1145 return failure(); 1146 1147 /// Deduce the type of the result to use for the canonicalized operation. 1148 RankedTensorType resultType = getCanonicalSliceResultType( 1149 sliceOp.getType().getRank(), sliceOp.getSourceType(), 1150 sliceOp.getMixedOffsets(), sliceOp.getMixedSizes(), 1151 sliceOp.getMixedStrides()); 1152 Value newSlice = rewriter.create<ExtractSliceOp>( 1153 sliceOp.getLoc(), resultType, castOp.source(), sliceOp.offsets(), 1154 sliceOp.sizes(), sliceOp.strides(), sliceOp.static_offsets(), 1155 sliceOp.static_sizes(), sliceOp.static_strides()); 1156 rewriter.replaceOpWithNewOp<tensor::CastOp>(sliceOp, sliceOp.getType(), 1157 newSlice); 1158 return success(); 1159 } 1160 }; 1161 } // namespace 1162 1163 /// Return the canonical type of the result of an extract_slice op. 1164 struct SliceReturnTypeCanonicalizer { 1165 RankedTensorType operator()(ExtractSliceOp op, 1166 ArrayRef<OpFoldResult> mixedOffsets, 1167 ArrayRef<OpFoldResult> mixedSizes, 1168 ArrayRef<OpFoldResult> mixedStrides) { 1169 return getCanonicalSliceResultType(op.getType().getRank(), 1170 op.getSourceType(), mixedOffsets, 1171 mixedSizes, mixedStrides); 1172 } 1173 }; 1174 1175 /// A canonicalizer wrapper to replace ExtractSliceOps. 1176 struct SliceCanonicalizer { 1177 void operator()(PatternRewriter &rewriter, ExtractSliceOp op, 1178 ExtractSliceOp newOp) { 1179 Value replacement = newOp.getResult(); 1180 if (replacement.getType() != op.getType()) 1181 replacement = rewriter.create<tensor::CastOp>(op.getLoc(), op.getType(), 1182 replacement); 1183 rewriter.replaceOp(op, replacement); 1184 } 1185 }; 1186 1187 void ExtractSliceOp::getCanonicalizationPatterns(RewritePatternSet &results, 1188 MLIRContext *context) { 1189 results.add< 1190 OpWithOffsetSizesAndStridesConstantArgumentFolder< 1191 ExtractSliceOp, SliceReturnTypeCanonicalizer, SliceCanonicalizer>, 1192 ExtractSliceOpCastFolder>(context); 1193 } 1194 1195 // 1196 static LogicalResult 1197 foldIdentityOffsetSizeAndStrideOpInterface(OffsetSizeAndStrideOpInterface op, 1198 ShapedType shapedType) { 1199 OpBuilder b(op.getContext()); 1200 for (OpFoldResult ofr : op.getMixedOffsets()) 1201 if (getConstantIntValue(ofr) != static_cast<int64_t>(0)) 1202 return failure(); 1203 // Rank-reducing noops only need to inspect the leading dimensions: llvm::zip 1204 // is appropriate. 1205 auto shape = shapedType.getShape(); 1206 for (auto it : llvm::zip(op.getMixedSizes(), shape)) 1207 if (getConstantIntValue(std::get<0>(it)) != std::get<1>(it)) 1208 return failure(); 1209 for (OpFoldResult ofr : op.getMixedStrides()) 1210 if (getConstantIntValue(ofr) != static_cast<int64_t>(1)) 1211 return failure(); 1212 return success(); 1213 } 1214 1215 /// If we have an ExtractSliceOp consuming an InsertSliceOp with the same slice, 1216 /// we can return the InsertSliceOp's source directly. 1217 // TODO: This only checks the immediate producer; extend to go up the 1218 // insert/extract chain if the slices are disjoint. 1219 static Value foldExtractAfterInsertSlice(ExtractSliceOp extractOp) { 1220 auto insertOp = extractOp.source().getDefiningOp<InsertSliceOp>(); 1221 1222 auto isSame = [](OpFoldResult a, OpFoldResult b) { return a == b; }; 1223 if (insertOp && insertOp.source().getType() == extractOp.getType() && 1224 insertOp.isSameAs(extractOp, isSame)) 1225 return insertOp.source(); 1226 1227 return {}; 1228 } 1229 1230 OpFoldResult ExtractSliceOp::fold(ArrayRef<Attribute>) { 1231 if (getSourceType() == getType() && 1232 succeeded(foldIdentityOffsetSizeAndStrideOpInterface(*this, getType()))) 1233 return this->source(); 1234 if (Value slice = foldExtractAfterInsertSlice(*this)) 1235 return slice; 1236 return OpFoldResult(); 1237 } 1238 1239 Value mlir::tensor::createCanonicalRankReducingExtractSliceOp( 1240 OpBuilder &b, Location loc, Value tensor, RankedTensorType targetType) { 1241 auto rankedTensorType = tensor.getType().cast<RankedTensorType>(); 1242 unsigned rank = rankedTensorType.getRank(); 1243 auto shape = rankedTensorType.getShape(); 1244 SmallVector<OpFoldResult> offsets(rank, b.getIndexAttr(0)); 1245 SmallVector<OpFoldResult> sizes; 1246 for (unsigned i = 0, e = rank; i < e; ++i) { 1247 OpFoldResult dim; 1248 if (rankedTensorType.isDynamicDim(i)) 1249 dim = b.createOrFold<tensor::DimOp>( 1250 loc, tensor, b.create<arith::ConstantIndexOp>(loc, i)); 1251 else 1252 dim = b.getIndexAttr(shape[i]); 1253 sizes.push_back(dim); 1254 } 1255 SmallVector<OpFoldResult> strides(rank, b.getIndexAttr(1)); 1256 return b.createOrFold<tensor::ExtractSliceOp>(loc, targetType, tensor, 1257 offsets, sizes, strides); 1258 } 1259 1260 //===----------------------------------------------------------------------===// 1261 // InsertSliceOp 1262 //===----------------------------------------------------------------------===// 1263 1264 // Build a InsertSliceOp with mixed static and dynamic entries. 1265 void InsertSliceOp::build(OpBuilder &b, OperationState &result, Value source, 1266 Value dest, ArrayRef<OpFoldResult> offsets, 1267 ArrayRef<OpFoldResult> sizes, 1268 ArrayRef<OpFoldResult> strides, 1269 ArrayRef<NamedAttribute> attrs) { 1270 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 1271 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 1272 dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets, 1273 ShapedType::kDynamicStrideOrOffset); 1274 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 1275 ShapedType::kDynamicSize); 1276 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 1277 ShapedType::kDynamicStrideOrOffset); 1278 build(b, result, dest.getType(), source, dest, dynamicOffsets, dynamicSizes, 1279 dynamicStrides, b.getI64ArrayAttr(staticOffsets), 1280 b.getI64ArrayAttr(staticSizes), b.getI64ArrayAttr(staticStrides)); 1281 result.addAttributes(attrs); 1282 } 1283 1284 // Build a InsertSliceOp with dynamic entries. 1285 void InsertSliceOp::build(OpBuilder &b, OperationState &result, Value source, 1286 Value dest, ValueRange offsets, ValueRange sizes, 1287 ValueRange strides, ArrayRef<NamedAttribute> attrs) { 1288 SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>( 1289 llvm::map_range(offsets, [](Value v) -> OpFoldResult { return v; })); 1290 SmallVector<OpFoldResult> sizeValues = llvm::to_vector<4>( 1291 llvm::map_range(sizes, [](Value v) -> OpFoldResult { return v; })); 1292 SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>( 1293 llvm::map_range(strides, [](Value v) -> OpFoldResult { return v; })); 1294 build(b, result, source, dest, offsetValues, sizeValues, strideValues); 1295 } 1296 1297 static SliceVerificationResult 1298 verifyInsertSliceOp(ShapedType srcType, ShapedType dstType, 1299 ArrayAttr staticOffsets, ArrayAttr staticSizes, 1300 ArrayAttr staticStrides, 1301 ShapedType *expectedType = nullptr) { 1302 // insert_slice is the inverse of extract_slice, use the same type inference. 1303 auto expected = ExtractSliceOp::inferRankReducedResultType( 1304 srcType.getRank(), dstType.cast<RankedTensorType>(), 1305 extractFromI64ArrayAttr(staticOffsets), 1306 extractFromI64ArrayAttr(staticSizes), 1307 extractFromI64ArrayAttr(staticStrides)) 1308 .cast<ShapedType>(); 1309 if (expectedType) 1310 *expectedType = expected; 1311 return isRankReducedType(expected, srcType); 1312 } 1313 1314 /// Verifier for InsertSliceOp. 1315 LogicalResult InsertSliceOp::verify() { 1316 ShapedType expectedType; 1317 auto result = 1318 verifyInsertSliceOp(getSourceType(), getType(), static_offsets(), 1319 static_sizes(), static_strides(), &expectedType); 1320 return produceSliceErrorMsg(result, *this, expectedType); 1321 } 1322 1323 /// If we have two consecutive InsertSliceOp writing to the same slice, we 1324 /// can mutate the second InsertSliceOp's destination to the first one's. 1325 /// 1326 /// Example: 1327 /// 1328 /// ```mlir 1329 /// %0 = tensor.insert_slice %slice0 into %input[0, 0] [64, 64] [1, 1] 1330 /// %1 = tensor.insert_slice %slice1 into %0[0, 0] [64, 64] [1, 1] 1331 /// ``` 1332 /// 1333 /// folds into: 1334 /// 1335 /// ```mlir 1336 /// %1 = tensor.insert_slice %slice1 into %input[0, 0] [64, 64] [1, 1] 1337 /// ``` 1338 static LogicalResult foldInsertAfterInsertSlice(InsertSliceOp insertOp) { 1339 auto prevInsertOp = insertOp.dest().getDefiningOp<InsertSliceOp>(); 1340 1341 auto isSame = [](OpFoldResult a, OpFoldResult b) { return a == b; }; 1342 if (!prevInsertOp || 1343 prevInsertOp.source().getType() != insertOp.source().getType() || 1344 !prevInsertOp.isSameAs(insertOp, isSame)) 1345 return failure(); 1346 1347 insertOp.destMutable().assign(prevInsertOp.dest()); 1348 return success(); 1349 } 1350 1351 OpFoldResult InsertSliceOp::fold(ArrayRef<Attribute>) { 1352 if (getSourceType().hasStaticShape() && getType().hasStaticShape() && 1353 getSourceType() == getType() && 1354 succeeded(foldIdentityOffsetSizeAndStrideOpInterface(*this, getType()))) 1355 return this->source(); 1356 if (succeeded(foldInsertAfterInsertSlice(*this))) 1357 return getResult(); 1358 return OpFoldResult(); 1359 } 1360 1361 LogicalResult InsertSliceOp::reifyResultShapes( 1362 OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) { 1363 reifiedReturnShapes.resize(1, SmallVector<Value>(getType().getRank())); 1364 for (auto dim : llvm::seq<int64_t>(0, getType().getRank())) { 1365 reifiedReturnShapes[0][dim] = 1366 builder.createOrFold<tensor::DimOp>(getLoc(), dest(), dim); 1367 } 1368 return success(); 1369 } 1370 1371 namespace { 1372 /// Pattern to rewrite a insert_slice op with constant arguments. 1373 class InsertSliceOpConstantArgumentFolder final 1374 : public OpRewritePattern<InsertSliceOp> { 1375 public: 1376 using OpRewritePattern<InsertSliceOp>::OpRewritePattern; 1377 1378 LogicalResult matchAndRewrite(InsertSliceOp insertSliceOp, 1379 PatternRewriter &rewriter) const override { 1380 // No constant operand, just return. 1381 if (llvm::none_of(insertSliceOp.getOperands(), [](Value operand) { 1382 return matchPattern(operand, matchConstantIndex()); 1383 })) 1384 return failure(); 1385 1386 // At least one of offsets/sizes/strides is a new constant. 1387 // Form the new list of operands and constant attributes from the 1388 // existing. 1389 SmallVector<OpFoldResult> mixedOffsets(insertSliceOp.getMixedOffsets()); 1390 SmallVector<OpFoldResult> mixedSizes(insertSliceOp.getMixedSizes()); 1391 SmallVector<OpFoldResult> mixedStrides(insertSliceOp.getMixedStrides()); 1392 canonicalizeSubViewPart(mixedOffsets, ShapedType::isDynamicStrideOrOffset); 1393 canonicalizeSubViewPart(mixedSizes, ShapedType::isDynamic); 1394 canonicalizeSubViewPart(mixedStrides, ShapedType::isDynamicStrideOrOffset); 1395 1396 // Create the new op in canonical form. 1397 auto sourceType = ExtractSliceOp::inferRankReducedResultType( 1398 insertSliceOp.getSourceType().getRank(), insertSliceOp.getType(), 1399 mixedOffsets, mixedSizes, mixedStrides); 1400 Value toInsert = insertSliceOp.source(); 1401 if (sourceType != insertSliceOp.getSourceType()) 1402 toInsert = rewriter.create<tensor::CastOp>(insertSliceOp.getLoc(), 1403 sourceType, toInsert); 1404 rewriter.replaceOpWithNewOp<InsertSliceOp>( 1405 insertSliceOp, toInsert, insertSliceOp.dest(), mixedOffsets, mixedSizes, 1406 mixedStrides); 1407 return success(); 1408 } 1409 }; 1410 1411 /// Fold tensor_casts with insert_slice operations. If the source or destination 1412 /// tensor is a tensor_cast that removes static type information, the cast is 1413 /// folded into the insert_slice operation. E.g.: 1414 /// 1415 /// ```mlir 1416 /// %1 = tensor.cast %0 : tensor<8x16xf32> to tensor<?x?xf32> 1417 /// %2 = tensor.insert_slice %1 into ... : tensor<?x?xf32> into ... 1418 /// ``` 1419 /// 1420 /// folds into: 1421 /// 1422 /// ```mlir 1423 /// %2 = tensor.insert_slice %0 into ... : tensor<8x16xf32> into ... 1424 /// ``` 1425 /// 1426 /// Note: When folding a cast on the destination tensor, the result of the 1427 /// insert_slice operation is casted to ensure that the type of the result did 1428 /// not change. 1429 struct InsertSliceOpCastFolder final : public OpRewritePattern<InsertSliceOp> { 1430 using OpRewritePattern<InsertSliceOp>::OpRewritePattern; 1431 1432 LogicalResult matchAndRewrite(InsertSliceOp insertSliceOp, 1433 PatternRewriter &rewriter) const override { 1434 if (llvm::any_of(insertSliceOp.getOperands(), [](Value operand) { 1435 return matchPattern(operand, matchConstantIndex()); 1436 })) 1437 return failure(); 1438 1439 auto getSourceOfCastOp = [](Value v) -> Optional<Value> { 1440 auto castOp = v.getDefiningOp<tensor::CastOp>(); 1441 if (!castOp || !canFoldIntoConsumerOp(castOp)) 1442 return llvm::None; 1443 return castOp.source(); 1444 }; 1445 Optional<Value> sourceCastSource = 1446 getSourceOfCastOp(insertSliceOp.source()); 1447 Optional<Value> destCastSource = getSourceOfCastOp(insertSliceOp.dest()); 1448 if (!sourceCastSource && !destCastSource) 1449 return failure(); 1450 1451 auto src = (sourceCastSource ? *sourceCastSource : insertSliceOp.source()); 1452 auto dst = (destCastSource ? *destCastSource : insertSliceOp.dest()); 1453 1454 auto srcType = src.getType().cast<ShapedType>(); 1455 auto dstType = dst.getType().cast<ShapedType>(); 1456 if (verifyInsertSliceOp(srcType, dstType, insertSliceOp.static_offsets(), 1457 insertSliceOp.static_sizes(), 1458 insertSliceOp.static_strides()) != 1459 SliceVerificationResult::Success) 1460 return failure(); 1461 1462 Value replacement = rewriter.create<InsertSliceOp>( 1463 insertSliceOp.getLoc(), src, dst, insertSliceOp.getMixedOffsets(), 1464 insertSliceOp.getMixedSizes(), insertSliceOp.getMixedStrides()); 1465 1466 if (replacement.getType() != insertSliceOp.getType()) { 1467 replacement = rewriter.create<tensor::CastOp>( 1468 insertSliceOp.getLoc(), insertSliceOp.getType(), replacement); 1469 } 1470 rewriter.replaceOp(insertSliceOp, replacement); 1471 return success(); 1472 } 1473 }; 1474 1475 /// If additional static type information can be deduced from a insert_slice's 1476 /// size operands, insert an explicit cast of the op's source operand. This 1477 /// enables other canonicalization patterns that are matching for tensor_cast 1478 /// ops such as `ForOpTensorCastFolder` in SCF. 1479 /// 1480 /// Example: 1481 /// 1482 /// ```mlir 1483 /// %r = tensor.insert_slice %0 into %1[...] [64, 64] [1, 1] 1484 /// : tensor<?x?xf32> into ... 1485 /// ``` 1486 /// 1487 /// folds into: 1488 /// 1489 /// ```mlir 1490 /// %tmp = tensor.cast %0 : tensor<?x?xf32> to tensor<64x64xf32> 1491 /// %r = tensor.insert_slice %tmp into %1[...] [64, 64] [1, 1] 1492 /// : tensor<64x64xf32> into ... 1493 /// ``` 1494 struct InsertSliceOpSourceCastInserter final 1495 : public OpRewritePattern<InsertSliceOp> { 1496 using OpRewritePattern<InsertSliceOp>::OpRewritePattern; 1497 1498 LogicalResult matchAndRewrite(InsertSliceOp insertSliceOp, 1499 PatternRewriter &rewriter) const override { 1500 RankedTensorType srcType = insertSliceOp.getSourceType(); 1501 if (srcType.getRank() != insertSliceOp.getType().getRank()) 1502 return failure(); 1503 SmallVector<int64_t> newSrcShape(srcType.getShape().begin(), 1504 srcType.getShape().end()); 1505 for (int64_t i = 0; i < srcType.getRank(); ++i) { 1506 if (Optional<int64_t> constInt = 1507 getConstantIntValue(insertSliceOp.getMixedSizes()[i])) 1508 newSrcShape[i] = *constInt; 1509 } 1510 1511 RankedTensorType newSrcType = 1512 RankedTensorType::get(newSrcShape, srcType.getElementType()); 1513 if (srcType == newSrcType || 1514 !preservesStaticInformation(srcType, newSrcType) || 1515 !tensor::CastOp::areCastCompatible(srcType, newSrcType)) 1516 return failure(); 1517 1518 // newSrcType is: 1519 // 1) Different from srcType. 1520 // 2) "More static" than srcType. 1521 // 3) Cast-compatible with srcType. 1522 // Insert the cast. 1523 Value cast = rewriter.create<tensor::CastOp>( 1524 insertSliceOp.getLoc(), newSrcType, insertSliceOp.source()); 1525 rewriter.replaceOpWithNewOp<InsertSliceOp>( 1526 insertSliceOp, cast, insertSliceOp.dest(), 1527 insertSliceOp.getMixedOffsets(), insertSliceOp.getMixedSizes(), 1528 insertSliceOp.getMixedStrides()); 1529 return success(); 1530 } 1531 }; 1532 } // namespace 1533 1534 void InsertSliceOp::getCanonicalizationPatterns(RewritePatternSet &results, 1535 MLIRContext *context) { 1536 results.add<InsertSliceOpConstantArgumentFolder, InsertSliceOpCastFolder, 1537 InsertSliceOpSourceCastInserter>(context); 1538 } 1539 1540 Value mlir::tensor::createCanonicalRankReducingInsertSliceOp(OpBuilder &b, 1541 Location loc, 1542 Value tensor, 1543 Value dest) { 1544 auto rankedTensorType = dest.getType().cast<RankedTensorType>(); 1545 unsigned rank = rankedTensorType.getRank(); 1546 auto shape = rankedTensorType.getShape(); 1547 SmallVector<OpFoldResult> offsets(rank, b.getIndexAttr(0)); 1548 SmallVector<OpFoldResult> sizes; 1549 for (unsigned i = 0, e = rank; i < e; ++i) { 1550 OpFoldResult dim; 1551 if (rankedTensorType.isDynamicDim(i)) 1552 dim = b.createOrFold<tensor::DimOp>( 1553 loc, dest, b.create<arith::ConstantIndexOp>(loc, i)); 1554 else 1555 dim = b.getIndexAttr(shape[i]); 1556 sizes.push_back(dim); 1557 } 1558 SmallVector<OpFoldResult> strides(rank, b.getIndexAttr(1)); 1559 return b.createOrFold<tensor::InsertSliceOp>(loc, tensor, dest, offsets, 1560 sizes, strides); 1561 } 1562 1563 //===----------------------------------------------------------------------===// 1564 // PadOp 1565 //===----------------------------------------------------------------------===// 1566 1567 // TODO: Replace custom<InferType> directive with AllTypesMatch as soon as it 1568 // supports optional types. 1569 void printInferType(OpAsmPrinter &printer, Operation *op, Value optOperand, 1570 Type typeToInfer, Type typeToInferFrom) {} 1571 1572 ParseResult parseInferType(OpAsmParser &parser, 1573 Optional<OpAsmParser::OperandType> optOperand, 1574 Type &typeToInfer, Type typeToInferFrom) { 1575 if (optOperand) 1576 typeToInfer = typeToInferFrom; 1577 return success(); 1578 } 1579 1580 LogicalResult PadOp::verify() { 1581 auto sourceType = source().getType().cast<RankedTensorType>(); 1582 auto resultType = result().getType().cast<RankedTensorType>(); 1583 auto expectedType = 1584 PadOp::inferResultType(sourceType, extractFromI64ArrayAttr(static_low()), 1585 extractFromI64ArrayAttr(static_high())); 1586 for (int i = 0, e = sourceType.getRank(); i < e; ++i) { 1587 if (resultType.getDimSize(i) == expectedType.getDimSize(i)) 1588 continue; 1589 if (expectedType.isDynamicDim(i)) 1590 continue; 1591 return emitError("specified type ") 1592 << resultType << " does not match the inferred type " 1593 << expectedType; 1594 } 1595 1596 auto ®ion = getRegion(); 1597 unsigned rank = resultType.getRank(); 1598 Block &block = region.front(); 1599 if (block.getNumArguments() != rank) 1600 return emitError("expected the block to have ") << rank << " arguments"; 1601 1602 // Note: the number and type of yield values are checked in the YieldOp. 1603 for (const auto &en : llvm::enumerate(block.getArgumentTypes())) { 1604 if (!en.value().isIndex()) 1605 return emitOpError("expected block argument ") 1606 << (en.index() + 1) << " to be an index"; 1607 } 1608 1609 // Ensure that the region yields an element of the right type. 1610 auto yieldOp = llvm::cast<YieldOp>(block.getTerminator()); 1611 if (yieldOp.value().getType() != 1612 getType().cast<ShapedType>().getElementType()) 1613 return emitOpError("expected yield type to match shape element type"); 1614 1615 return success(); 1616 } 1617 1618 RankedTensorType PadOp::inferResultType(RankedTensorType sourceType, 1619 ArrayRef<int64_t> staticLow, 1620 ArrayRef<int64_t> staticHigh, 1621 ArrayRef<int64_t> resultShape) { 1622 unsigned rank = sourceType.getRank(); 1623 assert(staticLow.size() == rank && "unexpected staticLow size mismatch"); 1624 assert(staticHigh.size() == rank && "unexpected staticHigh size mismatch"); 1625 assert((resultShape.empty() || resultShape.size() == rank) && 1626 "unexpected resultShape size mismatch"); 1627 1628 SmallVector<int64_t, 4> inferredShape; 1629 for (auto i : llvm::seq<unsigned>(0, rank)) { 1630 if (sourceType.isDynamicDim(i) || 1631 staticLow[i] == ShapedType::kDynamicSize || 1632 staticHigh[i] == ShapedType::kDynamicSize) { 1633 inferredShape.push_back(resultShape.empty() ? ShapedType::kDynamicSize 1634 : resultShape[i]); 1635 } else { 1636 int64_t size = sourceType.getDimSize(i) + staticLow[i] + staticHigh[i]; 1637 assert((resultShape.empty() || size == resultShape[i] || 1638 resultShape[i] == ShapedType::kDynamicSize) && 1639 "mismatch between inferred shape and result shape"); 1640 inferredShape.push_back(size); 1641 } 1642 } 1643 1644 return RankedTensorType::get(inferredShape, sourceType.getElementType()); 1645 } 1646 1647 void PadOp::build(OpBuilder &b, OperationState &result, Value source, 1648 ArrayRef<int64_t> staticLow, ArrayRef<int64_t> staticHigh, 1649 ValueRange low, ValueRange high, bool nofold, 1650 ArrayRef<NamedAttribute> attrs) { 1651 auto sourceType = source.getType().cast<RankedTensorType>(); 1652 auto resultType = inferResultType(sourceType, staticLow, staticHigh); 1653 build(b, result, resultType, source, low, high, b.getI64ArrayAttr(staticLow), 1654 b.getI64ArrayAttr(staticHigh), nofold ? b.getUnitAttr() : UnitAttr()); 1655 result.addAttributes(attrs); 1656 } 1657 1658 void PadOp::build(OpBuilder &b, OperationState &result, Value source, 1659 ValueRange low, ValueRange high, bool nofold, 1660 ArrayRef<NamedAttribute> attrs) { 1661 auto sourceType = source.getType().cast<RankedTensorType>(); 1662 unsigned rank = sourceType.getRank(); 1663 SmallVector<int64_t, 4> staticVector(rank, ShapedType::kDynamicSize); 1664 build(b, result, source, staticVector, staticVector, low, high, nofold, 1665 attrs); 1666 } 1667 1668 void PadOp::build(OpBuilder &b, OperationState &result, Type resultType, 1669 Value source, ArrayRef<OpFoldResult> low, 1670 ArrayRef<OpFoldResult> high, bool nofold, 1671 ArrayRef<NamedAttribute> attrs) { 1672 assert(resultType.isa<RankedTensorType>()); 1673 auto sourceType = source.getType().cast<RankedTensorType>(); 1674 SmallVector<Value, 4> dynamicLow, dynamicHigh; 1675 SmallVector<int64_t, 4> staticLow, staticHigh; 1676 // staticLow and staticHigh have full information of the padding config. 1677 // This will grow staticLow and staticHigh with 1 value. If the config is 1678 // dynamic (ie not a constant), dynamicLow and dynamicHigh will grow with 1 1679 // value as well. 1680 dispatchIndexOpFoldResults(low, dynamicLow, staticLow, 1681 ShapedType::kDynamicSize); 1682 dispatchIndexOpFoldResults(high, dynamicHigh, staticHigh, 1683 ShapedType::kDynamicSize); 1684 if (!resultType) { 1685 resultType = PadOp::inferResultType(sourceType, staticLow, staticHigh); 1686 } 1687 build(b, result, resultType, source, dynamicLow, dynamicHigh, 1688 b.getI64ArrayAttr(staticLow), b.getI64ArrayAttr(staticHigh), 1689 nofold ? b.getUnitAttr() : UnitAttr()); 1690 result.addAttributes(attrs); 1691 } 1692 1693 namespace { 1694 // Folds tensor.pad when padding is static zeros and the attribute 1695 // doesn't request otherwise. 1696 struct FoldStaticZeroPadding : public OpRewritePattern<PadOp> { 1697 using OpRewritePattern<PadOp>::OpRewritePattern; 1698 1699 LogicalResult matchAndRewrite(PadOp padTensorOp, 1700 PatternRewriter &rewriter) const override { 1701 if (!padTensorOp.hasZeroLowPad() || !padTensorOp.hasZeroHighPad()) 1702 return failure(); 1703 if (padTensorOp.nofold()) 1704 return failure(); 1705 rewriter.replaceOpWithNewOp<tensor::CastOp>( 1706 padTensorOp, padTensorOp.result().getType(), padTensorOp.source()); 1707 return success(); 1708 } 1709 }; 1710 1711 // Fold CastOp into PadOp when adding static information. 1712 struct FoldSourceTensorCast : public OpRewritePattern<PadOp> { 1713 using OpRewritePattern<PadOp>::OpRewritePattern; 1714 1715 LogicalResult matchAndRewrite(PadOp padTensorOp, 1716 PatternRewriter &rewriter) const override { 1717 auto castOp = padTensorOp.source().getDefiningOp<tensor::CastOp>(); 1718 if (!tensor::canFoldIntoConsumerOp(castOp)) 1719 return failure(); 1720 1721 auto newResultType = PadOp::inferResultType( 1722 castOp.source().getType().cast<RankedTensorType>(), 1723 extractFromI64ArrayAttr(padTensorOp.static_low()), 1724 extractFromI64ArrayAttr(padTensorOp.static_high()), 1725 padTensorOp.getResultType().getShape()); 1726 1727 if (newResultType == padTensorOp.getResultType()) { 1728 rewriter.updateRootInPlace(padTensorOp, [&]() { 1729 padTensorOp.sourceMutable().assign(castOp.source()); 1730 }); 1731 } else { 1732 auto newOp = rewriter.create<PadOp>( 1733 padTensorOp->getLoc(), newResultType, padTensorOp.source(), 1734 padTensorOp.low(), padTensorOp.high(), padTensorOp.static_low(), 1735 padTensorOp.static_high(), padTensorOp.nofold()); 1736 BlockAndValueMapping mapper; 1737 padTensorOp.getRegion().cloneInto(&newOp.getRegion(), mapper); 1738 1739 rewriter.replaceOpWithNewOp<tensor::CastOp>( 1740 padTensorOp, padTensorOp.getResultType(), newOp); 1741 } 1742 return success(); 1743 } 1744 }; 1745 1746 // Fold CastOp using the result of PadOp back into the latter if it adds 1747 // static information. 1748 struct FoldTargetTensorCast : public OpRewritePattern<PadOp> { 1749 using OpRewritePattern<PadOp>::OpRewritePattern; 1750 1751 LogicalResult matchAndRewrite(PadOp padTensorOp, 1752 PatternRewriter &rewriter) const override { 1753 if (!padTensorOp.result().hasOneUse()) 1754 return failure(); 1755 auto tensorCastOp = 1756 dyn_cast<tensor::CastOp>(*padTensorOp->getUsers().begin()); 1757 if (!tensorCastOp) 1758 return failure(); 1759 if (!tensor::preservesStaticInformation(padTensorOp.result().getType(), 1760 tensorCastOp.dest().getType())) 1761 return failure(); 1762 1763 auto replacementOp = rewriter.create<PadOp>( 1764 padTensorOp.getLoc(), tensorCastOp.dest().getType(), 1765 padTensorOp.source(), padTensorOp.low(), padTensorOp.high(), 1766 padTensorOp.static_low(), padTensorOp.static_high(), 1767 padTensorOp.nofold()); 1768 replacementOp.region().takeBody(padTensorOp.region()); 1769 1770 rewriter.replaceOp(padTensorOp, replacementOp.result()); 1771 rewriter.replaceOp(tensorCastOp, replacementOp.result()); 1772 return success(); 1773 } 1774 }; 1775 } // namespace 1776 1777 void PadOp::getCanonicalizationPatterns(RewritePatternSet &results, 1778 MLIRContext *context) { 1779 results 1780 .add<FoldStaticZeroPadding, FoldSourceTensorCast, FoldTargetTensorCast>( 1781 context); 1782 } 1783 1784 /// Return the padding value of the PadOp if it constant. In this context, 1785 /// "constant" means an actual constant or "defined outside of the block". 1786 /// 1787 /// Values are considered constant in three cases: 1788 /// - A ConstantLike value. 1789 /// - A basic block argument from a different block. 1790 /// - A value defined outside of the block. 1791 /// 1792 /// If the padding value is not constant, an empty Value is returned. 1793 Value PadOp::getConstantPaddingValue() { 1794 auto yieldOp = dyn_cast<YieldOp>(getRegion().front().getTerminator()); 1795 if (!yieldOp) 1796 return {}; 1797 Value padValue = yieldOp.value(); 1798 // Check if yield value is a constant. 1799 if (matchPattern(padValue, m_Constant())) 1800 return padValue; 1801 // Check if yield value is defined inside the PadOp block. 1802 if (padValue.getParentBlock() == &getRegion().front()) 1803 return {}; 1804 // Else: Yield value defined outside of the PadOp block. 1805 return padValue; 1806 } 1807 1808 OpFoldResult PadOp::fold(ArrayRef<Attribute>) { 1809 if (getResultType().hasStaticShape() && getResultType() == getSourceType() && 1810 !nofold()) 1811 return source(); 1812 return {}; 1813 } 1814 1815 //===----------------------------------------------------------------------===// 1816 // SplatOp 1817 //===----------------------------------------------------------------------===// 1818 1819 OpFoldResult SplatOp::fold(ArrayRef<Attribute> operands) { 1820 auto constOperand = operands.front(); 1821 if (!constOperand.isa_and_nonnull<IntegerAttr, FloatAttr>()) 1822 return {}; 1823 1824 // SplatElementsAttr::get treats single value for second arg as being a splat. 1825 return SplatElementsAttr::get(getType(), {constOperand}); 1826 } 1827 1828 //===----------------------------------------------------------------------===// 1829 // TableGen'd op method definitions 1830 //===----------------------------------------------------------------------===// 1831 1832 #define GET_OP_CLASSES 1833 #include "mlir/Dialect/Tensor/IR/TensorOps.cpp.inc" 1834