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