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 static void print(OpAsmPrinter &p, ExpandShapeOp op) { 737 ::mlir::printReshapeOp<ExpandShapeOp>(p, op); 738 } 739 740 static void print(OpAsmPrinter &p, CollapseShapeOp op) { 741 ::mlir::printReshapeOp<CollapseShapeOp>(p, op); 742 } 743 744 /// Compute the RankedTensorType obtained by applying `reassociation` to `type`. 745 static RankedTensorType 746 computeTensorReshapeCollapsedType(RankedTensorType type, 747 ArrayRef<AffineMap> reassociation) { 748 auto shape = type.getShape(); 749 SmallVector<int64_t, 4> newShape; 750 newShape.reserve(reassociation.size()); 751 752 // Use the fact that reassociation is valid to simplify the logic: only use 753 // each map's rank. 754 assert(isReassociationValid(reassociation) && "invalid reassociation"); 755 unsigned currentDim = 0; 756 for (AffineMap m : reassociation) { 757 unsigned dim = m.getNumResults(); 758 auto band = shape.slice(currentDim, dim); 759 int64_t size = 1; 760 if (llvm::is_contained(band, ShapedType::kDynamicSize)) 761 size = ShapedType::kDynamicSize; 762 else 763 for (unsigned d = 0; d < dim; ++d) 764 size *= shape[currentDim + d]; 765 newShape.push_back(size); 766 currentDim += dim; 767 } 768 769 return RankedTensorType::get(newShape, type.getElementType()); 770 } 771 772 void CollapseShapeOp::build(OpBuilder &b, OperationState &result, Value src, 773 ArrayRef<ReassociationIndices> reassociation, 774 ArrayRef<NamedAttribute> attrs) { 775 auto resultType = computeTensorReshapeCollapsedType( 776 src.getType().cast<RankedTensorType>(), 777 getSymbolLessAffineMaps( 778 convertReassociationIndicesToExprs(b.getContext(), reassociation))); 779 build(b, result, resultType, src, attrs); 780 result.addAttribute(getReassociationAttrName(), 781 getReassociationIndicesAttribute(b, reassociation)); 782 } 783 784 void ExpandShapeOp::build(OpBuilder &b, OperationState &result, Value src, 785 ArrayRef<ReassociationIndices> reassociation, 786 ArrayRef<NamedAttribute> attrs) { 787 auto resultType = computeTensorReshapeCollapsedType( 788 src.getType().cast<RankedTensorType>(), 789 getSymbolLessAffineMaps( 790 convertReassociationIndicesToExprs(b.getContext(), reassociation))); 791 build(b, result, resultType, src, attrs); 792 result.addAttribute(getReassociationAttrName(), 793 getReassociationIndicesAttribute(b, reassociation)); 794 } 795 796 template <typename TensorReshapeOp, bool isExpansion = std::is_same< 797 TensorReshapeOp, ExpandShapeOp>::value> 798 static LogicalResult verifyTensorReshapeOp(TensorReshapeOp op, 799 RankedTensorType expandedType, 800 RankedTensorType collapsedType) { 801 if (failed( 802 verifyReshapeLikeTypes(op, expandedType, collapsedType, isExpansion))) 803 return failure(); 804 805 auto maps = op.getReassociationMaps(); 806 RankedTensorType expectedType = 807 computeTensorReshapeCollapsedType(expandedType, maps); 808 if (collapsedType != expectedType) 809 return op.emitOpError("expected collapsed type to be ") 810 << expectedType << ", but got " << collapsedType; 811 return success(); 812 } 813 814 LogicalResult ExpandShapeOp::verify() { 815 return verifyTensorReshapeOp(*this, getResultType(), getSrcType()); 816 } 817 818 LogicalResult CollapseShapeOp::verify() { 819 return verifyTensorReshapeOp(*this, getSrcType(), getResultType()); 820 } 821 822 namespace { 823 /// Reshape of a splat constant can be replaced with a constant of the result 824 /// type. 825 template <typename TensorReshapeOp> 826 struct FoldReshapeWithConstant : OpRewritePattern<TensorReshapeOp> { 827 using OpRewritePattern<TensorReshapeOp>::OpRewritePattern; 828 LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp, 829 PatternRewriter &rewriter) const override { 830 DenseElementsAttr attr; 831 if (!matchPattern(reshapeOp.src(), m_Constant(&attr))) 832 return failure(); 833 if (!attr || !attr.isSplat()) 834 return failure(); 835 DenseElementsAttr newAttr = DenseElementsAttr::getFromRawBuffer( 836 reshapeOp.getResultType(), attr.getRawData(), true); 837 rewriter.replaceOpWithNewOp<arith::ConstantOp>(reshapeOp, newAttr); 838 return success(); 839 } 840 }; 841 842 /// Reshape of a FromElements can be replaced with a FromElements of the result 843 /// type 844 template <typename TensorReshapeOp> 845 struct FoldReshapeWithFromElements : OpRewritePattern<TensorReshapeOp> { 846 using OpRewritePattern<TensorReshapeOp>::OpRewritePattern; 847 LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp, 848 PatternRewriter &rewriter) const override { 849 auto fromElements = 850 reshapeOp.src().template getDefiningOp<FromElementsOp>(); 851 if (!fromElements) 852 return failure(); 853 854 auto shapedTy = reshapeOp.getType().template cast<ShapedType>(); 855 856 if (!shapedTy.hasStaticShape()) 857 return failure(); 858 859 rewriter.replaceOpWithNewOp<FromElementsOp>(reshapeOp, reshapeOp.getType(), 860 fromElements.elements()); 861 return success(); 862 } 863 }; 864 865 } // namespace 866 867 void ExpandShapeOp::getCanonicalizationPatterns(RewritePatternSet &results, 868 MLIRContext *context) { 869 results.add<CollapseReshapeOps<ExpandShapeOp>, 870 CollapseMixedReshapeOps<ExpandShapeOp, CollapseShapeOp>, 871 FoldReshapeWithConstant<ExpandShapeOp>, 872 FoldReshapeWithFromElements<ExpandShapeOp>>(context); 873 } 874 875 void CollapseShapeOp::getCanonicalizationPatterns(RewritePatternSet &results, 876 MLIRContext *context) { 877 results.add<CollapseReshapeOps<CollapseShapeOp>, 878 CollapseMixedReshapeOps<CollapseShapeOp, ExpandShapeOp>, 879 FoldReshapeWithConstant<CollapseShapeOp>, 880 FoldReshapeWithFromElements<CollapseShapeOp>>(context); 881 } 882 883 OpFoldResult ExpandShapeOp::fold(ArrayRef<Attribute> operands) { 884 return foldReshapeOp<ExpandShapeOp, CollapseShapeOp>(*this, operands); 885 } 886 OpFoldResult CollapseShapeOp::fold(ArrayRef<Attribute> operands) { 887 return foldReshapeOp<CollapseShapeOp, ExpandShapeOp>(*this, operands); 888 } 889 890 //===----------------------------------------------------------------------===// 891 // ExtractSliceOp 892 //===----------------------------------------------------------------------===// 893 894 /// An extract_slice op result type can be fully inferred from the source type 895 /// and the static representation of offsets, sizes and strides. Special 896 /// sentinels encode the dynamic case. 897 RankedTensorType ExtractSliceOp::inferResultType( 898 RankedTensorType sourceRankedTensorType, ArrayRef<int64_t> staticOffsets, 899 ArrayRef<int64_t> staticSizes, ArrayRef<int64_t> staticStrides) { 900 // An extract_slice op may specify only a leading subset of offset/sizes/ 901 // strides in which case we complete with offset=0, sizes from memref type and 902 // strides=1. 903 unsigned rank = sourceRankedTensorType.getRank(); 904 (void)rank; 905 assert(staticSizes.size() == rank && 906 "unexpected staticSizes not equal to rank of source"); 907 return RankedTensorType::get(staticSizes, 908 sourceRankedTensorType.getElementType()); 909 } 910 911 RankedTensorType ExtractSliceOp::inferResultType( 912 RankedTensorType sourceRankedTensorType, ArrayRef<OpFoldResult> offsets, 913 ArrayRef<OpFoldResult> sizes, ArrayRef<OpFoldResult> strides) { 914 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 915 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 916 dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets, 917 ShapedType::kDynamicStrideOrOffset); 918 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 919 ShapedType::kDynamicSize); 920 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 921 ShapedType::kDynamicStrideOrOffset); 922 return ExtractSliceOp::inferResultType(sourceRankedTensorType, staticOffsets, 923 staticSizes, staticStrides); 924 } 925 926 /// An extract_slice op result type can be fully inferred from the source type 927 /// and the static representation of offsets, sizes and strides. Special 928 /// sentinels encode the dynamic case. 929 RankedTensorType ExtractSliceOp::inferRankReducedResultType( 930 unsigned resultRank, RankedTensorType sourceRankedTensorType, 931 ArrayRef<int64_t> offsets, ArrayRef<int64_t> sizes, 932 ArrayRef<int64_t> strides) { 933 auto inferredType = 934 inferResultType(sourceRankedTensorType, offsets, sizes, strides) 935 .cast<RankedTensorType>(); 936 int rankDiff = inferredType.getRank() - resultRank; 937 if (rankDiff > 0) { 938 auto shape = inferredType.getShape(); 939 llvm::SmallBitVector dimsToProject = 940 getPositionsOfShapeOne(rankDiff, shape); 941 SmallVector<int64_t> projectedShape; 942 for (unsigned pos = 0, e = shape.size(); pos < e; ++pos) 943 if (!dimsToProject.test(pos)) 944 projectedShape.push_back(shape[pos]); 945 inferredType = 946 RankedTensorType::get(projectedShape, inferredType.getElementType()); 947 } 948 return inferredType; 949 } 950 951 RankedTensorType ExtractSliceOp::inferRankReducedResultType( 952 unsigned resultRank, RankedTensorType sourceRankedTensorType, 953 ArrayRef<OpFoldResult> offsets, ArrayRef<OpFoldResult> sizes, 954 ArrayRef<OpFoldResult> strides) { 955 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 956 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 957 dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets, 958 ShapedType::kDynamicStrideOrOffset); 959 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 960 ShapedType::kDynamicSize); 961 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 962 ShapedType::kDynamicStrideOrOffset); 963 return ExtractSliceOp::inferRankReducedResultType( 964 resultRank, sourceRankedTensorType, staticOffsets, staticSizes, 965 staticStrides); 966 } 967 968 /// Build an ExtractSliceOp with mixed static and dynamic entries and custom 969 /// result type. If the type passed is nullptr, it is inferred. 970 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, 971 RankedTensorType resultType, Value source, 972 ArrayRef<OpFoldResult> offsets, 973 ArrayRef<OpFoldResult> sizes, 974 ArrayRef<OpFoldResult> strides, 975 ArrayRef<NamedAttribute> attrs) { 976 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 977 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 978 dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets, 979 ShapedType::kDynamicStrideOrOffset); 980 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 981 ShapedType::kDynamicSize); 982 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 983 ShapedType::kDynamicStrideOrOffset); 984 auto sourceRankedTensorType = source.getType().cast<RankedTensorType>(); 985 // Structuring implementation this way avoids duplication between builders. 986 if (!resultType) { 987 resultType = 988 ExtractSliceOp::inferResultType(sourceRankedTensorType, staticOffsets, 989 staticSizes, staticStrides) 990 .cast<RankedTensorType>(); 991 } 992 build(b, result, resultType, source, dynamicOffsets, dynamicSizes, 993 dynamicStrides, b.getI64ArrayAttr(staticOffsets), 994 b.getI64ArrayAttr(staticSizes), b.getI64ArrayAttr(staticStrides)); 995 result.addAttributes(attrs); 996 } 997 998 /// Build an ExtractSliceOp with mixed static and dynamic entries and inferred 999 /// result type. 1000 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, Value source, 1001 ArrayRef<OpFoldResult> offsets, 1002 ArrayRef<OpFoldResult> sizes, 1003 ArrayRef<OpFoldResult> strides, 1004 ArrayRef<NamedAttribute> attrs) { 1005 build(b, result, RankedTensorType(), source, offsets, sizes, strides, attrs); 1006 } 1007 1008 /// Build an ExtractSliceOp with dynamic entries and custom result type. If the 1009 /// type passed is nullptr, it is inferred. 1010 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, 1011 RankedTensorType resultType, Value source, 1012 ValueRange offsets, ValueRange sizes, 1013 ValueRange strides, ArrayRef<NamedAttribute> attrs) { 1014 SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>( 1015 llvm::map_range(offsets, [](Value v) -> OpFoldResult { return v; })); 1016 SmallVector<OpFoldResult> sizeValues = llvm::to_vector<4>( 1017 llvm::map_range(sizes, [](Value v) -> OpFoldResult { return v; })); 1018 SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>( 1019 llvm::map_range(strides, [](Value v) -> OpFoldResult { return v; })); 1020 build(b, result, resultType, source, offsetValues, sizeValues, strideValues); 1021 } 1022 1023 /// Build an ExtractSliceOp with dynamic entries and inferred result type. 1024 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, Value source, 1025 ValueRange offsets, ValueRange sizes, 1026 ValueRange strides, ArrayRef<NamedAttribute> attrs) { 1027 build(b, result, RankedTensorType(), source, offsets, sizes, strides, attrs); 1028 } 1029 1030 template <typename OpTy> 1031 static LogicalResult produceSliceErrorMsg(SliceVerificationResult result, 1032 OpTy op, Type expectedType) { 1033 auto memrefType = expectedType.cast<ShapedType>(); 1034 switch (result) { 1035 case SliceVerificationResult::Success: 1036 return success(); 1037 case SliceVerificationResult::RankTooLarge: 1038 return op.emitError("expected rank to be smaller or equal to ") 1039 << "the other rank. "; 1040 case SliceVerificationResult::SizeMismatch: 1041 return op.emitError("expected type to be ") 1042 << expectedType << " or a rank-reduced version. (size mismatch) "; 1043 case SliceVerificationResult::ElemTypeMismatch: 1044 return op.emitError("expected element type to be ") 1045 << memrefType.getElementType(); 1046 default: 1047 llvm_unreachable("unexpected extract_slice op verification result"); 1048 } 1049 } 1050 1051 /// Verifier for ExtractSliceOp. 1052 LogicalResult ExtractSliceOp::verify() { 1053 // Verify result type against inferred type. 1054 auto expectedType = ExtractSliceOp::inferResultType( 1055 getSourceType(), getMixedOffsets(), getMixedSizes(), getMixedStrides()); 1056 auto result = isRankReducedType(expectedType.cast<ShapedType>(), getType()); 1057 return produceSliceErrorMsg(result, *this, expectedType); 1058 } 1059 1060 /// Infer the canonical type of the result of an extract_slice op. Returns a 1061 /// type with rank `resultRank` that is either the rank of the rank-reduced 1062 /// type, or the non-rank-reduced type. 1063 static RankedTensorType 1064 getCanonicalSliceResultType(unsigned resultRank, RankedTensorType sourceType, 1065 ArrayRef<OpFoldResult> mixedOffsets, 1066 ArrayRef<OpFoldResult> mixedSizes, 1067 ArrayRef<OpFoldResult> mixedStrides) { 1068 auto resultType = 1069 ExtractSliceOp::inferRankReducedResultType( 1070 resultRank, sourceType, mixedOffsets, mixedSizes, mixedStrides) 1071 .cast<RankedTensorType>(); 1072 if (resultType.getRank() != resultRank) { 1073 resultType = ExtractSliceOp::inferResultType(sourceType, mixedOffsets, 1074 mixedSizes, mixedStrides) 1075 .cast<RankedTensorType>(); 1076 } 1077 return resultType; 1078 } 1079 1080 llvm::SmallBitVector ExtractSliceOp::getDroppedDims() { 1081 ArrayRef<int64_t> resultShape = getType().getShape(); 1082 SmallVector<OpFoldResult> mixedSizes = getMixedSizes(); 1083 llvm::SmallBitVector droppedDims(mixedSizes.size()); 1084 unsigned shapePos = 0; 1085 for (const auto &size : enumerate(mixedSizes)) { 1086 Optional<int64_t> sizeVal = getConstantIntValue(size.value()); 1087 // If the size is not 1, or if the current matched dimension of the result 1088 // is the same static shape as the size value (which is 1), then the 1089 // dimension is preserved. 1090 if (!sizeVal || sizeVal.getValue() != 1 || 1091 (shapePos < resultShape.size() && resultShape[shapePos] == 1)) { 1092 shapePos++; 1093 continue; 1094 } 1095 droppedDims.set(size.index()); 1096 } 1097 return droppedDims; 1098 } 1099 1100 LogicalResult ExtractSliceOp::reifyResultShapes( 1101 OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) { 1102 reifiedReturnShapes.resize(1); 1103 reifiedReturnShapes[0].reserve(getType().getRank()); 1104 SmallVector<OpFoldResult> mixedSizes = getMixedSizes(); 1105 llvm::SmallBitVector droppedDims = getDroppedDims(); 1106 Location loc = getLoc(); 1107 for (const auto &size : enumerate(mixedSizes)) { 1108 if (droppedDims.test(size.index())) 1109 continue; 1110 if (auto attr = size.value().dyn_cast<Attribute>()) { 1111 reifiedReturnShapes[0].push_back(builder.create<arith::ConstantIndexOp>( 1112 loc, attr.cast<IntegerAttr>().getInt())); 1113 continue; 1114 } 1115 reifiedReturnShapes[0].push_back(size.value().get<Value>()); 1116 } 1117 return success(); 1118 } 1119 1120 namespace { 1121 /// Pattern to rewrite an extract_slice op with tensor::Cast arguments. 1122 /// This essentially pushes memref_cast past its consuming slice when 1123 /// `canFoldIntoConsumerOp` is true. 1124 /// 1125 /// Example: 1126 /// ``` 1127 /// %0 = tensor.cast %V : tensor<16x16xf32> to tensor<?x?xf32> 1128 /// %1 = tensor.extract_slice %0[0, 0][3, 4][1, 1] : tensor<?x?xf32> to 1129 /// tensor<3x4xf32> 1130 /// ``` 1131 /// is rewritten into: 1132 /// ``` 1133 /// %0 = tensor.extract_slice %V[0, 0][3, 4][1, 1] : tensor<16x16xf32> to 1134 /// tensor<3x4xf32> %1 = tensor.cast %0: tensor<3x4xf32> to tensor<3x4xf32> 1135 /// ``` 1136 class ExtractSliceOpCastFolder final : public OpRewritePattern<ExtractSliceOp> { 1137 public: 1138 using OpRewritePattern<ExtractSliceOp>::OpRewritePattern; 1139 1140 LogicalResult matchAndRewrite(ExtractSliceOp sliceOp, 1141 PatternRewriter &rewriter) const override { 1142 // Any constant operand, just return to let SubViewOpConstantFolder kick in. 1143 if (llvm::any_of(sliceOp.getOperands(), [](Value operand) { 1144 return matchPattern(operand, matchConstantIndex()); 1145 })) 1146 return failure(); 1147 1148 auto castOp = sliceOp.source().getDefiningOp<tensor::CastOp>(); 1149 if (!castOp) 1150 return failure(); 1151 1152 if (!canFoldIntoConsumerOp(castOp)) 1153 return failure(); 1154 1155 /// Deduce the type of the result to use for the canonicalized operation. 1156 RankedTensorType resultType = getCanonicalSliceResultType( 1157 sliceOp.getType().getRank(), sliceOp.getSourceType(), 1158 sliceOp.getMixedOffsets(), sliceOp.getMixedSizes(), 1159 sliceOp.getMixedStrides()); 1160 Value newSlice = rewriter.create<ExtractSliceOp>( 1161 sliceOp.getLoc(), resultType, castOp.source(), sliceOp.offsets(), 1162 sliceOp.sizes(), sliceOp.strides(), sliceOp.static_offsets(), 1163 sliceOp.static_sizes(), sliceOp.static_strides()); 1164 rewriter.replaceOpWithNewOp<tensor::CastOp>(sliceOp, sliceOp.getType(), 1165 newSlice); 1166 return success(); 1167 } 1168 }; 1169 } // namespace 1170 1171 /// Return the canonical type of the result of an extract_slice op. 1172 struct SliceReturnTypeCanonicalizer { 1173 RankedTensorType operator()(ExtractSliceOp op, 1174 ArrayRef<OpFoldResult> mixedOffsets, 1175 ArrayRef<OpFoldResult> mixedSizes, 1176 ArrayRef<OpFoldResult> mixedStrides) { 1177 return getCanonicalSliceResultType(op.getType().getRank(), 1178 op.getSourceType(), mixedOffsets, 1179 mixedSizes, mixedStrides); 1180 } 1181 }; 1182 1183 /// A canonicalizer wrapper to replace ExtractSliceOps. 1184 struct SliceCanonicalizer { 1185 void operator()(PatternRewriter &rewriter, ExtractSliceOp op, 1186 ExtractSliceOp newOp) { 1187 Value replacement = newOp.getResult(); 1188 if (replacement.getType() != op.getType()) 1189 replacement = rewriter.create<tensor::CastOp>(op.getLoc(), op.getType(), 1190 replacement); 1191 rewriter.replaceOp(op, replacement); 1192 } 1193 }; 1194 1195 void ExtractSliceOp::getCanonicalizationPatterns(RewritePatternSet &results, 1196 MLIRContext *context) { 1197 results.add< 1198 OpWithOffsetSizesAndStridesConstantArgumentFolder< 1199 ExtractSliceOp, SliceReturnTypeCanonicalizer, SliceCanonicalizer>, 1200 ExtractSliceOpCastFolder>(context); 1201 } 1202 1203 // 1204 static LogicalResult 1205 foldIdentityOffsetSizeAndStrideOpInterface(OffsetSizeAndStrideOpInterface op, 1206 ShapedType shapedType) { 1207 OpBuilder b(op.getContext()); 1208 for (OpFoldResult ofr : op.getMixedOffsets()) 1209 if (getConstantIntValue(ofr) != static_cast<int64_t>(0)) 1210 return failure(); 1211 // Rank-reducing noops only need to inspect the leading dimensions: llvm::zip 1212 // is appropriate. 1213 auto shape = shapedType.getShape(); 1214 for (auto it : llvm::zip(op.getMixedSizes(), shape)) 1215 if (getConstantIntValue(std::get<0>(it)) != std::get<1>(it)) 1216 return failure(); 1217 for (OpFoldResult ofr : op.getMixedStrides()) 1218 if (getConstantIntValue(ofr) != static_cast<int64_t>(1)) 1219 return failure(); 1220 return success(); 1221 } 1222 1223 /// If we have an ExtractSliceOp consuming an InsertSliceOp with the same slice, 1224 /// we can return the InsertSliceOp's source directly. 1225 // TODO: This only checks the immediate producer; extend to go up the 1226 // insert/extract chain if the slices are disjoint. 1227 static Value foldExtractAfterInsertSlice(ExtractSliceOp extractOp) { 1228 auto insertOp = extractOp.source().getDefiningOp<InsertSliceOp>(); 1229 1230 auto isSame = [](OpFoldResult a, OpFoldResult b) { return a == b; }; 1231 if (insertOp && insertOp.source().getType() == extractOp.getType() && 1232 insertOp.isSameAs(extractOp, isSame)) 1233 return insertOp.source(); 1234 1235 return {}; 1236 } 1237 1238 OpFoldResult ExtractSliceOp::fold(ArrayRef<Attribute>) { 1239 if (getSourceType() == getType() && 1240 succeeded(foldIdentityOffsetSizeAndStrideOpInterface(*this, getType()))) 1241 return this->source(); 1242 if (Value slice = foldExtractAfterInsertSlice(*this)) 1243 return slice; 1244 return OpFoldResult(); 1245 } 1246 1247 Value mlir::tensor::createCanonicalRankReducingExtractSliceOp( 1248 OpBuilder &b, Location loc, Value tensor, RankedTensorType targetType) { 1249 auto rankedTensorType = tensor.getType().cast<RankedTensorType>(); 1250 unsigned rank = rankedTensorType.getRank(); 1251 auto shape = rankedTensorType.getShape(); 1252 SmallVector<OpFoldResult> offsets(rank, b.getIndexAttr(0)); 1253 SmallVector<OpFoldResult> sizes; 1254 for (unsigned i = 0, e = rank; i < e; ++i) { 1255 OpFoldResult dim; 1256 if (rankedTensorType.isDynamicDim(i)) 1257 dim = b.createOrFold<tensor::DimOp>( 1258 loc, tensor, b.create<arith::ConstantIndexOp>(loc, i)); 1259 else 1260 dim = b.getIndexAttr(shape[i]); 1261 sizes.push_back(dim); 1262 } 1263 SmallVector<OpFoldResult> strides(rank, b.getIndexAttr(1)); 1264 return b.createOrFold<tensor::ExtractSliceOp>(loc, targetType, tensor, 1265 offsets, sizes, strides); 1266 } 1267 1268 //===----------------------------------------------------------------------===// 1269 // InsertSliceOp 1270 //===----------------------------------------------------------------------===// 1271 1272 // Build a InsertSliceOp with mixed static and dynamic entries. 1273 void InsertSliceOp::build(OpBuilder &b, OperationState &result, Value source, 1274 Value dest, ArrayRef<OpFoldResult> offsets, 1275 ArrayRef<OpFoldResult> sizes, 1276 ArrayRef<OpFoldResult> strides, 1277 ArrayRef<NamedAttribute> attrs) { 1278 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 1279 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 1280 dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets, 1281 ShapedType::kDynamicStrideOrOffset); 1282 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 1283 ShapedType::kDynamicSize); 1284 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 1285 ShapedType::kDynamicStrideOrOffset); 1286 build(b, result, dest.getType(), source, dest, dynamicOffsets, dynamicSizes, 1287 dynamicStrides, b.getI64ArrayAttr(staticOffsets), 1288 b.getI64ArrayAttr(staticSizes), b.getI64ArrayAttr(staticStrides)); 1289 result.addAttributes(attrs); 1290 } 1291 1292 // Build a InsertSliceOp with dynamic entries. 1293 void InsertSliceOp::build(OpBuilder &b, OperationState &result, Value source, 1294 Value dest, ValueRange offsets, ValueRange sizes, 1295 ValueRange strides, ArrayRef<NamedAttribute> attrs) { 1296 SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>( 1297 llvm::map_range(offsets, [](Value v) -> OpFoldResult { return v; })); 1298 SmallVector<OpFoldResult> sizeValues = llvm::to_vector<4>( 1299 llvm::map_range(sizes, [](Value v) -> OpFoldResult { return v; })); 1300 SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>( 1301 llvm::map_range(strides, [](Value v) -> OpFoldResult { return v; })); 1302 build(b, result, source, dest, offsetValues, sizeValues, strideValues); 1303 } 1304 1305 /// Verifier for InsertSliceOp. 1306 LogicalResult InsertSliceOp::verify() { 1307 // insert_slice is the inverse of extract_slice, use the same type inference. 1308 auto expectedType = ExtractSliceOp::inferRankReducedResultType( 1309 getSourceType().getRank(), getType(), 1310 extractFromI64ArrayAttr(static_offsets()), 1311 extractFromI64ArrayAttr(static_sizes()), 1312 extractFromI64ArrayAttr(static_strides())); 1313 auto result = 1314 isRankReducedType(expectedType.cast<ShapedType>(), getSourceType()); 1315 return produceSliceErrorMsg(result, *this, expectedType); 1316 } 1317 1318 /// If we have two consecutive InsertSliceOp writing to the same slice, we 1319 /// can mutate the second InsertSliceOp's destination to the first one's. 1320 /// 1321 /// Example: 1322 /// 1323 /// ```mlir 1324 /// %0 = tensor.insert_slice %slice0 into %input[0, 0] [64, 64] [1, 1] 1325 /// %1 = tensor.insert_slice %slice1 into %0[0, 0] [64, 64] [1, 1] 1326 /// ``` 1327 /// 1328 /// folds into: 1329 /// 1330 /// ```mlir 1331 /// %1 = tensor.insert_slice %slice1 into %input[0, 0] [64, 64] [1, 1] 1332 /// ``` 1333 static LogicalResult foldInsertAfterInsertSlice(InsertSliceOp insertOp) { 1334 auto prevInsertOp = insertOp.dest().getDefiningOp<InsertSliceOp>(); 1335 1336 auto isSame = [](OpFoldResult a, OpFoldResult b) { return a == b; }; 1337 if (!prevInsertOp || 1338 prevInsertOp.source().getType() != insertOp.source().getType() || 1339 !prevInsertOp.isSameAs(insertOp, isSame)) 1340 return failure(); 1341 1342 insertOp.destMutable().assign(prevInsertOp.dest()); 1343 return success(); 1344 } 1345 1346 OpFoldResult InsertSliceOp::fold(ArrayRef<Attribute>) { 1347 if (getSourceType().hasStaticShape() && getType().hasStaticShape() && 1348 getSourceType() == getType() && 1349 succeeded(foldIdentityOffsetSizeAndStrideOpInterface(*this, getType()))) 1350 return this->source(); 1351 if (succeeded(foldInsertAfterInsertSlice(*this))) 1352 return getResult(); 1353 return OpFoldResult(); 1354 } 1355 1356 LogicalResult InsertSliceOp::reifyResultShapes( 1357 OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) { 1358 reifiedReturnShapes.resize(1, SmallVector<Value>(getType().getRank())); 1359 for (auto dim : llvm::seq<int64_t>(0, getType().getRank())) { 1360 reifiedReturnShapes[0][dim] = 1361 builder.createOrFold<tensor::DimOp>(getLoc(), dest(), dim); 1362 } 1363 return success(); 1364 } 1365 1366 namespace { 1367 /// Pattern to rewrite a insert_slice op with constant arguments. 1368 class InsertSliceOpConstantArgumentFolder final 1369 : public OpRewritePattern<InsertSliceOp> { 1370 public: 1371 using OpRewritePattern<InsertSliceOp>::OpRewritePattern; 1372 1373 LogicalResult matchAndRewrite(InsertSliceOp insertSliceOp, 1374 PatternRewriter &rewriter) const override { 1375 // No constant operand, just return. 1376 if (llvm::none_of(insertSliceOp.getOperands(), [](Value operand) { 1377 return matchPattern(operand, matchConstantIndex()); 1378 })) 1379 return failure(); 1380 1381 // At least one of offsets/sizes/strides is a new constant. 1382 // Form the new list of operands and constant attributes from the 1383 // existing. 1384 SmallVector<OpFoldResult> mixedOffsets(insertSliceOp.getMixedOffsets()); 1385 SmallVector<OpFoldResult> mixedSizes(insertSliceOp.getMixedSizes()); 1386 SmallVector<OpFoldResult> mixedStrides(insertSliceOp.getMixedStrides()); 1387 canonicalizeSubViewPart(mixedOffsets, ShapedType::isDynamicStrideOrOffset); 1388 canonicalizeSubViewPart(mixedSizes, ShapedType::isDynamic); 1389 canonicalizeSubViewPart(mixedStrides, ShapedType::isDynamicStrideOrOffset); 1390 1391 // Create the new op in canonical form. 1392 auto sourceType = ExtractSliceOp::inferRankReducedResultType( 1393 insertSliceOp.getSourceType().getRank(), insertSliceOp.getType(), 1394 mixedOffsets, mixedSizes, mixedStrides); 1395 Value toInsert = insertSliceOp.source(); 1396 if (sourceType != insertSliceOp.getSourceType()) 1397 toInsert = rewriter.create<tensor::CastOp>(insertSliceOp.getLoc(), 1398 sourceType, toInsert); 1399 rewriter.replaceOpWithNewOp<InsertSliceOp>( 1400 insertSliceOp, toInsert, insertSliceOp.dest(), mixedOffsets, mixedSizes, 1401 mixedStrides); 1402 return success(); 1403 } 1404 }; 1405 1406 /// Fold tensor_casts with insert_slice operations. If the source or destination 1407 /// tensor is a tensor_cast that removes static type information, the cast is 1408 /// folded into the insert_slice operation. E.g.: 1409 /// 1410 /// ```mlir 1411 /// %1 = tensor.cast %0 : tensor<8x16xf32> to tensor<?x?xf32> 1412 /// %2 = tensor.insert_slice %1 into ... : tensor<?x?xf32> into ... 1413 /// ``` 1414 /// 1415 /// folds into: 1416 /// 1417 /// ```mlir 1418 /// %2 = tensor.insert_slice %0 into ... : tensor<8x16xf32> into ... 1419 /// ``` 1420 /// 1421 /// Note: When folding a cast on the destination tensor, the result of the 1422 /// insert_slice operation is casted to ensure that the type of the result did 1423 /// not change. 1424 struct InsertSliceOpCastFolder final : public OpRewritePattern<InsertSliceOp> { 1425 using OpRewritePattern<InsertSliceOp>::OpRewritePattern; 1426 1427 LogicalResult matchAndRewrite(InsertSliceOp insertSliceOp, 1428 PatternRewriter &rewriter) const override { 1429 if (llvm::any_of(insertSliceOp.getOperands(), [](Value operand) { 1430 return matchPattern(operand, matchConstantIndex()); 1431 })) 1432 return failure(); 1433 1434 auto getSourceOfCastOp = [](Value v) -> Optional<Value> { 1435 auto castOp = v.getDefiningOp<tensor::CastOp>(); 1436 if (!castOp || !canFoldIntoConsumerOp(castOp)) 1437 return llvm::None; 1438 return castOp.source(); 1439 }; 1440 Optional<Value> sourceCastSource = 1441 getSourceOfCastOp(insertSliceOp.source()); 1442 Optional<Value> destCastSource = getSourceOfCastOp(insertSliceOp.dest()); 1443 if (!sourceCastSource && !destCastSource) 1444 return failure(); 1445 1446 Value replacement = rewriter.create<InsertSliceOp>( 1447 insertSliceOp.getLoc(), 1448 (sourceCastSource ? *sourceCastSource : insertSliceOp.source()), 1449 (destCastSource ? *destCastSource : insertSliceOp.dest()), 1450 insertSliceOp.getMixedOffsets(), insertSliceOp.getMixedSizes(), 1451 insertSliceOp.getMixedStrides()); 1452 1453 if (replacement.getType() != insertSliceOp.getType()) { 1454 replacement = rewriter.create<tensor::CastOp>( 1455 insertSliceOp.getLoc(), insertSliceOp.getType(), replacement); 1456 } 1457 rewriter.replaceOp(insertSliceOp, replacement); 1458 return success(); 1459 } 1460 }; 1461 1462 /// If additional static type information can be deduced from a insert_slice's 1463 /// size operands, insert an explicit cast of the op's source operand. This 1464 /// enables other canonicalization patterns that are matching for tensor_cast 1465 /// ops such as `ForOpTensorCastFolder` in SCF. 1466 /// 1467 /// Example: 1468 /// 1469 /// ```mlir 1470 /// %r = tensor.insert_slice %0 into %1[...] [64, 64] [1, 1] 1471 /// : tensor<?x?xf32> into ... 1472 /// ``` 1473 /// 1474 /// folds into: 1475 /// 1476 /// ```mlir 1477 /// %tmp = tensor.cast %0 : tensor<?x?xf32> to tensor<64x64xf32> 1478 /// %r = tensor.insert_slice %tmp into %1[...] [64, 64] [1, 1] 1479 /// : tensor<64x64xf32> into ... 1480 /// ``` 1481 struct InsertSliceOpSourceCastInserter final 1482 : public OpRewritePattern<InsertSliceOp> { 1483 using OpRewritePattern<InsertSliceOp>::OpRewritePattern; 1484 1485 LogicalResult matchAndRewrite(InsertSliceOp insertSliceOp, 1486 PatternRewriter &rewriter) const override { 1487 RankedTensorType srcType = insertSliceOp.getSourceType(); 1488 if (srcType.getRank() != insertSliceOp.getType().getRank()) 1489 return failure(); 1490 SmallVector<int64_t> newSrcShape(srcType.getShape().begin(), 1491 srcType.getShape().end()); 1492 for (int64_t i = 0; i < srcType.getRank(); ++i) { 1493 if (Optional<int64_t> constInt = 1494 getConstantIntValue(insertSliceOp.getMixedSizes()[i])) 1495 newSrcShape[i] = *constInt; 1496 } 1497 1498 RankedTensorType newSrcType = 1499 RankedTensorType::get(newSrcShape, srcType.getElementType()); 1500 if (srcType == newSrcType || 1501 !preservesStaticInformation(srcType, newSrcType) || 1502 !tensor::CastOp::areCastCompatible(srcType, newSrcType)) 1503 return failure(); 1504 1505 // newSrcType is: 1506 // 1) Different from srcType. 1507 // 2) "More static" than srcType. 1508 // 3) Cast-compatible with srcType. 1509 // Insert the cast. 1510 Value cast = rewriter.create<tensor::CastOp>( 1511 insertSliceOp.getLoc(), newSrcType, insertSliceOp.source()); 1512 rewriter.replaceOpWithNewOp<InsertSliceOp>( 1513 insertSliceOp, cast, insertSliceOp.dest(), 1514 insertSliceOp.getMixedOffsets(), insertSliceOp.getMixedSizes(), 1515 insertSliceOp.getMixedStrides()); 1516 return success(); 1517 } 1518 }; 1519 } // namespace 1520 1521 void InsertSliceOp::getCanonicalizationPatterns(RewritePatternSet &results, 1522 MLIRContext *context) { 1523 results.add<InsertSliceOpConstantArgumentFolder, InsertSliceOpCastFolder, 1524 InsertSliceOpSourceCastInserter>(context); 1525 } 1526 1527 Value mlir::tensor::createCanonicalRankReducingInsertSliceOp(OpBuilder &b, 1528 Location loc, 1529 Value tensor, 1530 Value dest) { 1531 auto rankedTensorType = dest.getType().cast<RankedTensorType>(); 1532 unsigned rank = rankedTensorType.getRank(); 1533 auto shape = rankedTensorType.getShape(); 1534 SmallVector<OpFoldResult> offsets(rank, b.getIndexAttr(0)); 1535 SmallVector<OpFoldResult> sizes; 1536 for (unsigned i = 0, e = rank; i < e; ++i) { 1537 OpFoldResult dim; 1538 if (rankedTensorType.isDynamicDim(i)) 1539 dim = b.createOrFold<tensor::DimOp>( 1540 loc, dest, b.create<arith::ConstantIndexOp>(loc, i)); 1541 else 1542 dim = b.getIndexAttr(shape[i]); 1543 sizes.push_back(dim); 1544 } 1545 SmallVector<OpFoldResult> strides(rank, b.getIndexAttr(1)); 1546 return b.createOrFold<tensor::InsertSliceOp>(loc, tensor, dest, offsets, 1547 sizes, strides); 1548 } 1549 1550 //===----------------------------------------------------------------------===// 1551 // PadOp 1552 //===----------------------------------------------------------------------===// 1553 1554 // TODO: Replace custom<InferType> directive with AllTypesMatch as soon as it 1555 // supports optional types. 1556 void printInferType(OpAsmPrinter &printer, Operation *op, Value optOperand, 1557 Type typeToInfer, Type typeToInferFrom) {} 1558 1559 ParseResult parseInferType(OpAsmParser &parser, 1560 Optional<OpAsmParser::OperandType> optOperand, 1561 Type &typeToInfer, Type typeToInferFrom) { 1562 if (optOperand) 1563 typeToInfer = typeToInferFrom; 1564 return success(); 1565 } 1566 1567 LogicalResult PadOp::verify() { 1568 auto sourceType = source().getType().cast<RankedTensorType>(); 1569 auto resultType = result().getType().cast<RankedTensorType>(); 1570 auto expectedType = 1571 PadOp::inferResultType(sourceType, extractFromI64ArrayAttr(static_low()), 1572 extractFromI64ArrayAttr(static_high())); 1573 for (int i = 0, e = sourceType.getRank(); i < e; ++i) { 1574 if (resultType.getDimSize(i) == expectedType.getDimSize(i)) 1575 continue; 1576 if (expectedType.isDynamicDim(i)) 1577 continue; 1578 return emitError("specified type ") 1579 << resultType << " does not match the inferred type " 1580 << expectedType; 1581 } 1582 1583 auto ®ion = getRegion(); 1584 unsigned rank = resultType.getRank(); 1585 Block &block = region.front(); 1586 if (block.getNumArguments() != rank) 1587 return emitError("expected the block to have ") << rank << " arguments"; 1588 1589 // Note: the number and type of yield values are checked in the YieldOp. 1590 for (const auto &en : llvm::enumerate(block.getArgumentTypes())) { 1591 if (!en.value().isIndex()) 1592 return emitOpError("expected block argument ") 1593 << (en.index() + 1) << " to be an index"; 1594 } 1595 1596 // Ensure that the region yields an element of the right type. 1597 auto yieldOp = llvm::cast<YieldOp>(block.getTerminator()); 1598 if (yieldOp.value().getType() != 1599 getType().cast<ShapedType>().getElementType()) 1600 return emitOpError("expected yield type to match shape element type"); 1601 1602 return success(); 1603 } 1604 1605 RankedTensorType PadOp::inferResultType(RankedTensorType sourceType, 1606 ArrayRef<int64_t> staticLow, 1607 ArrayRef<int64_t> staticHigh, 1608 ArrayRef<int64_t> resultShape) { 1609 unsigned rank = sourceType.getRank(); 1610 assert(staticLow.size() == rank && "unexpected staticLow size mismatch"); 1611 assert(staticHigh.size() == rank && "unexpected staticHigh size mismatch"); 1612 assert((resultShape.empty() || resultShape.size() == rank) && 1613 "unexpected resultShape size mismatch"); 1614 1615 SmallVector<int64_t, 4> inferredShape; 1616 for (auto i : llvm::seq<unsigned>(0, rank)) { 1617 if (sourceType.isDynamicDim(i) || 1618 staticLow[i] == ShapedType::kDynamicSize || 1619 staticHigh[i] == ShapedType::kDynamicSize) { 1620 inferredShape.push_back(resultShape.empty() ? ShapedType::kDynamicSize 1621 : resultShape[i]); 1622 } else { 1623 int64_t size = sourceType.getDimSize(i) + staticLow[i] + staticHigh[i]; 1624 assert((resultShape.empty() || size == resultShape[i] || 1625 resultShape[i] == ShapedType::kDynamicSize) && 1626 "mismatch between inferred shape and result shape"); 1627 inferredShape.push_back(size); 1628 } 1629 } 1630 1631 return RankedTensorType::get(inferredShape, sourceType.getElementType()); 1632 } 1633 1634 void PadOp::build(OpBuilder &b, OperationState &result, Value source, 1635 ArrayRef<int64_t> staticLow, ArrayRef<int64_t> staticHigh, 1636 ValueRange low, ValueRange high, bool nofold, 1637 ArrayRef<NamedAttribute> attrs) { 1638 auto sourceType = source.getType().cast<RankedTensorType>(); 1639 auto resultType = inferResultType(sourceType, staticLow, staticHigh); 1640 build(b, result, resultType, source, low, high, b.getI64ArrayAttr(staticLow), 1641 b.getI64ArrayAttr(staticHigh), nofold ? b.getUnitAttr() : UnitAttr()); 1642 result.addAttributes(attrs); 1643 } 1644 1645 void PadOp::build(OpBuilder &b, OperationState &result, Value source, 1646 ValueRange low, ValueRange high, bool nofold, 1647 ArrayRef<NamedAttribute> attrs) { 1648 auto sourceType = source.getType().cast<RankedTensorType>(); 1649 unsigned rank = sourceType.getRank(); 1650 SmallVector<int64_t, 4> staticVector(rank, ShapedType::kDynamicSize); 1651 build(b, result, source, staticVector, staticVector, low, high, nofold, 1652 attrs); 1653 } 1654 1655 void PadOp::build(OpBuilder &b, OperationState &result, Type resultType, 1656 Value source, ArrayRef<OpFoldResult> low, 1657 ArrayRef<OpFoldResult> high, bool nofold, 1658 ArrayRef<NamedAttribute> attrs) { 1659 assert(resultType.isa<RankedTensorType>()); 1660 auto sourceType = source.getType().cast<RankedTensorType>(); 1661 SmallVector<Value, 4> dynamicLow, dynamicHigh; 1662 SmallVector<int64_t, 4> staticLow, staticHigh; 1663 // staticLow and staticHigh have full information of the padding config. 1664 // This will grow staticLow and staticHigh with 1 value. If the config is 1665 // dynamic (ie not a constant), dynamicLow and dynamicHigh will grow with 1 1666 // value as well. 1667 dispatchIndexOpFoldResults(low, dynamicLow, staticLow, 1668 ShapedType::kDynamicSize); 1669 dispatchIndexOpFoldResults(high, dynamicHigh, staticHigh, 1670 ShapedType::kDynamicSize); 1671 if (!resultType) { 1672 resultType = PadOp::inferResultType(sourceType, staticLow, staticHigh); 1673 } 1674 build(b, result, resultType, source, dynamicLow, dynamicHigh, 1675 b.getI64ArrayAttr(staticLow), b.getI64ArrayAttr(staticHigh), 1676 nofold ? b.getUnitAttr() : UnitAttr()); 1677 result.addAttributes(attrs); 1678 } 1679 1680 namespace { 1681 // Folds tensor.pad when padding is static zeros and the attribute 1682 // doesn't request otherwise. 1683 struct FoldStaticZeroPadding : public OpRewritePattern<PadOp> { 1684 using OpRewritePattern<PadOp>::OpRewritePattern; 1685 1686 LogicalResult matchAndRewrite(PadOp padTensorOp, 1687 PatternRewriter &rewriter) const override { 1688 if (!padTensorOp.hasZeroLowPad() || !padTensorOp.hasZeroHighPad()) 1689 return failure(); 1690 if (padTensorOp.nofold()) 1691 return failure(); 1692 rewriter.replaceOpWithNewOp<tensor::CastOp>( 1693 padTensorOp, padTensorOp.result().getType(), padTensorOp.source()); 1694 return success(); 1695 } 1696 }; 1697 1698 // Fold CastOp into PadOp when adding static information. 1699 struct FoldSourceTensorCast : public OpRewritePattern<PadOp> { 1700 using OpRewritePattern<PadOp>::OpRewritePattern; 1701 1702 LogicalResult matchAndRewrite(PadOp padTensorOp, 1703 PatternRewriter &rewriter) const override { 1704 auto castOp = padTensorOp.source().getDefiningOp<tensor::CastOp>(); 1705 if (!tensor::canFoldIntoConsumerOp(castOp)) 1706 return failure(); 1707 1708 auto newResultType = PadOp::inferResultType( 1709 castOp.source().getType().cast<RankedTensorType>(), 1710 extractFromI64ArrayAttr(padTensorOp.static_low()), 1711 extractFromI64ArrayAttr(padTensorOp.static_high()), 1712 padTensorOp.getResultType().getShape()); 1713 1714 if (newResultType == padTensorOp.getResultType()) { 1715 rewriter.updateRootInPlace(padTensorOp, [&]() { 1716 padTensorOp.sourceMutable().assign(castOp.source()); 1717 }); 1718 } else { 1719 auto newOp = rewriter.create<PadOp>( 1720 padTensorOp->getLoc(), newResultType, padTensorOp.source(), 1721 padTensorOp.low(), padTensorOp.high(), padTensorOp.static_low(), 1722 padTensorOp.static_high(), padTensorOp.nofold()); 1723 BlockAndValueMapping mapper; 1724 padTensorOp.getRegion().cloneInto(&newOp.getRegion(), mapper); 1725 1726 rewriter.replaceOpWithNewOp<tensor::CastOp>( 1727 padTensorOp, padTensorOp.getResultType(), newOp); 1728 } 1729 return success(); 1730 } 1731 }; 1732 1733 // Fold CastOp using the result of PadOp back into the latter if it adds 1734 // static information. 1735 struct FoldTargetTensorCast : public OpRewritePattern<PadOp> { 1736 using OpRewritePattern<PadOp>::OpRewritePattern; 1737 1738 LogicalResult matchAndRewrite(PadOp padTensorOp, 1739 PatternRewriter &rewriter) const override { 1740 if (!padTensorOp.result().hasOneUse()) 1741 return failure(); 1742 auto tensorCastOp = 1743 dyn_cast<tensor::CastOp>(*padTensorOp->getUsers().begin()); 1744 if (!tensorCastOp) 1745 return failure(); 1746 if (!tensor::preservesStaticInformation(padTensorOp.result().getType(), 1747 tensorCastOp.dest().getType())) 1748 return failure(); 1749 1750 auto replacementOp = rewriter.create<PadOp>( 1751 padTensorOp.getLoc(), tensorCastOp.dest().getType(), 1752 padTensorOp.source(), padTensorOp.low(), padTensorOp.high(), 1753 padTensorOp.static_low(), padTensorOp.static_high(), 1754 padTensorOp.nofold()); 1755 replacementOp.region().takeBody(padTensorOp.region()); 1756 1757 rewriter.replaceOp(padTensorOp, replacementOp.result()); 1758 rewriter.replaceOp(tensorCastOp, replacementOp.result()); 1759 return success(); 1760 } 1761 }; 1762 } // namespace 1763 1764 void PadOp::getCanonicalizationPatterns(RewritePatternSet &results, 1765 MLIRContext *context) { 1766 results 1767 .add<FoldStaticZeroPadding, FoldSourceTensorCast, FoldTargetTensorCast>( 1768 context); 1769 } 1770 1771 /// Return the padding value of the PadOp if it constant. In this context, 1772 /// "constant" means an actual constant or "defined outside of the block". 1773 /// 1774 /// Values are considered constant in three cases: 1775 /// - A ConstantLike value. 1776 /// - A basic block argument from a different block. 1777 /// - A value defined outside of the block. 1778 /// 1779 /// If the padding value is not constant, an empty Value is returned. 1780 Value PadOp::getConstantPaddingValue() { 1781 auto yieldOp = dyn_cast<YieldOp>(getRegion().front().getTerminator()); 1782 if (!yieldOp) 1783 return {}; 1784 Value padValue = yieldOp.value(); 1785 // Check if yield value is a constant. 1786 if (matchPattern(padValue, m_Constant())) 1787 return padValue; 1788 // Check if yield value is defined inside the PadOp block. 1789 if (padValue.getParentBlock() == &getRegion().front()) 1790 return {}; 1791 // Else: Yield value defined outside of the PadOp block. 1792 return padValue; 1793 } 1794 1795 OpFoldResult PadOp::fold(ArrayRef<Attribute>) { 1796 if (getResultType().hasStaticShape() && getResultType() == getSourceType() && 1797 !nofold()) 1798 return source(); 1799 return {}; 1800 } 1801 1802 //===----------------------------------------------------------------------===// 1803 // SplatOp 1804 //===----------------------------------------------------------------------===// 1805 1806 OpFoldResult SplatOp::fold(ArrayRef<Attribute> operands) { 1807 auto constOperand = operands.front(); 1808 if (!constOperand.isa_and_nonnull<IntegerAttr, FloatAttr>()) 1809 return {}; 1810 1811 // SplatElementsAttr::get treats single value for second arg as being a splat. 1812 return SplatElementsAttr::get(getType(), {constOperand}); 1813 } 1814 1815 //===----------------------------------------------------------------------===// 1816 // TableGen'd op method definitions 1817 //===----------------------------------------------------------------------===// 1818 1819 #define GET_OP_CLASSES 1820 #include "mlir/Dialect/Tensor/IR/TensorOps.cpp.inc" 1821