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