1 //===----------------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 10 #include "mlir/Dialect/Arithmetic/Utils/Utils.h" 11 #include "mlir/Dialect/MemRef/IR/MemRef.h" 12 #include "mlir/Dialect/MemRef/Utils/MemRefUtils.h" 13 #include "mlir/Dialect/Utils/StaticValueUtils.h" 14 #include "mlir/IR/AffineMap.h" 15 #include "mlir/IR/Builders.h" 16 #include "mlir/IR/BuiltinTypes.h" 17 #include "mlir/IR/Matchers.h" 18 #include "mlir/IR/PatternMatch.h" 19 #include "mlir/IR/TypeUtilities.h" 20 #include "mlir/Interfaces/InferTypeOpInterface.h" 21 #include "mlir/Interfaces/SideEffectInterfaces.h" 22 #include "mlir/Interfaces/ViewLikeInterface.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallBitVector.h" 25 26 using namespace mlir; 27 using namespace mlir::memref; 28 29 /// Materialize a single constant operation from a given attribute value with 30 /// the desired resultant type. 31 Operation *MemRefDialect::materializeConstant(OpBuilder &builder, 32 Attribute value, Type type, 33 Location loc) { 34 if (arith::ConstantOp::isBuildableWith(value, type)) 35 return builder.create<arith::ConstantOp>(loc, value, type); 36 return nullptr; 37 } 38 39 //===----------------------------------------------------------------------===// 40 // Common canonicalization pattern support logic 41 //===----------------------------------------------------------------------===// 42 43 /// This is a common class used for patterns of the form 44 /// "someop(memrefcast) -> someop". It folds the source of any memref.cast 45 /// into the root operation directly. 46 LogicalResult mlir::memref::foldMemRefCast(Operation *op, Value inner) { 47 bool folded = false; 48 for (OpOperand &operand : op->getOpOperands()) { 49 auto cast = operand.get().getDefiningOp<CastOp>(); 50 if (cast && operand.get() != inner && 51 !cast.getOperand().getType().isa<UnrankedMemRefType>()) { 52 operand.set(cast.getOperand()); 53 folded = true; 54 } 55 } 56 return success(folded); 57 } 58 59 /// Return an unranked/ranked tensor type for the given unranked/ranked memref 60 /// type. 61 Type mlir::memref::getTensorTypeFromMemRefType(Type type) { 62 if (auto memref = type.dyn_cast<MemRefType>()) 63 return RankedTensorType::get(memref.getShape(), memref.getElementType()); 64 if (auto memref = type.dyn_cast<UnrankedMemRefType>()) 65 return UnrankedTensorType::get(memref.getElementType()); 66 return NoneType::get(type.getContext()); 67 } 68 69 //===----------------------------------------------------------------------===// 70 // AllocOp / AllocaOp 71 //===----------------------------------------------------------------------===// 72 73 template <typename AllocLikeOp> 74 static LogicalResult verifyAllocLikeOp(AllocLikeOp op) { 75 static_assert(llvm::is_one_of<AllocLikeOp, AllocOp, AllocaOp>::value, 76 "applies to only alloc or alloca"); 77 auto memRefType = op.getResult().getType().template dyn_cast<MemRefType>(); 78 if (!memRefType) 79 return op.emitOpError("result must be a memref"); 80 81 if (static_cast<int64_t>(op.dynamicSizes().size()) != 82 memRefType.getNumDynamicDims()) 83 return op.emitOpError("dimension operand count does not equal memref " 84 "dynamic dimension count"); 85 86 unsigned numSymbols = 0; 87 if (!memRefType.getLayout().isIdentity()) 88 numSymbols = memRefType.getLayout().getAffineMap().getNumSymbols(); 89 if (op.symbolOperands().size() != numSymbols) 90 return op.emitOpError("symbol operand count does not equal memref symbol " 91 "count: expected ") 92 << numSymbols << ", got " << op.symbolOperands().size(); 93 94 return success(); 95 } 96 97 LogicalResult AllocOp::verify() { return verifyAllocLikeOp(*this); } 98 99 LogicalResult AllocaOp::verify() { 100 // An alloca op needs to have an ancestor with an allocation scope trait. 101 if (!(*this)->getParentWithTrait<OpTrait::AutomaticAllocationScope>()) 102 return emitOpError( 103 "requires an ancestor op with AutomaticAllocationScope trait"); 104 105 return verifyAllocLikeOp(*this); 106 } 107 108 namespace { 109 /// Fold constant dimensions into an alloc like operation. 110 template <typename AllocLikeOp> 111 struct SimplifyAllocConst : public OpRewritePattern<AllocLikeOp> { 112 using OpRewritePattern<AllocLikeOp>::OpRewritePattern; 113 114 LogicalResult matchAndRewrite(AllocLikeOp alloc, 115 PatternRewriter &rewriter) const override { 116 // Check to see if any dimensions operands are constants. If so, we can 117 // substitute and drop them. 118 if (llvm::none_of(alloc.dynamicSizes(), [](Value operand) { 119 return matchPattern(operand, matchConstantIndex()); 120 })) 121 return failure(); 122 123 auto memrefType = alloc.getType(); 124 125 // Ok, we have one or more constant operands. Collect the non-constant ones 126 // and keep track of the resultant memref type to build. 127 SmallVector<int64_t, 4> newShapeConstants; 128 newShapeConstants.reserve(memrefType.getRank()); 129 SmallVector<Value, 4> dynamicSizes; 130 131 unsigned dynamicDimPos = 0; 132 for (unsigned dim = 0, e = memrefType.getRank(); dim < e; ++dim) { 133 int64_t dimSize = memrefType.getDimSize(dim); 134 // If this is already static dimension, keep it. 135 if (dimSize != -1) { 136 newShapeConstants.push_back(dimSize); 137 continue; 138 } 139 auto dynamicSize = alloc.dynamicSizes()[dynamicDimPos]; 140 auto *defOp = dynamicSize.getDefiningOp(); 141 if (auto constantIndexOp = 142 dyn_cast_or_null<arith::ConstantIndexOp>(defOp)) { 143 // Dynamic shape dimension will be folded. 144 newShapeConstants.push_back(constantIndexOp.value()); 145 } else { 146 // Dynamic shape dimension not folded; copy dynamicSize from old memref. 147 newShapeConstants.push_back(-1); 148 dynamicSizes.push_back(dynamicSize); 149 } 150 dynamicDimPos++; 151 } 152 153 // Create new memref type (which will have fewer dynamic dimensions). 154 MemRefType newMemRefType = 155 MemRefType::Builder(memrefType).setShape(newShapeConstants); 156 assert(static_cast<int64_t>(dynamicSizes.size()) == 157 newMemRefType.getNumDynamicDims()); 158 159 // Create and insert the alloc op for the new memref. 160 auto newAlloc = rewriter.create<AllocLikeOp>( 161 alloc.getLoc(), newMemRefType, dynamicSizes, alloc.symbolOperands(), 162 alloc.alignmentAttr()); 163 // Insert a cast so we have the same type as the old alloc. 164 auto resultCast = 165 rewriter.create<CastOp>(alloc.getLoc(), alloc.getType(), newAlloc); 166 167 rewriter.replaceOp(alloc, {resultCast}); 168 return success(); 169 } 170 }; 171 172 /// Fold alloc operations with no users or only store and dealloc uses. 173 template <typename T> 174 struct SimplifyDeadAlloc : public OpRewritePattern<T> { 175 using OpRewritePattern<T>::OpRewritePattern; 176 177 LogicalResult matchAndRewrite(T alloc, 178 PatternRewriter &rewriter) const override { 179 if (llvm::any_of(alloc->getUsers(), [&](Operation *op) { 180 if (auto storeOp = dyn_cast<StoreOp>(op)) 181 return storeOp.value() == alloc; 182 return !isa<DeallocOp>(op); 183 })) 184 return failure(); 185 186 for (Operation *user : llvm::make_early_inc_range(alloc->getUsers())) 187 rewriter.eraseOp(user); 188 189 rewriter.eraseOp(alloc); 190 return success(); 191 } 192 }; 193 } // namespace 194 195 void AllocOp::getCanonicalizationPatterns(RewritePatternSet &results, 196 MLIRContext *context) { 197 results.add<SimplifyAllocConst<AllocOp>, SimplifyDeadAlloc<AllocOp>>(context); 198 } 199 200 void AllocaOp::getCanonicalizationPatterns(RewritePatternSet &results, 201 MLIRContext *context) { 202 results.add<SimplifyAllocConst<AllocaOp>, SimplifyDeadAlloc<AllocaOp>>( 203 context); 204 } 205 206 //===----------------------------------------------------------------------===// 207 // AllocaScopeOp 208 //===----------------------------------------------------------------------===// 209 210 void AllocaScopeOp::print(OpAsmPrinter &p) { 211 bool printBlockTerminators = false; 212 213 p << ' '; 214 if (!results().empty()) { 215 p << " -> (" << getResultTypes() << ")"; 216 printBlockTerminators = true; 217 } 218 p << ' '; 219 p.printRegion(bodyRegion(), 220 /*printEntryBlockArgs=*/false, 221 /*printBlockTerminators=*/printBlockTerminators); 222 p.printOptionalAttrDict((*this)->getAttrs()); 223 } 224 225 ParseResult AllocaScopeOp::parse(OpAsmParser &parser, OperationState &result) { 226 // Create a region for the body. 227 result.regions.reserve(1); 228 Region *bodyRegion = result.addRegion(); 229 230 // Parse optional results type list. 231 if (parser.parseOptionalArrowTypeList(result.types)) 232 return failure(); 233 234 // Parse the body region. 235 if (parser.parseRegion(*bodyRegion, /*arguments=*/{}, /*argTypes=*/{})) 236 return failure(); 237 AllocaScopeOp::ensureTerminator(*bodyRegion, parser.getBuilder(), 238 result.location); 239 240 // Parse the optional attribute list. 241 if (parser.parseOptionalAttrDict(result.attributes)) 242 return failure(); 243 244 return success(); 245 } 246 247 void AllocaScopeOp::getSuccessorRegions( 248 Optional<unsigned> index, ArrayRef<Attribute> operands, 249 SmallVectorImpl<RegionSuccessor> ®ions) { 250 if (index.hasValue()) { 251 regions.push_back(RegionSuccessor(getResults())); 252 return; 253 } 254 255 regions.push_back(RegionSuccessor(&bodyRegion())); 256 } 257 258 /// Given an operation, return whether this op is guaranteed to 259 /// allocate an AutomaticAllocationScopeResource 260 static bool isGuaranteedAutomaticAllocation(Operation *op) { 261 MemoryEffectOpInterface interface = dyn_cast<MemoryEffectOpInterface>(op); 262 if (!interface) 263 return false; 264 for (auto res : op->getResults()) { 265 if (auto effect = 266 interface.getEffectOnValue<MemoryEffects::Allocate>(res)) { 267 if (isa<SideEffects::AutomaticAllocationScopeResource>( 268 effect->getResource())) 269 return true; 270 } 271 } 272 return false; 273 } 274 275 /// Given an operation, return whether this op itself could 276 /// allocate an AutomaticAllocationScopeResource. Note that 277 /// this will not check whether an operation contained within 278 /// the op can allocate. 279 static bool isOpItselfPotentialAutomaticAllocation(Operation *op) { 280 // This op itself doesn't create a stack allocation, 281 // the inner allocation should be handled separately. 282 if (op->hasTrait<OpTrait::HasRecursiveSideEffects>()) 283 return false; 284 MemoryEffectOpInterface interface = dyn_cast<MemoryEffectOpInterface>(op); 285 if (!interface) 286 return true; 287 for (auto res : op->getResults()) { 288 if (auto effect = 289 interface.getEffectOnValue<MemoryEffects::Allocate>(res)) { 290 if (isa<SideEffects::AutomaticAllocationScopeResource>( 291 effect->getResource())) 292 return true; 293 } 294 } 295 return false; 296 } 297 298 /// Return whether this op is the last non terminating op 299 /// in a region. That is to say, it is in a one-block region 300 /// and is only followed by a terminator. This prevents 301 /// extending the lifetime of allocations. 302 static bool lastNonTerminatorInRegion(Operation *op) { 303 return op->getNextNode() == op->getBlock()->getTerminator() && 304 op->getParentRegion()->getBlocks().size() == 1; 305 } 306 307 /// Inline an AllocaScopeOp if either the direct parent is an allocation scope 308 /// or it contains no allocation. 309 struct AllocaScopeInliner : public OpRewritePattern<AllocaScopeOp> { 310 using OpRewritePattern<AllocaScopeOp>::OpRewritePattern; 311 312 LogicalResult matchAndRewrite(AllocaScopeOp op, 313 PatternRewriter &rewriter) const override { 314 bool hasPotentialAlloca = 315 op->walk<WalkOrder::PreOrder>([&](Operation *alloc) { 316 if (alloc == op) 317 return WalkResult::advance(); 318 if (isOpItselfPotentialAutomaticAllocation(alloc)) 319 return WalkResult::interrupt(); 320 if (alloc->hasTrait<OpTrait::AutomaticAllocationScope>()) 321 return WalkResult::skip(); 322 return WalkResult::advance(); 323 }).wasInterrupted(); 324 325 // If this contains no potential allocation, it is always legal to 326 // inline. Otherwise, consider two conditions: 327 if (hasPotentialAlloca) { 328 // If the parent isn't an allocation scope, or we are not the last 329 // non-terminator op in the parent, we will extend the lifetime. 330 if (!op->getParentOp()->hasTrait<OpTrait::AutomaticAllocationScope>()) 331 return failure(); 332 if (!lastNonTerminatorInRegion(op)) 333 return failure(); 334 } 335 336 Block *block = &op.getRegion().front(); 337 Operation *terminator = block->getTerminator(); 338 ValueRange results = terminator->getOperands(); 339 rewriter.mergeBlockBefore(block, op); 340 rewriter.replaceOp(op, results); 341 rewriter.eraseOp(terminator); 342 return success(); 343 } 344 }; 345 346 /// Move allocations into an allocation scope, if it is legal to 347 /// move them (e.g. their operands are available at the location 348 /// the op would be moved to). 349 struct AllocaScopeHoister : public OpRewritePattern<AllocaScopeOp> { 350 using OpRewritePattern<AllocaScopeOp>::OpRewritePattern; 351 352 LogicalResult matchAndRewrite(AllocaScopeOp op, 353 PatternRewriter &rewriter) const override { 354 355 if (!op->getParentWithTrait<OpTrait::AutomaticAllocationScope>()) 356 return failure(); 357 358 Operation *lastParentWithoutScope = op->getParentOp(); 359 360 if (!lastParentWithoutScope || 361 lastParentWithoutScope->hasTrait<OpTrait::AutomaticAllocationScope>()) 362 return failure(); 363 364 // Only apply to if this is this last non-terminator 365 // op in the block (lest lifetime be extended) of a one 366 // block region 367 if (!lastNonTerminatorInRegion(op) || 368 !lastNonTerminatorInRegion(lastParentWithoutScope)) 369 return failure(); 370 371 while (!lastParentWithoutScope->getParentOp() 372 ->hasTrait<OpTrait::AutomaticAllocationScope>()) { 373 lastParentWithoutScope = lastParentWithoutScope->getParentOp(); 374 if (!lastParentWithoutScope || 375 !lastNonTerminatorInRegion(lastParentWithoutScope)) 376 return failure(); 377 } 378 assert(lastParentWithoutScope->getParentOp() 379 ->hasTrait<OpTrait::AutomaticAllocationScope>()); 380 381 Region *containingRegion = nullptr; 382 for (auto &r : lastParentWithoutScope->getRegions()) { 383 if (r.isAncestor(op->getParentRegion())) { 384 assert(containingRegion == nullptr && 385 "only one region can contain the op"); 386 containingRegion = &r; 387 } 388 } 389 assert(containingRegion && "op must be contained in a region"); 390 391 SmallVector<Operation *> toHoist; 392 op->walk([&](Operation *alloc) { 393 if (!isGuaranteedAutomaticAllocation(alloc)) 394 return WalkResult::skip(); 395 396 // If any operand is not defined before the location of 397 // lastParentWithoutScope (i.e. where we would hoist to), skip. 398 if (llvm::any_of(alloc->getOperands(), [&](Value v) { 399 return containingRegion->isAncestor(v.getParentRegion()); 400 })) 401 return WalkResult::skip(); 402 toHoist.push_back(alloc); 403 return WalkResult::advance(); 404 }); 405 406 if (toHoist.empty()) 407 return failure(); 408 rewriter.setInsertionPoint(lastParentWithoutScope); 409 for (auto *op : toHoist) { 410 auto *cloned = rewriter.clone(*op); 411 rewriter.replaceOp(op, cloned->getResults()); 412 } 413 return success(); 414 } 415 }; 416 417 void AllocaScopeOp::getCanonicalizationPatterns(RewritePatternSet &results, 418 MLIRContext *context) { 419 results.add<AllocaScopeInliner, AllocaScopeHoister>(context); 420 } 421 422 //===----------------------------------------------------------------------===// 423 // AssumeAlignmentOp 424 //===----------------------------------------------------------------------===// 425 426 LogicalResult AssumeAlignmentOp::verify() { 427 if (!llvm::isPowerOf2_32(alignment())) 428 return emitOpError("alignment must be power of 2"); 429 return success(); 430 } 431 432 //===----------------------------------------------------------------------===// 433 // CastOp 434 //===----------------------------------------------------------------------===// 435 436 /// Determines whether MemRef_CastOp casts to a more dynamic version of the 437 /// source memref. This is useful to to fold a memref.cast into a consuming op 438 /// and implement canonicalization patterns for ops in different dialects that 439 /// may consume the results of memref.cast operations. Such foldable memref.cast 440 /// operations are typically inserted as `view` and `subview` ops are 441 /// canonicalized, to preserve the type compatibility of their uses. 442 /// 443 /// Returns true when all conditions are met: 444 /// 1. source and result are ranked memrefs with strided semantics and same 445 /// element type and rank. 446 /// 2. each of the source's size, offset or stride has more static information 447 /// than the corresponding result's size, offset or stride. 448 /// 449 /// Example 1: 450 /// ```mlir 451 /// %1 = memref.cast %0 : memref<8x16xf32> to memref<?x?xf32> 452 /// %2 = consumer %1 ... : memref<?x?xf32> ... 453 /// ``` 454 /// 455 /// may fold into: 456 /// 457 /// ```mlir 458 /// %2 = consumer %0 ... : memref<8x16xf32> ... 459 /// ``` 460 /// 461 /// Example 2: 462 /// ``` 463 /// %1 = memref.cast %0 : memref<?x16xf32, affine_map<(i, j)->(16 * i + j)>> 464 /// to memref<?x?xf32> 465 /// consumer %1 : memref<?x?xf32> ... 466 /// ``` 467 /// 468 /// may fold into: 469 /// 470 /// ``` 471 /// consumer %0 ... : memref<?x16xf32, affine_map<(i, j)->(16 * i + j)>> 472 /// ``` 473 bool CastOp::canFoldIntoConsumerOp(CastOp castOp) { 474 MemRefType sourceType = castOp.source().getType().dyn_cast<MemRefType>(); 475 MemRefType resultType = castOp.getType().dyn_cast<MemRefType>(); 476 477 // Requires ranked MemRefType. 478 if (!sourceType || !resultType) 479 return false; 480 481 // Requires same elemental type. 482 if (sourceType.getElementType() != resultType.getElementType()) 483 return false; 484 485 // Requires same rank. 486 if (sourceType.getRank() != resultType.getRank()) 487 return false; 488 489 // Only fold casts between strided memref forms. 490 int64_t sourceOffset, resultOffset; 491 SmallVector<int64_t, 4> sourceStrides, resultStrides; 492 if (failed(getStridesAndOffset(sourceType, sourceStrides, sourceOffset)) || 493 failed(getStridesAndOffset(resultType, resultStrides, resultOffset))) 494 return false; 495 496 // If cast is towards more static sizes along any dimension, don't fold. 497 for (auto it : llvm::zip(sourceType.getShape(), resultType.getShape())) { 498 auto ss = std::get<0>(it), st = std::get<1>(it); 499 if (ss != st) 500 if (ShapedType::isDynamic(ss) && !ShapedType::isDynamic(st)) 501 return false; 502 } 503 504 // If cast is towards more static offset along any dimension, don't fold. 505 if (sourceOffset != resultOffset) 506 if (ShapedType::isDynamicStrideOrOffset(sourceOffset) && 507 !ShapedType::isDynamicStrideOrOffset(resultOffset)) 508 return false; 509 510 // If cast is towards more static strides along any dimension, don't fold. 511 for (auto it : llvm::zip(sourceStrides, resultStrides)) { 512 auto ss = std::get<0>(it), st = std::get<1>(it); 513 if (ss != st) 514 if (ShapedType::isDynamicStrideOrOffset(ss) && 515 !ShapedType::isDynamicStrideOrOffset(st)) 516 return false; 517 } 518 519 return true; 520 } 521 522 bool CastOp::areCastCompatible(TypeRange inputs, TypeRange outputs) { 523 if (inputs.size() != 1 || outputs.size() != 1) 524 return false; 525 Type a = inputs.front(), b = outputs.front(); 526 auto aT = a.dyn_cast<MemRefType>(); 527 auto bT = b.dyn_cast<MemRefType>(); 528 529 auto uaT = a.dyn_cast<UnrankedMemRefType>(); 530 auto ubT = b.dyn_cast<UnrankedMemRefType>(); 531 532 if (aT && bT) { 533 if (aT.getElementType() != bT.getElementType()) 534 return false; 535 if (aT.getLayout() != bT.getLayout()) { 536 int64_t aOffset, bOffset; 537 SmallVector<int64_t, 4> aStrides, bStrides; 538 if (failed(getStridesAndOffset(aT, aStrides, aOffset)) || 539 failed(getStridesAndOffset(bT, bStrides, bOffset)) || 540 aStrides.size() != bStrides.size()) 541 return false; 542 543 // Strides along a dimension/offset are compatible if the value in the 544 // source memref is static and the value in the target memref is the 545 // same. They are also compatible if either one is dynamic (see 546 // description of MemRefCastOp for details). 547 auto checkCompatible = [](int64_t a, int64_t b) { 548 return (a == MemRefType::getDynamicStrideOrOffset() || 549 b == MemRefType::getDynamicStrideOrOffset() || a == b); 550 }; 551 if (!checkCompatible(aOffset, bOffset)) 552 return false; 553 for (const auto &aStride : enumerate(aStrides)) 554 if (!checkCompatible(aStride.value(), bStrides[aStride.index()])) 555 return false; 556 } 557 if (aT.getMemorySpace() != bT.getMemorySpace()) 558 return false; 559 560 // They must have the same rank, and any specified dimensions must match. 561 if (aT.getRank() != bT.getRank()) 562 return false; 563 564 for (unsigned i = 0, e = aT.getRank(); i != e; ++i) { 565 int64_t aDim = aT.getDimSize(i), bDim = bT.getDimSize(i); 566 if (aDim != -1 && bDim != -1 && aDim != bDim) 567 return false; 568 } 569 return true; 570 } else { 571 if (!aT && !uaT) 572 return false; 573 if (!bT && !ubT) 574 return false; 575 // Unranked to unranked casting is unsupported 576 if (uaT && ubT) 577 return false; 578 579 auto aEltType = (aT) ? aT.getElementType() : uaT.getElementType(); 580 auto bEltType = (bT) ? bT.getElementType() : ubT.getElementType(); 581 if (aEltType != bEltType) 582 return false; 583 584 auto aMemSpace = (aT) ? aT.getMemorySpace() : uaT.getMemorySpace(); 585 auto bMemSpace = (bT) ? bT.getMemorySpace() : ubT.getMemorySpace(); 586 return aMemSpace == bMemSpace; 587 } 588 589 return false; 590 } 591 592 OpFoldResult CastOp::fold(ArrayRef<Attribute> operands) { 593 return succeeded(foldMemRefCast(*this)) ? getResult() : Value(); 594 } 595 596 //===----------------------------------------------------------------------===// 597 // CopyOp 598 //===----------------------------------------------------------------------===// 599 600 namespace { 601 /// If the source/target of a CopyOp is a CastOp that does not modify the shape 602 /// and element type, the cast can be skipped. Such CastOps only cast the layout 603 /// of the type. 604 struct FoldCopyOfCast : public OpRewritePattern<CopyOp> { 605 using OpRewritePattern<CopyOp>::OpRewritePattern; 606 607 LogicalResult matchAndRewrite(CopyOp copyOp, 608 PatternRewriter &rewriter) const override { 609 bool modified = false; 610 611 // Check source. 612 if (auto castOp = copyOp.source().getDefiningOp<CastOp>()) { 613 auto fromType = castOp.source().getType().dyn_cast<MemRefType>(); 614 auto toType = castOp.source().getType().dyn_cast<MemRefType>(); 615 616 if (fromType && toType) { 617 if (fromType.getShape() == toType.getShape() && 618 fromType.getElementType() == toType.getElementType()) { 619 rewriter.updateRootInPlace( 620 copyOp, [&] { copyOp.sourceMutable().assign(castOp.source()); }); 621 modified = true; 622 } 623 } 624 } 625 626 // Check target. 627 if (auto castOp = copyOp.target().getDefiningOp<CastOp>()) { 628 auto fromType = castOp.source().getType().dyn_cast<MemRefType>(); 629 auto toType = castOp.source().getType().dyn_cast<MemRefType>(); 630 631 if (fromType && toType) { 632 if (fromType.getShape() == toType.getShape() && 633 fromType.getElementType() == toType.getElementType()) { 634 rewriter.updateRootInPlace( 635 copyOp, [&] { copyOp.targetMutable().assign(castOp.source()); }); 636 modified = true; 637 } 638 } 639 } 640 641 return success(modified); 642 } 643 }; 644 645 /// Fold memref.copy(%x, %x). 646 struct FoldSelfCopy : public OpRewritePattern<CopyOp> { 647 using OpRewritePattern<CopyOp>::OpRewritePattern; 648 649 LogicalResult matchAndRewrite(CopyOp copyOp, 650 PatternRewriter &rewriter) const override { 651 if (copyOp.source() != copyOp.target()) 652 return failure(); 653 654 rewriter.eraseOp(copyOp); 655 return success(); 656 } 657 }; 658 } // namespace 659 660 void CopyOp::getCanonicalizationPatterns(RewritePatternSet &results, 661 MLIRContext *context) { 662 results.add<FoldCopyOfCast, FoldSelfCopy>(context); 663 } 664 665 LogicalResult CopyOp::fold(ArrayRef<Attribute> cstOperands, 666 SmallVectorImpl<OpFoldResult> &results) { 667 /// copy(memrefcast) -> copy 668 bool folded = false; 669 Operation *op = *this; 670 for (OpOperand &operand : op->getOpOperands()) { 671 auto castOp = operand.get().getDefiningOp<memref::CastOp>(); 672 if (castOp && memref::CastOp::canFoldIntoConsumerOp(castOp)) { 673 operand.set(castOp.getOperand()); 674 folded = true; 675 } 676 } 677 return success(folded); 678 } 679 680 //===----------------------------------------------------------------------===// 681 // DeallocOp 682 //===----------------------------------------------------------------------===// 683 684 LogicalResult DeallocOp::fold(ArrayRef<Attribute> cstOperands, 685 SmallVectorImpl<OpFoldResult> &results) { 686 /// dealloc(memrefcast) -> dealloc 687 return foldMemRefCast(*this); 688 } 689 690 //===----------------------------------------------------------------------===// 691 // DimOp 692 //===----------------------------------------------------------------------===// 693 694 void DimOp::build(OpBuilder &builder, OperationState &result, Value source, 695 int64_t index) { 696 auto loc = result.location; 697 Value indexValue = builder.create<arith::ConstantIndexOp>(loc, index); 698 build(builder, result, source, indexValue); 699 } 700 701 void DimOp::build(OpBuilder &builder, OperationState &result, Value source, 702 Value index) { 703 auto indexTy = builder.getIndexType(); 704 build(builder, result, indexTy, source, index); 705 } 706 707 Optional<int64_t> DimOp::getConstantIndex() { 708 if (auto constantOp = index().getDefiningOp<arith::ConstantOp>()) 709 return constantOp.getValue().cast<IntegerAttr>().getInt(); 710 return {}; 711 } 712 713 LogicalResult DimOp::verify() { 714 // Assume unknown index to be in range. 715 Optional<int64_t> index = getConstantIndex(); 716 if (!index.hasValue()) 717 return success(); 718 719 // Check that constant index is not knowingly out of range. 720 auto type = source().getType(); 721 if (auto memrefType = type.dyn_cast<MemRefType>()) { 722 if (index.getValue() >= memrefType.getRank()) 723 return emitOpError("index is out of range"); 724 } else if (type.isa<UnrankedMemRefType>()) { 725 // Assume index to be in range. 726 } else { 727 llvm_unreachable("expected operand with memref type"); 728 } 729 return success(); 730 } 731 732 /// Return a map with key being elements in `vals` and data being number of 733 /// occurences of it. Use std::map, since the `vals` here are strides and the 734 /// dynamic stride value is the same as the tombstone value for 735 /// `DenseMap<int64_t>`. 736 static std::map<int64_t, unsigned> getNumOccurences(ArrayRef<int64_t> vals) { 737 std::map<int64_t, unsigned> numOccurences; 738 for (auto val : vals) 739 numOccurences[val]++; 740 return numOccurences; 741 } 742 743 /// Given the `originalType` and a `candidateReducedType` whose shape is assumed 744 /// to be a subset of `originalType` with some `1` entries erased, return the 745 /// set of indices that specifies which of the entries of `originalShape` are 746 /// dropped to obtain `reducedShape`. 747 /// This accounts for cases where there are multiple unit-dims, but only a 748 /// subset of those are dropped. For MemRefTypes these can be disambiguated 749 /// using the strides. If a dimension is dropped the stride must be dropped too. 750 static llvm::Optional<llvm::SmallBitVector> 751 computeMemRefRankReductionMask(MemRefType originalType, MemRefType reducedType, 752 ArrayRef<OpFoldResult> sizes) { 753 llvm::SmallBitVector unusedDims(originalType.getRank()); 754 if (originalType.getRank() == reducedType.getRank()) 755 return unusedDims; 756 757 for (const auto &dim : llvm::enumerate(sizes)) 758 if (auto attr = dim.value().dyn_cast<Attribute>()) 759 if (attr.cast<IntegerAttr>().getInt() == 1) 760 unusedDims.set(dim.index()); 761 762 // Early exit for the case where the number of unused dims matches the number 763 // of ranks reduced. 764 if (unusedDims.count() + reducedType.getRank() == originalType.getRank()) 765 return unusedDims; 766 767 SmallVector<int64_t> originalStrides, candidateStrides; 768 int64_t originalOffset, candidateOffset; 769 if (failed( 770 getStridesAndOffset(originalType, originalStrides, originalOffset)) || 771 failed( 772 getStridesAndOffset(reducedType, candidateStrides, candidateOffset))) 773 return llvm::None; 774 775 // For memrefs, a dimension is truly dropped if its corresponding stride is 776 // also dropped. This is particularly important when more than one of the dims 777 // is 1. Track the number of occurences of the strides in the original type 778 // and the candidate type. For each unused dim that stride should not be 779 // present in the candidate type. Note that there could be multiple dimensions 780 // that have the same size. We dont need to exactly figure out which dim 781 // corresponds to which stride, we just need to verify that the number of 782 // reptitions of a stride in the original + number of unused dims with that 783 // stride == number of repititions of a stride in the candidate. 784 std::map<int64_t, unsigned> currUnaccountedStrides = 785 getNumOccurences(originalStrides); 786 std::map<int64_t, unsigned> candidateStridesNumOccurences = 787 getNumOccurences(candidateStrides); 788 for (size_t dim = 0, e = unusedDims.size(); dim != e; ++dim) { 789 if (!unusedDims.test(dim)) 790 continue; 791 int64_t originalStride = originalStrides[dim]; 792 if (currUnaccountedStrides[originalStride] > 793 candidateStridesNumOccurences[originalStride]) { 794 // This dim can be treated as dropped. 795 currUnaccountedStrides[originalStride]--; 796 continue; 797 } 798 if (currUnaccountedStrides[originalStride] == 799 candidateStridesNumOccurences[originalStride]) { 800 // The stride for this is not dropped. Keep as is. 801 unusedDims.reset(dim); 802 continue; 803 } 804 if (currUnaccountedStrides[originalStride] < 805 candidateStridesNumOccurences[originalStride]) { 806 // This should never happen. Cant have a stride in the reduced rank type 807 // that wasnt in the original one. 808 return llvm::None; 809 } 810 } 811 812 if ((int64_t)unusedDims.count() + reducedType.getRank() != 813 originalType.getRank()) 814 return llvm::None; 815 return unusedDims; 816 } 817 818 llvm::SmallBitVector SubViewOp::getDroppedDims() { 819 MemRefType sourceType = getSourceType(); 820 MemRefType resultType = getType(); 821 llvm::Optional<llvm::SmallBitVector> unusedDims = 822 computeMemRefRankReductionMask(sourceType, resultType, getMixedSizes()); 823 assert(unusedDims && "unable to find unused dims of subview"); 824 return *unusedDims; 825 } 826 827 OpFoldResult DimOp::fold(ArrayRef<Attribute> operands) { 828 // All forms of folding require a known index. 829 auto index = operands[1].dyn_cast_or_null<IntegerAttr>(); 830 if (!index) 831 return {}; 832 833 // Folding for unranked types (UnrankedMemRefType) is not supported. 834 auto memrefType = source().getType().dyn_cast<MemRefType>(); 835 if (!memrefType) 836 return {}; 837 838 // Fold if the shape extent along the given index is known. 839 if (!memrefType.isDynamicDim(index.getInt())) { 840 Builder builder(getContext()); 841 return builder.getIndexAttr(memrefType.getShape()[index.getInt()]); 842 } 843 844 // The size at the given index is now known to be a dynamic size. 845 unsigned unsignedIndex = index.getValue().getZExtValue(); 846 847 // Fold dim to the size argument for an `AllocOp`, `ViewOp`, or `SubViewOp`. 848 Operation *definingOp = source().getDefiningOp(); 849 850 if (auto alloc = dyn_cast_or_null<AllocOp>(definingOp)) 851 return *(alloc.getDynamicSizes().begin() + 852 memrefType.getDynamicDimIndex(unsignedIndex)); 853 854 if (auto alloca = dyn_cast_or_null<AllocaOp>(definingOp)) 855 return *(alloca.getDynamicSizes().begin() + 856 memrefType.getDynamicDimIndex(unsignedIndex)); 857 858 if (auto view = dyn_cast_or_null<ViewOp>(definingOp)) 859 return *(view.getDynamicSizes().begin() + 860 memrefType.getDynamicDimIndex(unsignedIndex)); 861 862 if (auto subview = dyn_cast_or_null<SubViewOp>(definingOp)) { 863 llvm::SmallBitVector unusedDims = subview.getDroppedDims(); 864 unsigned resultIndex = 0; 865 unsigned sourceRank = subview.getSourceType().getRank(); 866 unsigned sourceIndex = 0; 867 for (auto i : llvm::seq<unsigned>(0, sourceRank)) { 868 if (unusedDims.test(i)) 869 continue; 870 if (resultIndex == unsignedIndex) { 871 sourceIndex = i; 872 break; 873 } 874 resultIndex++; 875 } 876 assert(subview.isDynamicSize(sourceIndex) && 877 "expected dynamic subview size"); 878 return subview.getDynamicSize(sourceIndex); 879 } 880 881 if (auto sizeInterface = 882 dyn_cast_or_null<OffsetSizeAndStrideOpInterface>(definingOp)) { 883 assert(sizeInterface.isDynamicSize(unsignedIndex) && 884 "Expected dynamic subview size"); 885 return sizeInterface.getDynamicSize(unsignedIndex); 886 } 887 888 // dim(memrefcast) -> dim 889 if (succeeded(foldMemRefCast(*this))) 890 return getResult(); 891 892 return {}; 893 } 894 895 namespace { 896 /// Fold dim of a memref reshape operation to a load into the reshape's shape 897 /// operand. 898 struct DimOfMemRefReshape : public OpRewritePattern<DimOp> { 899 using OpRewritePattern<DimOp>::OpRewritePattern; 900 901 LogicalResult matchAndRewrite(DimOp dim, 902 PatternRewriter &rewriter) const override { 903 auto reshape = dim.source().getDefiningOp<ReshapeOp>(); 904 905 if (!reshape) 906 return failure(); 907 908 // Place the load directly after the reshape to ensure that the shape memref 909 // was not mutated. 910 rewriter.setInsertionPointAfter(reshape); 911 Location loc = dim.getLoc(); 912 Value load = rewriter.create<LoadOp>(loc, reshape.shape(), dim.index()); 913 if (load.getType() != dim.getType()) 914 load = rewriter.create<arith::IndexCastOp>(loc, dim.getType(), load); 915 rewriter.replaceOp(dim, load); 916 return success(); 917 } 918 }; 919 920 } // namespace 921 922 void DimOp::getCanonicalizationPatterns(RewritePatternSet &results, 923 MLIRContext *context) { 924 results.add<DimOfMemRefReshape>(context); 925 } 926 927 // --------------------------------------------------------------------------- 928 // DmaStartOp 929 // --------------------------------------------------------------------------- 930 931 void DmaStartOp::build(OpBuilder &builder, OperationState &result, 932 Value srcMemRef, ValueRange srcIndices, Value destMemRef, 933 ValueRange destIndices, Value numElements, 934 Value tagMemRef, ValueRange tagIndices, Value stride, 935 Value elementsPerStride) { 936 result.addOperands(srcMemRef); 937 result.addOperands(srcIndices); 938 result.addOperands(destMemRef); 939 result.addOperands(destIndices); 940 result.addOperands({numElements, tagMemRef}); 941 result.addOperands(tagIndices); 942 if (stride) 943 result.addOperands({stride, elementsPerStride}); 944 } 945 946 void DmaStartOp::print(OpAsmPrinter &p) { 947 p << " " << getSrcMemRef() << '[' << getSrcIndices() << "], " 948 << getDstMemRef() << '[' << getDstIndices() << "], " << getNumElements() 949 << ", " << getTagMemRef() << '[' << getTagIndices() << ']'; 950 if (isStrided()) 951 p << ", " << getStride() << ", " << getNumElementsPerStride(); 952 953 p.printOptionalAttrDict((*this)->getAttrs()); 954 p << " : " << getSrcMemRef().getType() << ", " << getDstMemRef().getType() 955 << ", " << getTagMemRef().getType(); 956 } 957 958 // Parse DmaStartOp. 959 // Ex: 960 // %dma_id = dma_start %src[%i, %j], %dst[%k, %l], %size, 961 // %tag[%index], %stride, %num_elt_per_stride : 962 // : memref<3076 x f32, 0>, 963 // memref<1024 x f32, 2>, 964 // memref<1 x i32> 965 // 966 ParseResult DmaStartOp::parse(OpAsmParser &parser, OperationState &result) { 967 OpAsmParser::UnresolvedOperand srcMemRefInfo; 968 SmallVector<OpAsmParser::UnresolvedOperand, 4> srcIndexInfos; 969 OpAsmParser::UnresolvedOperand dstMemRefInfo; 970 SmallVector<OpAsmParser::UnresolvedOperand, 4> dstIndexInfos; 971 OpAsmParser::UnresolvedOperand numElementsInfo; 972 OpAsmParser::UnresolvedOperand tagMemrefInfo; 973 SmallVector<OpAsmParser::UnresolvedOperand, 4> tagIndexInfos; 974 SmallVector<OpAsmParser::UnresolvedOperand, 2> strideInfo; 975 976 SmallVector<Type, 3> types; 977 auto indexType = parser.getBuilder().getIndexType(); 978 979 // Parse and resolve the following list of operands: 980 // *) source memref followed by its indices (in square brackets). 981 // *) destination memref followed by its indices (in square brackets). 982 // *) dma size in KiB. 983 if (parser.parseOperand(srcMemRefInfo) || 984 parser.parseOperandList(srcIndexInfos, OpAsmParser::Delimiter::Square) || 985 parser.parseComma() || parser.parseOperand(dstMemRefInfo) || 986 parser.parseOperandList(dstIndexInfos, OpAsmParser::Delimiter::Square) || 987 parser.parseComma() || parser.parseOperand(numElementsInfo) || 988 parser.parseComma() || parser.parseOperand(tagMemrefInfo) || 989 parser.parseOperandList(tagIndexInfos, OpAsmParser::Delimiter::Square)) 990 return failure(); 991 992 // Parse optional stride and elements per stride. 993 if (parser.parseTrailingOperandList(strideInfo)) 994 return failure(); 995 996 bool isStrided = strideInfo.size() == 2; 997 if (!strideInfo.empty() && !isStrided) { 998 return parser.emitError(parser.getNameLoc(), 999 "expected two stride related operands"); 1000 } 1001 1002 if (parser.parseColonTypeList(types)) 1003 return failure(); 1004 if (types.size() != 3) 1005 return parser.emitError(parser.getNameLoc(), "fewer/more types expected"); 1006 1007 if (parser.resolveOperand(srcMemRefInfo, types[0], result.operands) || 1008 parser.resolveOperands(srcIndexInfos, indexType, result.operands) || 1009 parser.resolveOperand(dstMemRefInfo, types[1], result.operands) || 1010 parser.resolveOperands(dstIndexInfos, indexType, result.operands) || 1011 // size should be an index. 1012 parser.resolveOperand(numElementsInfo, indexType, result.operands) || 1013 parser.resolveOperand(tagMemrefInfo, types[2], result.operands) || 1014 // tag indices should be index. 1015 parser.resolveOperands(tagIndexInfos, indexType, result.operands)) 1016 return failure(); 1017 1018 if (isStrided) { 1019 if (parser.resolveOperands(strideInfo, indexType, result.operands)) 1020 return failure(); 1021 } 1022 1023 return success(); 1024 } 1025 1026 LogicalResult DmaStartOp::verify() { 1027 unsigned numOperands = getNumOperands(); 1028 1029 // Mandatory non-variadic operands are: src memref, dst memref, tag memref and 1030 // the number of elements. 1031 if (numOperands < 4) 1032 return emitOpError("expected at least 4 operands"); 1033 1034 // Check types of operands. The order of these calls is important: the later 1035 // calls rely on some type properties to compute the operand position. 1036 // 1. Source memref. 1037 if (!getSrcMemRef().getType().isa<MemRefType>()) 1038 return emitOpError("expected source to be of memref type"); 1039 if (numOperands < getSrcMemRefRank() + 4) 1040 return emitOpError() << "expected at least " << getSrcMemRefRank() + 4 1041 << " operands"; 1042 if (!getSrcIndices().empty() && 1043 !llvm::all_of(getSrcIndices().getTypes(), 1044 [](Type t) { return t.isIndex(); })) 1045 return emitOpError("expected source indices to be of index type"); 1046 1047 // 2. Destination memref. 1048 if (!getDstMemRef().getType().isa<MemRefType>()) 1049 return emitOpError("expected destination to be of memref type"); 1050 unsigned numExpectedOperands = getSrcMemRefRank() + getDstMemRefRank() + 4; 1051 if (numOperands < numExpectedOperands) 1052 return emitOpError() << "expected at least " << numExpectedOperands 1053 << " operands"; 1054 if (!getDstIndices().empty() && 1055 !llvm::all_of(getDstIndices().getTypes(), 1056 [](Type t) { return t.isIndex(); })) 1057 return emitOpError("expected destination indices to be of index type"); 1058 1059 // 3. Number of elements. 1060 if (!getNumElements().getType().isIndex()) 1061 return emitOpError("expected num elements to be of index type"); 1062 1063 // 4. Tag memref. 1064 if (!getTagMemRef().getType().isa<MemRefType>()) 1065 return emitOpError("expected tag to be of memref type"); 1066 numExpectedOperands += getTagMemRefRank(); 1067 if (numOperands < numExpectedOperands) 1068 return emitOpError() << "expected at least " << numExpectedOperands 1069 << " operands"; 1070 if (!getTagIndices().empty() && 1071 !llvm::all_of(getTagIndices().getTypes(), 1072 [](Type t) { return t.isIndex(); })) 1073 return emitOpError("expected tag indices to be of index type"); 1074 1075 // Optional stride-related operands must be either both present or both 1076 // absent. 1077 if (numOperands != numExpectedOperands && 1078 numOperands != numExpectedOperands + 2) 1079 return emitOpError("incorrect number of operands"); 1080 1081 // 5. Strides. 1082 if (isStrided()) { 1083 if (!getStride().getType().isIndex() || 1084 !getNumElementsPerStride().getType().isIndex()) 1085 return emitOpError( 1086 "expected stride and num elements per stride to be of type index"); 1087 } 1088 1089 return success(); 1090 } 1091 1092 LogicalResult DmaStartOp::fold(ArrayRef<Attribute> cstOperands, 1093 SmallVectorImpl<OpFoldResult> &results) { 1094 /// dma_start(memrefcast) -> dma_start 1095 return foldMemRefCast(*this); 1096 } 1097 1098 // --------------------------------------------------------------------------- 1099 // DmaWaitOp 1100 // --------------------------------------------------------------------------- 1101 1102 LogicalResult DmaWaitOp::fold(ArrayRef<Attribute> cstOperands, 1103 SmallVectorImpl<OpFoldResult> &results) { 1104 /// dma_wait(memrefcast) -> dma_wait 1105 return foldMemRefCast(*this); 1106 } 1107 1108 LogicalResult DmaWaitOp::verify() { 1109 // Check that the number of tag indices matches the tagMemRef rank. 1110 unsigned numTagIndices = tagIndices().size(); 1111 unsigned tagMemRefRank = getTagMemRefRank(); 1112 if (numTagIndices != tagMemRefRank) 1113 return emitOpError() << "expected tagIndices to have the same number of " 1114 "elements as the tagMemRef rank, expected " 1115 << tagMemRefRank << ", but got " << numTagIndices; 1116 return success(); 1117 } 1118 1119 //===----------------------------------------------------------------------===// 1120 // GenericAtomicRMWOp 1121 //===----------------------------------------------------------------------===// 1122 1123 void GenericAtomicRMWOp::build(OpBuilder &builder, OperationState &result, 1124 Value memref, ValueRange ivs) { 1125 result.addOperands(memref); 1126 result.addOperands(ivs); 1127 1128 if (auto memrefType = memref.getType().dyn_cast<MemRefType>()) { 1129 Type elementType = memrefType.getElementType(); 1130 result.addTypes(elementType); 1131 1132 Region *bodyRegion = result.addRegion(); 1133 bodyRegion->push_back(new Block()); 1134 bodyRegion->addArgument(elementType, memref.getLoc()); 1135 } 1136 } 1137 1138 LogicalResult GenericAtomicRMWOp::verify() { 1139 auto &body = getRegion(); 1140 if (body.getNumArguments() != 1) 1141 return emitOpError("expected single number of entry block arguments"); 1142 1143 if (getResult().getType() != body.getArgument(0).getType()) 1144 return emitOpError("expected block argument of the same type result type"); 1145 1146 bool hasSideEffects = 1147 body.walk([&](Operation *nestedOp) { 1148 if (MemoryEffectOpInterface::hasNoEffect(nestedOp)) 1149 return WalkResult::advance(); 1150 nestedOp->emitError( 1151 "body of 'memref.generic_atomic_rmw' should contain " 1152 "only operations with no side effects"); 1153 return WalkResult::interrupt(); 1154 }) 1155 .wasInterrupted(); 1156 return hasSideEffects ? failure() : success(); 1157 } 1158 1159 ParseResult GenericAtomicRMWOp::parse(OpAsmParser &parser, 1160 OperationState &result) { 1161 OpAsmParser::UnresolvedOperand memref; 1162 Type memrefType; 1163 SmallVector<OpAsmParser::UnresolvedOperand, 4> ivs; 1164 1165 Type indexType = parser.getBuilder().getIndexType(); 1166 if (parser.parseOperand(memref) || 1167 parser.parseOperandList(ivs, OpAsmParser::Delimiter::Square) || 1168 parser.parseColonType(memrefType) || 1169 parser.resolveOperand(memref, memrefType, result.operands) || 1170 parser.resolveOperands(ivs, indexType, result.operands)) 1171 return failure(); 1172 1173 Region *body = result.addRegion(); 1174 if (parser.parseRegion(*body, llvm::None, llvm::None) || 1175 parser.parseOptionalAttrDict(result.attributes)) 1176 return failure(); 1177 result.types.push_back(memrefType.cast<MemRefType>().getElementType()); 1178 return success(); 1179 } 1180 1181 void GenericAtomicRMWOp::print(OpAsmPrinter &p) { 1182 p << ' ' << memref() << "[" << indices() << "] : " << memref().getType() 1183 << ' '; 1184 p.printRegion(getRegion()); 1185 p.printOptionalAttrDict((*this)->getAttrs()); 1186 } 1187 1188 //===----------------------------------------------------------------------===// 1189 // AtomicYieldOp 1190 //===----------------------------------------------------------------------===// 1191 1192 LogicalResult AtomicYieldOp::verify() { 1193 Type parentType = (*this)->getParentOp()->getResultTypes().front(); 1194 Type resultType = result().getType(); 1195 if (parentType != resultType) 1196 return emitOpError() << "types mismatch between yield op: " << resultType 1197 << " and its parent: " << parentType; 1198 return success(); 1199 } 1200 1201 //===----------------------------------------------------------------------===// 1202 // GlobalOp 1203 //===----------------------------------------------------------------------===// 1204 1205 static void printGlobalMemrefOpTypeAndInitialValue(OpAsmPrinter &p, GlobalOp op, 1206 TypeAttr type, 1207 Attribute initialValue) { 1208 p << type; 1209 if (!op.isExternal()) { 1210 p << " = "; 1211 if (op.isUninitialized()) 1212 p << "uninitialized"; 1213 else 1214 p.printAttributeWithoutType(initialValue); 1215 } 1216 } 1217 1218 static ParseResult 1219 parseGlobalMemrefOpTypeAndInitialValue(OpAsmParser &parser, TypeAttr &typeAttr, 1220 Attribute &initialValue) { 1221 Type type; 1222 if (parser.parseType(type)) 1223 return failure(); 1224 1225 auto memrefType = type.dyn_cast<MemRefType>(); 1226 if (!memrefType || !memrefType.hasStaticShape()) 1227 return parser.emitError(parser.getNameLoc()) 1228 << "type should be static shaped memref, but got " << type; 1229 typeAttr = TypeAttr::get(type); 1230 1231 if (parser.parseOptionalEqual()) 1232 return success(); 1233 1234 if (succeeded(parser.parseOptionalKeyword("uninitialized"))) { 1235 initialValue = UnitAttr::get(parser.getContext()); 1236 return success(); 1237 } 1238 1239 Type tensorType = getTensorTypeFromMemRefType(memrefType); 1240 if (parser.parseAttribute(initialValue, tensorType)) 1241 return failure(); 1242 if (!initialValue.isa<ElementsAttr>()) 1243 return parser.emitError(parser.getNameLoc()) 1244 << "initial value should be a unit or elements attribute"; 1245 return success(); 1246 } 1247 1248 LogicalResult GlobalOp::verify() { 1249 auto memrefType = type().dyn_cast<MemRefType>(); 1250 if (!memrefType || !memrefType.hasStaticShape()) 1251 return emitOpError("type should be static shaped memref, but got ") 1252 << type(); 1253 1254 // Verify that the initial value, if present, is either a unit attribute or 1255 // an elements attribute. 1256 if (initial_value().hasValue()) { 1257 Attribute initValue = initial_value().getValue(); 1258 if (!initValue.isa<UnitAttr>() && !initValue.isa<ElementsAttr>()) 1259 return emitOpError("initial value should be a unit or elements " 1260 "attribute, but got ") 1261 << initValue; 1262 1263 // Check that the type of the initial value is compatible with the type of 1264 // the global variable. 1265 if (initValue.isa<ElementsAttr>()) { 1266 Type initType = initValue.getType(); 1267 Type tensorType = getTensorTypeFromMemRefType(memrefType); 1268 if (initType != tensorType) 1269 return emitOpError("initial value expected to be of type ") 1270 << tensorType << ", but was of type " << initType; 1271 } 1272 } 1273 1274 if (Optional<uint64_t> alignAttr = alignment()) { 1275 uint64_t alignment = alignAttr.getValue(); 1276 1277 if (!llvm::isPowerOf2_64(alignment)) 1278 return emitError() << "alignment attribute value " << alignment 1279 << " is not a power of 2"; 1280 } 1281 1282 // TODO: verify visibility for declarations. 1283 return success(); 1284 } 1285 1286 ElementsAttr GlobalOp::getConstantInitValue() { 1287 auto initVal = initial_value(); 1288 if (constant() && initVal.hasValue()) 1289 return initVal.getValue().cast<ElementsAttr>(); 1290 return {}; 1291 } 1292 1293 //===----------------------------------------------------------------------===// 1294 // GetGlobalOp 1295 //===----------------------------------------------------------------------===// 1296 1297 LogicalResult 1298 GetGlobalOp::verifySymbolUses(SymbolTableCollection &symbolTable) { 1299 // Verify that the result type is same as the type of the referenced 1300 // memref.global op. 1301 auto global = 1302 symbolTable.lookupNearestSymbolFrom<GlobalOp>(*this, nameAttr()); 1303 if (!global) 1304 return emitOpError("'") 1305 << name() << "' does not reference a valid global memref"; 1306 1307 Type resultType = result().getType(); 1308 if (global.type() != resultType) 1309 return emitOpError("result type ") 1310 << resultType << " does not match type " << global.type() 1311 << " of the global memref @" << name(); 1312 return success(); 1313 } 1314 1315 //===----------------------------------------------------------------------===// 1316 // LoadOp 1317 //===----------------------------------------------------------------------===// 1318 1319 LogicalResult LoadOp::verify() { 1320 if (getNumOperands() != 1 + getMemRefType().getRank()) 1321 return emitOpError("incorrect number of indices for load"); 1322 return success(); 1323 } 1324 1325 OpFoldResult LoadOp::fold(ArrayRef<Attribute> cstOperands) { 1326 /// load(memrefcast) -> load 1327 if (succeeded(foldMemRefCast(*this))) 1328 return getResult(); 1329 return OpFoldResult(); 1330 } 1331 1332 //===----------------------------------------------------------------------===// 1333 // PrefetchOp 1334 //===----------------------------------------------------------------------===// 1335 1336 void PrefetchOp::print(OpAsmPrinter &p) { 1337 p << " " << memref() << '['; 1338 p.printOperands(indices()); 1339 p << ']' << ", " << (isWrite() ? "write" : "read"); 1340 p << ", locality<" << localityHint(); 1341 p << ">, " << (isDataCache() ? "data" : "instr"); 1342 p.printOptionalAttrDict( 1343 (*this)->getAttrs(), 1344 /*elidedAttrs=*/{"localityHint", "isWrite", "isDataCache"}); 1345 p << " : " << getMemRefType(); 1346 } 1347 1348 ParseResult PrefetchOp::parse(OpAsmParser &parser, OperationState &result) { 1349 OpAsmParser::UnresolvedOperand memrefInfo; 1350 SmallVector<OpAsmParser::UnresolvedOperand, 4> indexInfo; 1351 IntegerAttr localityHint; 1352 MemRefType type; 1353 StringRef readOrWrite, cacheType; 1354 1355 auto indexTy = parser.getBuilder().getIndexType(); 1356 auto i32Type = parser.getBuilder().getIntegerType(32); 1357 if (parser.parseOperand(memrefInfo) || 1358 parser.parseOperandList(indexInfo, OpAsmParser::Delimiter::Square) || 1359 parser.parseComma() || parser.parseKeyword(&readOrWrite) || 1360 parser.parseComma() || parser.parseKeyword("locality") || 1361 parser.parseLess() || 1362 parser.parseAttribute(localityHint, i32Type, "localityHint", 1363 result.attributes) || 1364 parser.parseGreater() || parser.parseComma() || 1365 parser.parseKeyword(&cacheType) || parser.parseColonType(type) || 1366 parser.resolveOperand(memrefInfo, type, result.operands) || 1367 parser.resolveOperands(indexInfo, indexTy, result.operands)) 1368 return failure(); 1369 1370 if (!readOrWrite.equals("read") && !readOrWrite.equals("write")) 1371 return parser.emitError(parser.getNameLoc(), 1372 "rw specifier has to be 'read' or 'write'"); 1373 result.addAttribute( 1374 PrefetchOp::getIsWriteAttrName(), 1375 parser.getBuilder().getBoolAttr(readOrWrite.equals("write"))); 1376 1377 if (!cacheType.equals("data") && !cacheType.equals("instr")) 1378 return parser.emitError(parser.getNameLoc(), 1379 "cache type has to be 'data' or 'instr'"); 1380 1381 result.addAttribute( 1382 PrefetchOp::getIsDataCacheAttrName(), 1383 parser.getBuilder().getBoolAttr(cacheType.equals("data"))); 1384 1385 return success(); 1386 } 1387 1388 LogicalResult PrefetchOp::verify() { 1389 if (getNumOperands() != 1 + getMemRefType().getRank()) 1390 return emitOpError("too few indices"); 1391 1392 return success(); 1393 } 1394 1395 LogicalResult PrefetchOp::fold(ArrayRef<Attribute> cstOperands, 1396 SmallVectorImpl<OpFoldResult> &results) { 1397 // prefetch(memrefcast) -> prefetch 1398 return foldMemRefCast(*this); 1399 } 1400 1401 //===----------------------------------------------------------------------===// 1402 // RankOp 1403 //===----------------------------------------------------------------------===// 1404 1405 OpFoldResult RankOp::fold(ArrayRef<Attribute> operands) { 1406 // Constant fold rank when the rank of the operand is known. 1407 auto type = getOperand().getType(); 1408 auto shapedType = type.dyn_cast<ShapedType>(); 1409 if (shapedType && shapedType.hasRank()) 1410 return IntegerAttr::get(IndexType::get(getContext()), shapedType.getRank()); 1411 return IntegerAttr(); 1412 } 1413 1414 //===----------------------------------------------------------------------===// 1415 // ReinterpretCastOp 1416 //===----------------------------------------------------------------------===// 1417 1418 /// Build a ReinterpretCastOp with all dynamic entries: `staticOffsets`, 1419 /// `staticSizes` and `staticStrides` are automatically filled with 1420 /// source-memref-rank sentinel values that encode dynamic entries. 1421 void ReinterpretCastOp::build(OpBuilder &b, OperationState &result, 1422 MemRefType resultType, Value source, 1423 OpFoldResult offset, ArrayRef<OpFoldResult> sizes, 1424 ArrayRef<OpFoldResult> strides, 1425 ArrayRef<NamedAttribute> attrs) { 1426 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 1427 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 1428 dispatchIndexOpFoldResults(offset, dynamicOffsets, staticOffsets, 1429 ShapedType::kDynamicStrideOrOffset); 1430 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 1431 ShapedType::kDynamicSize); 1432 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 1433 ShapedType::kDynamicStrideOrOffset); 1434 build(b, result, resultType, source, dynamicOffsets, dynamicSizes, 1435 dynamicStrides, b.getI64ArrayAttr(staticOffsets), 1436 b.getI64ArrayAttr(staticSizes), b.getI64ArrayAttr(staticStrides)); 1437 result.addAttributes(attrs); 1438 } 1439 1440 void ReinterpretCastOp::build(OpBuilder &b, OperationState &result, 1441 MemRefType resultType, Value source, 1442 int64_t offset, ArrayRef<int64_t> sizes, 1443 ArrayRef<int64_t> strides, 1444 ArrayRef<NamedAttribute> attrs) { 1445 SmallVector<OpFoldResult> sizeValues = 1446 llvm::to_vector<4>(llvm::map_range(sizes, [&](int64_t v) -> OpFoldResult { 1447 return b.getI64IntegerAttr(v); 1448 })); 1449 SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>( 1450 llvm::map_range(strides, [&](int64_t v) -> OpFoldResult { 1451 return b.getI64IntegerAttr(v); 1452 })); 1453 build(b, result, resultType, source, b.getI64IntegerAttr(offset), sizeValues, 1454 strideValues, attrs); 1455 } 1456 1457 void ReinterpretCastOp::build(OpBuilder &b, OperationState &result, 1458 MemRefType resultType, Value source, Value offset, 1459 ValueRange sizes, ValueRange strides, 1460 ArrayRef<NamedAttribute> attrs) { 1461 SmallVector<OpFoldResult> sizeValues = llvm::to_vector<4>( 1462 llvm::map_range(sizes, [](Value v) -> OpFoldResult { return v; })); 1463 SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>( 1464 llvm::map_range(strides, [](Value v) -> OpFoldResult { return v; })); 1465 build(b, result, resultType, source, offset, sizeValues, strideValues, attrs); 1466 } 1467 1468 // TODO: ponder whether we want to allow missing trailing sizes/strides that are 1469 // completed automatically, like we have for subview and extract_slice. 1470 LogicalResult ReinterpretCastOp::verify() { 1471 // The source and result memrefs should be in the same memory space. 1472 auto srcType = source().getType().cast<BaseMemRefType>(); 1473 auto resultType = getType().cast<MemRefType>(); 1474 if (srcType.getMemorySpace() != resultType.getMemorySpace()) 1475 return emitError("different memory spaces specified for source type ") 1476 << srcType << " and result memref type " << resultType; 1477 if (srcType.getElementType() != resultType.getElementType()) 1478 return emitError("different element types specified for source type ") 1479 << srcType << " and result memref type " << resultType; 1480 1481 // Match sizes in result memref type and in static_sizes attribute. 1482 for (auto &en : llvm::enumerate(llvm::zip( 1483 resultType.getShape(), extractFromI64ArrayAttr(static_sizes())))) { 1484 int64_t resultSize = std::get<0>(en.value()); 1485 int64_t expectedSize = std::get<1>(en.value()); 1486 if (!ShapedType::isDynamic(resultSize) && 1487 !ShapedType::isDynamic(expectedSize) && resultSize != expectedSize) 1488 return emitError("expected result type with size = ") 1489 << expectedSize << " instead of " << resultSize 1490 << " in dim = " << en.index(); 1491 } 1492 1493 // Match offset and strides in static_offset and static_strides attributes. If 1494 // result memref type has no affine map specified, this will assume an 1495 // identity layout. 1496 int64_t resultOffset; 1497 SmallVector<int64_t, 4> resultStrides; 1498 if (failed(getStridesAndOffset(resultType, resultStrides, resultOffset))) 1499 return emitError("expected result type to have strided layout but found ") 1500 << resultType; 1501 1502 // Match offset in result memref type and in static_offsets attribute. 1503 int64_t expectedOffset = extractFromI64ArrayAttr(static_offsets()).front(); 1504 if (!ShapedType::isDynamicStrideOrOffset(resultOffset) && 1505 !ShapedType::isDynamicStrideOrOffset(expectedOffset) && 1506 resultOffset != expectedOffset) 1507 return emitError("expected result type with offset = ") 1508 << resultOffset << " instead of " << expectedOffset; 1509 1510 // Match strides in result memref type and in static_strides attribute. 1511 for (auto &en : llvm::enumerate(llvm::zip( 1512 resultStrides, extractFromI64ArrayAttr(static_strides())))) { 1513 int64_t resultStride = std::get<0>(en.value()); 1514 int64_t expectedStride = std::get<1>(en.value()); 1515 if (!ShapedType::isDynamicStrideOrOffset(resultStride) && 1516 !ShapedType::isDynamicStrideOrOffset(expectedStride) && 1517 resultStride != expectedStride) 1518 return emitError("expected result type with stride = ") 1519 << expectedStride << " instead of " << resultStride 1520 << " in dim = " << en.index(); 1521 } 1522 1523 return success(); 1524 } 1525 1526 OpFoldResult ReinterpretCastOp::fold(ArrayRef<Attribute> /*operands*/) { 1527 Value src = source(); 1528 auto getPrevSrc = [&]() -> Value { 1529 // reinterpret_cast(reinterpret_cast(x)) -> reinterpret_cast(x). 1530 if (auto prev = src.getDefiningOp<ReinterpretCastOp>()) 1531 return prev.source(); 1532 1533 // reinterpret_cast(cast(x)) -> reinterpret_cast(x). 1534 if (auto prev = src.getDefiningOp<CastOp>()) 1535 return prev.source(); 1536 1537 // reinterpret_cast(subview(x)) -> reinterpret_cast(x) if subview offsets 1538 // are 0. 1539 if (auto prev = src.getDefiningOp<SubViewOp>()) 1540 if (llvm::all_of(prev.getMixedOffsets(), [](OpFoldResult val) { 1541 return isConstantIntValue(val, 0); 1542 })) 1543 return prev.source(); 1544 1545 return nullptr; 1546 }; 1547 1548 if (auto prevSrc = getPrevSrc()) { 1549 sourceMutable().assign(prevSrc); 1550 return getResult(); 1551 } 1552 1553 return nullptr; 1554 } 1555 1556 //===----------------------------------------------------------------------===// 1557 // Reassociative reshape ops 1558 //===----------------------------------------------------------------------===// 1559 1560 SmallVector<AffineMap, 4> CollapseShapeOp::getReassociationMaps() { 1561 return getSymbolLessAffineMaps(getReassociationExprs()); 1562 } 1563 SmallVector<ReassociationExprs, 4> CollapseShapeOp::getReassociationExprs() { 1564 return convertReassociationIndicesToExprs(getContext(), 1565 getReassociationIndices()); 1566 } 1567 1568 SmallVector<AffineMap, 4> ExpandShapeOp::getReassociationMaps() { 1569 return getSymbolLessAffineMaps(getReassociationExprs()); 1570 } 1571 SmallVector<ReassociationExprs, 4> ExpandShapeOp::getReassociationExprs() { 1572 return convertReassociationIndicesToExprs(getContext(), 1573 getReassociationIndices()); 1574 } 1575 1576 /// Detect whether memref dims [dim, dim + extent) can be reshaped without 1577 /// copies. 1578 static bool isReshapableDimBand(unsigned dim, unsigned extent, 1579 ArrayRef<int64_t> sizes, 1580 ArrayRef<AffineExpr> strides) { 1581 // Bands of extent one can be reshaped, as they are not reshaped at all. 1582 if (extent == 1) 1583 return true; 1584 // Otherwise, the size of the first dimension needs to be known. 1585 if (ShapedType::isDynamic(sizes[dim])) 1586 return false; 1587 assert(sizes.size() == strides.size() && "mismatched ranks"); 1588 // off by 1 indexing to avoid out of bounds 1589 // V 1590 for (auto idx = dim, e = dim + extent; idx + 1 < e; ++idx) { 1591 // Only bands of static shapes are reshapable. This is due to the fact that 1592 // there is no relation between dynamic sizes and dynamic strides: we do not 1593 // have enough information to know whether a "-1" size corresponds to the 1594 // proper symbol in the AffineExpr of a stride. 1595 if (ShapedType::isDynamic(sizes[idx + 1])) 1596 return false; 1597 // TODO: Refine this by passing the proper nDims and nSymbols so we can 1598 // simplify on the fly and catch more reshapable cases. 1599 if (strides[idx] != strides[idx + 1] * sizes[idx + 1]) 1600 return false; 1601 } 1602 return true; 1603 } 1604 1605 /// Compute the MemRefType obtained by applying the `reassociation` (which is 1606 /// expected to be valid) to `type`. 1607 /// If `type` is Contiguous MemRefType, this always produce a contiguous 1608 /// MemRefType. 1609 static MemRefType 1610 computeReshapeCollapsedType(MemRefType type, 1611 ArrayRef<AffineMap> reassociation) { 1612 auto sizes = type.getShape(); 1613 AffineExpr offset; 1614 SmallVector<AffineExpr, 4> strides; 1615 auto status = getStridesAndOffset(type, strides, offset); 1616 auto isIdentityLayout = type.getLayout().isIdentity(); 1617 (void)status; 1618 assert(succeeded(status) && "expected strided memref"); 1619 1620 SmallVector<int64_t, 4> newSizes; 1621 newSizes.reserve(reassociation.size()); 1622 SmallVector<AffineExpr, 4> newStrides; 1623 newStrides.reserve(reassociation.size()); 1624 1625 // Use the fact that reassociation is valid to simplify the logic: only use 1626 // each map's rank. 1627 assert(isReassociationValid(reassociation) && "invalid reassociation"); 1628 unsigned currentDim = 0; 1629 for (AffineMap m : reassociation) { 1630 unsigned dim = m.getNumResults(); 1631 int64_t size = 1; 1632 AffineExpr stride = strides[currentDim + dim - 1]; 1633 if (isIdentityLayout || 1634 isReshapableDimBand(currentDim, dim, sizes, strides)) { 1635 for (unsigned d = 0; d < dim; ++d) { 1636 int64_t currentSize = sizes[currentDim + d]; 1637 if (ShapedType::isDynamic(currentSize)) { 1638 size = ShapedType::kDynamicSize; 1639 break; 1640 } 1641 size *= currentSize; 1642 } 1643 } else { 1644 size = ShapedType::kDynamicSize; 1645 stride = AffineExpr(); 1646 } 1647 newSizes.push_back(size); 1648 newStrides.push_back(stride); 1649 currentDim += dim; 1650 } 1651 1652 // Early-exit: if `type` is contiguous, the result must be contiguous. 1653 if (canonicalizeStridedLayout(type).getLayout().isIdentity()) 1654 return MemRefType::Builder(type).setShape(newSizes).setLayout({}); 1655 1656 // Convert back to int64_t because we don't have enough information to create 1657 // new strided layouts from AffineExpr only. This corresponds to a case where 1658 // copies may be necessary. 1659 int64_t intOffset = ShapedType::kDynamicStrideOrOffset; 1660 if (auto o = offset.dyn_cast<AffineConstantExpr>()) 1661 intOffset = o.getValue(); 1662 SmallVector<int64_t, 4> intStrides; 1663 intStrides.reserve(strides.size()); 1664 for (auto stride : newStrides) { 1665 if (auto cst = stride.dyn_cast_or_null<AffineConstantExpr>()) 1666 intStrides.push_back(cst.getValue()); 1667 else 1668 intStrides.push_back(ShapedType::kDynamicStrideOrOffset); 1669 } 1670 auto layout = 1671 makeStridedLinearLayoutMap(intStrides, intOffset, type.getContext()); 1672 return canonicalizeStridedLayout( 1673 MemRefType::Builder(type).setShape(newSizes).setLayout( 1674 AffineMapAttr::get(layout))); 1675 } 1676 1677 void CollapseShapeOp::build(OpBuilder &b, OperationState &result, Value src, 1678 ArrayRef<ReassociationIndices> reassociation, 1679 ArrayRef<NamedAttribute> attrs) { 1680 auto memRefType = src.getType().cast<MemRefType>(); 1681 auto resultType = computeReshapeCollapsedType( 1682 memRefType, getSymbolLessAffineMaps(convertReassociationIndicesToExprs( 1683 b.getContext(), reassociation))); 1684 build(b, result, resultType, src, attrs); 1685 result.addAttribute(getReassociationAttrName(), 1686 getReassociationIndicesAttribute(b, reassociation)); 1687 } 1688 1689 template <typename ReshapeOp, 1690 bool isExpansion = std::is_same<ReshapeOp, ExpandShapeOp>::value> 1691 static LogicalResult verifyReshapeOp(ReshapeOp op, MemRefType expandedType, 1692 MemRefType collapsedType) { 1693 if (failed( 1694 verifyReshapeLikeTypes(op, expandedType, collapsedType, isExpansion))) 1695 return failure(); 1696 auto maps = op.getReassociationMaps(); 1697 MemRefType expectedType = computeReshapeCollapsedType(expandedType, maps); 1698 if (collapsedType != expectedType) 1699 return op.emitOpError("expected collapsed type to be ") 1700 << expectedType << ", but got " << collapsedType; 1701 return success(); 1702 } 1703 1704 LogicalResult ExpandShapeOp::verify() { 1705 return verifyReshapeOp(*this, getResultType(), getSrcType()); 1706 } 1707 1708 void ExpandShapeOp::getCanonicalizationPatterns(RewritePatternSet &results, 1709 MLIRContext *context) { 1710 results.add<CollapseReshapeOps<ExpandShapeOp>, 1711 CollapseMixedReshapeOps<ExpandShapeOp, CollapseShapeOp>>(context); 1712 } 1713 1714 LogicalResult CollapseShapeOp::verify() { 1715 return verifyReshapeOp(*this, getSrcType(), getResultType()); 1716 } 1717 1718 struct CollapseShapeOpMemRefCastFolder 1719 : public OpRewritePattern<CollapseShapeOp> { 1720 public: 1721 using OpRewritePattern<CollapseShapeOp>::OpRewritePattern; 1722 1723 LogicalResult matchAndRewrite(CollapseShapeOp op, 1724 PatternRewriter &rewriter) const override { 1725 auto cast = op.getOperand().getDefiningOp<CastOp>(); 1726 if (!cast) 1727 return failure(); 1728 1729 if (!CastOp::canFoldIntoConsumerOp(cast)) 1730 return failure(); 1731 1732 Type newResultType = computeReshapeCollapsedType( 1733 cast.getOperand().getType().cast<MemRefType>(), 1734 op.getReassociationMaps()); 1735 1736 if (newResultType == op.getResultType()) { 1737 rewriter.updateRootInPlace( 1738 op, [&]() { op.srcMutable().assign(cast.source()); }); 1739 } else { 1740 Value newOp = rewriter.create<CollapseShapeOp>( 1741 op->getLoc(), cast.source(), op.getReassociationIndices()); 1742 rewriter.replaceOpWithNewOp<CastOp>(op, op.getType(), newOp); 1743 } 1744 return success(); 1745 } 1746 }; 1747 1748 void CollapseShapeOp::getCanonicalizationPatterns(RewritePatternSet &results, 1749 MLIRContext *context) { 1750 results.add<CollapseReshapeOps<CollapseShapeOp>, 1751 CollapseMixedReshapeOps<CollapseShapeOp, ExpandShapeOp>, 1752 CollapseShapeOpMemRefCastFolder>(context); 1753 } 1754 OpFoldResult ExpandShapeOp::fold(ArrayRef<Attribute> operands) { 1755 return foldReshapeOp<ExpandShapeOp, CollapseShapeOp>(*this, operands); 1756 } 1757 OpFoldResult CollapseShapeOp::fold(ArrayRef<Attribute> operands) { 1758 return foldReshapeOp<CollapseShapeOp, ExpandShapeOp>(*this, operands); 1759 } 1760 1761 //===----------------------------------------------------------------------===// 1762 // ReshapeOp 1763 //===----------------------------------------------------------------------===// 1764 1765 LogicalResult ReshapeOp::verify() { 1766 Type operandType = source().getType(); 1767 Type resultType = result().getType(); 1768 1769 Type operandElementType = operandType.cast<ShapedType>().getElementType(); 1770 Type resultElementType = resultType.cast<ShapedType>().getElementType(); 1771 if (operandElementType != resultElementType) 1772 return emitOpError("element types of source and destination memref " 1773 "types should be the same"); 1774 1775 if (auto operandMemRefType = operandType.dyn_cast<MemRefType>()) 1776 if (!operandMemRefType.getLayout().isIdentity()) 1777 return emitOpError("source memref type should have identity affine map"); 1778 1779 int64_t shapeSize = shape().getType().cast<MemRefType>().getDimSize(0); 1780 auto resultMemRefType = resultType.dyn_cast<MemRefType>(); 1781 if (resultMemRefType) { 1782 if (!resultMemRefType.getLayout().isIdentity()) 1783 return emitOpError("result memref type should have identity affine map"); 1784 if (shapeSize == ShapedType::kDynamicSize) 1785 return emitOpError("cannot use shape operand with dynamic length to " 1786 "reshape to statically-ranked memref type"); 1787 if (shapeSize != resultMemRefType.getRank()) 1788 return emitOpError( 1789 "length of shape operand differs from the result's memref rank"); 1790 } 1791 return success(); 1792 } 1793 1794 //===----------------------------------------------------------------------===// 1795 // StoreOp 1796 //===----------------------------------------------------------------------===// 1797 1798 LogicalResult StoreOp::verify() { 1799 if (getNumOperands() != 2 + getMemRefType().getRank()) 1800 return emitOpError("store index operand count not equal to memref rank"); 1801 1802 return success(); 1803 } 1804 1805 LogicalResult StoreOp::fold(ArrayRef<Attribute> cstOperands, 1806 SmallVectorImpl<OpFoldResult> &results) { 1807 /// store(memrefcast) -> store 1808 return foldMemRefCast(*this, getValueToStore()); 1809 } 1810 1811 //===----------------------------------------------------------------------===// 1812 // SubViewOp 1813 //===----------------------------------------------------------------------===// 1814 1815 namespace { 1816 /// Helpers to write more idiomatic operations. 1817 namespace saturated_arith { 1818 struct Wrapper { 1819 explicit Wrapper(int64_t v) : v(v) {} 1820 operator int64_t() { return v; } 1821 int64_t v; 1822 }; 1823 Wrapper operator+(Wrapper a, int64_t b) { 1824 if (ShapedType::isDynamicStrideOrOffset(a) || 1825 ShapedType::isDynamicStrideOrOffset(b)) 1826 return Wrapper(ShapedType::kDynamicStrideOrOffset); 1827 return Wrapper(a.v + b); 1828 } 1829 Wrapper operator*(Wrapper a, int64_t b) { 1830 if (ShapedType::isDynamicStrideOrOffset(a) || 1831 ShapedType::isDynamicStrideOrOffset(b)) 1832 return Wrapper(ShapedType::kDynamicStrideOrOffset); 1833 return Wrapper(a.v * b); 1834 } 1835 } // namespace saturated_arith 1836 } // namespace 1837 1838 /// A subview result type can be fully inferred from the source type and the 1839 /// static representation of offsets, sizes and strides. Special sentinels 1840 /// encode the dynamic case. 1841 Type SubViewOp::inferResultType(MemRefType sourceMemRefType, 1842 ArrayRef<int64_t> staticOffsets, 1843 ArrayRef<int64_t> staticSizes, 1844 ArrayRef<int64_t> staticStrides) { 1845 unsigned rank = sourceMemRefType.getRank(); 1846 (void)rank; 1847 assert(staticOffsets.size() == rank && "staticOffsets length mismatch"); 1848 assert(staticSizes.size() == rank && "staticSizes length mismatch"); 1849 assert(staticStrides.size() == rank && "staticStrides length mismatch"); 1850 1851 // Extract source offset and strides. 1852 int64_t sourceOffset; 1853 SmallVector<int64_t, 4> sourceStrides; 1854 auto res = getStridesAndOffset(sourceMemRefType, sourceStrides, sourceOffset); 1855 assert(succeeded(res) && "SubViewOp expected strided memref type"); 1856 (void)res; 1857 1858 // Compute target offset whose value is: 1859 // `sourceOffset + sum_i(staticOffset_i * sourceStrides_i)`. 1860 int64_t targetOffset = sourceOffset; 1861 for (auto it : llvm::zip(staticOffsets, sourceStrides)) { 1862 auto staticOffset = std::get<0>(it), targetStride = std::get<1>(it); 1863 using namespace saturated_arith; 1864 targetOffset = Wrapper(targetOffset) + Wrapper(staticOffset) * targetStride; 1865 } 1866 1867 // Compute target stride whose value is: 1868 // `sourceStrides_i * staticStrides_i`. 1869 SmallVector<int64_t, 4> targetStrides; 1870 targetStrides.reserve(staticOffsets.size()); 1871 for (auto it : llvm::zip(sourceStrides, staticStrides)) { 1872 auto sourceStride = std::get<0>(it), staticStride = std::get<1>(it); 1873 using namespace saturated_arith; 1874 targetStrides.push_back(Wrapper(sourceStride) * staticStride); 1875 } 1876 1877 // The type is now known. 1878 return MemRefType::get( 1879 staticSizes, sourceMemRefType.getElementType(), 1880 makeStridedLinearLayoutMap(targetStrides, targetOffset, 1881 sourceMemRefType.getContext()), 1882 sourceMemRefType.getMemorySpace()); 1883 } 1884 1885 Type SubViewOp::inferResultType(MemRefType sourceMemRefType, 1886 ArrayRef<OpFoldResult> offsets, 1887 ArrayRef<OpFoldResult> sizes, 1888 ArrayRef<OpFoldResult> strides) { 1889 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 1890 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 1891 dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets, 1892 ShapedType::kDynamicStrideOrOffset); 1893 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 1894 ShapedType::kDynamicSize); 1895 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 1896 ShapedType::kDynamicStrideOrOffset); 1897 return SubViewOp::inferResultType(sourceMemRefType, staticOffsets, 1898 staticSizes, staticStrides); 1899 } 1900 1901 Type SubViewOp::inferRankReducedResultType(unsigned resultRank, 1902 MemRefType sourceRankedTensorType, 1903 ArrayRef<int64_t> offsets, 1904 ArrayRef<int64_t> sizes, 1905 ArrayRef<int64_t> strides) { 1906 auto inferredType = 1907 inferResultType(sourceRankedTensorType, offsets, sizes, strides) 1908 .cast<MemRefType>(); 1909 assert(inferredType.getRank() >= resultRank && "expected "); 1910 int rankDiff = inferredType.getRank() - resultRank; 1911 if (rankDiff > 0) { 1912 auto shape = inferredType.getShape(); 1913 llvm::SmallBitVector dimsToProject = 1914 getPositionsOfShapeOne(rankDiff, shape); 1915 SmallVector<int64_t> projectedShape; 1916 for (unsigned pos = 0, e = shape.size(); pos < e; ++pos) 1917 if (!dimsToProject.test(pos)) 1918 projectedShape.push_back(shape[pos]); 1919 1920 AffineMap map = inferredType.getLayout().getAffineMap(); 1921 if (!map.isIdentity()) 1922 map = getProjectedMap(map, dimsToProject); 1923 inferredType = 1924 MemRefType::get(projectedShape, inferredType.getElementType(), map, 1925 inferredType.getMemorySpace()); 1926 } 1927 return inferredType; 1928 } 1929 1930 Type SubViewOp::inferRankReducedResultType(unsigned resultRank, 1931 MemRefType sourceRankedTensorType, 1932 ArrayRef<OpFoldResult> offsets, 1933 ArrayRef<OpFoldResult> sizes, 1934 ArrayRef<OpFoldResult> strides) { 1935 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 1936 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 1937 dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets, 1938 ShapedType::kDynamicStrideOrOffset); 1939 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 1940 ShapedType::kDynamicSize); 1941 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 1942 ShapedType::kDynamicStrideOrOffset); 1943 return SubViewOp::inferRankReducedResultType( 1944 resultRank, sourceRankedTensorType, staticOffsets, staticSizes, 1945 staticStrides); 1946 } 1947 // Build a SubViewOp with mixed static and dynamic entries and custom result 1948 // type. If the type passed is nullptr, it is inferred. 1949 void SubViewOp::build(OpBuilder &b, OperationState &result, 1950 MemRefType resultType, Value source, 1951 ArrayRef<OpFoldResult> offsets, 1952 ArrayRef<OpFoldResult> sizes, 1953 ArrayRef<OpFoldResult> strides, 1954 ArrayRef<NamedAttribute> attrs) { 1955 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 1956 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 1957 dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets, 1958 ShapedType::kDynamicStrideOrOffset); 1959 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 1960 ShapedType::kDynamicSize); 1961 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 1962 ShapedType::kDynamicStrideOrOffset); 1963 auto sourceMemRefType = source.getType().cast<MemRefType>(); 1964 // Structuring implementation this way avoids duplication between builders. 1965 if (!resultType) { 1966 resultType = SubViewOp::inferResultType(sourceMemRefType, staticOffsets, 1967 staticSizes, staticStrides) 1968 .cast<MemRefType>(); 1969 } 1970 build(b, result, resultType, source, dynamicOffsets, dynamicSizes, 1971 dynamicStrides, b.getI64ArrayAttr(staticOffsets), 1972 b.getI64ArrayAttr(staticSizes), b.getI64ArrayAttr(staticStrides)); 1973 result.addAttributes(attrs); 1974 } 1975 1976 // Build a SubViewOp with mixed static and dynamic entries and inferred result 1977 // type. 1978 void SubViewOp::build(OpBuilder &b, OperationState &result, Value source, 1979 ArrayRef<OpFoldResult> offsets, 1980 ArrayRef<OpFoldResult> sizes, 1981 ArrayRef<OpFoldResult> strides, 1982 ArrayRef<NamedAttribute> attrs) { 1983 build(b, result, MemRefType(), source, offsets, sizes, strides, attrs); 1984 } 1985 1986 // Build a SubViewOp with static entries and inferred result type. 1987 void SubViewOp::build(OpBuilder &b, OperationState &result, Value source, 1988 ArrayRef<int64_t> offsets, ArrayRef<int64_t> sizes, 1989 ArrayRef<int64_t> strides, 1990 ArrayRef<NamedAttribute> attrs) { 1991 SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>( 1992 llvm::map_range(offsets, [&](int64_t v) -> OpFoldResult { 1993 return b.getI64IntegerAttr(v); 1994 })); 1995 SmallVector<OpFoldResult> sizeValues = 1996 llvm::to_vector<4>(llvm::map_range(sizes, [&](int64_t v) -> OpFoldResult { 1997 return b.getI64IntegerAttr(v); 1998 })); 1999 SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>( 2000 llvm::map_range(strides, [&](int64_t v) -> OpFoldResult { 2001 return b.getI64IntegerAttr(v); 2002 })); 2003 build(b, result, source, offsetValues, sizeValues, strideValues, attrs); 2004 } 2005 2006 // Build a SubViewOp with dynamic entries and custom result type. If the 2007 // type passed is nullptr, it is inferred. 2008 void SubViewOp::build(OpBuilder &b, OperationState &result, 2009 MemRefType resultType, Value source, 2010 ArrayRef<int64_t> offsets, ArrayRef<int64_t> sizes, 2011 ArrayRef<int64_t> strides, 2012 ArrayRef<NamedAttribute> attrs) { 2013 SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>( 2014 llvm::map_range(offsets, [&](int64_t v) -> OpFoldResult { 2015 return b.getI64IntegerAttr(v); 2016 })); 2017 SmallVector<OpFoldResult> sizeValues = 2018 llvm::to_vector<4>(llvm::map_range(sizes, [&](int64_t v) -> OpFoldResult { 2019 return b.getI64IntegerAttr(v); 2020 })); 2021 SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>( 2022 llvm::map_range(strides, [&](int64_t v) -> OpFoldResult { 2023 return b.getI64IntegerAttr(v); 2024 })); 2025 build(b, result, resultType, source, offsetValues, sizeValues, strideValues, 2026 attrs); 2027 } 2028 2029 // Build a SubViewOp with dynamic entries and custom result type. If the type 2030 // passed is nullptr, it is inferred. 2031 void SubViewOp::build(OpBuilder &b, OperationState &result, 2032 MemRefType resultType, Value source, ValueRange offsets, 2033 ValueRange sizes, ValueRange strides, 2034 ArrayRef<NamedAttribute> attrs) { 2035 SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>( 2036 llvm::map_range(offsets, [](Value v) -> OpFoldResult { return v; })); 2037 SmallVector<OpFoldResult> sizeValues = llvm::to_vector<4>( 2038 llvm::map_range(sizes, [](Value v) -> OpFoldResult { return v; })); 2039 SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>( 2040 llvm::map_range(strides, [](Value v) -> OpFoldResult { return v; })); 2041 build(b, result, resultType, source, offsetValues, sizeValues, strideValues); 2042 } 2043 2044 // Build a SubViewOp with dynamic entries and inferred result type. 2045 void SubViewOp::build(OpBuilder &b, OperationState &result, Value source, 2046 ValueRange offsets, ValueRange sizes, ValueRange strides, 2047 ArrayRef<NamedAttribute> attrs) { 2048 build(b, result, MemRefType(), source, offsets, sizes, strides, attrs); 2049 } 2050 2051 /// For ViewLikeOpInterface. 2052 Value SubViewOp::getViewSource() { return source(); } 2053 2054 /// Return true if t1 and t2 have equal offsets (both dynamic or of same static 2055 /// value). 2056 static bool haveCompatibleOffsets(MemRefType t1, MemRefType t2) { 2057 AffineExpr t1Offset, t2Offset; 2058 SmallVector<AffineExpr> t1Strides, t2Strides; 2059 auto res1 = getStridesAndOffset(t1, t1Strides, t1Offset); 2060 auto res2 = getStridesAndOffset(t2, t2Strides, t2Offset); 2061 return succeeded(res1) && succeeded(res2) && t1Offset == t2Offset; 2062 } 2063 2064 /// Checks if `original` Type type can be rank reduced to `reduced` type. 2065 /// This function is slight variant of `is subsequence` algorithm where 2066 /// not matching dimension must be 1. 2067 static SliceVerificationResult 2068 isRankReducedMemRefType(MemRefType originalType, 2069 MemRefType candidateRankReducedType, 2070 ArrayRef<OpFoldResult> sizes) { 2071 auto partialRes = isRankReducedType(originalType, candidateRankReducedType); 2072 if (partialRes != SliceVerificationResult::Success) 2073 return partialRes; 2074 2075 auto optionalUnusedDimsMask = computeMemRefRankReductionMask( 2076 originalType, candidateRankReducedType, sizes); 2077 2078 // Sizes cannot be matched in case empty vector is returned. 2079 if (!optionalUnusedDimsMask.hasValue()) 2080 return SliceVerificationResult::LayoutMismatch; 2081 2082 if (originalType.getMemorySpace() != 2083 candidateRankReducedType.getMemorySpace()) 2084 return SliceVerificationResult::MemSpaceMismatch; 2085 2086 // No amount of stride dropping can reconcile incompatible offsets. 2087 if (!haveCompatibleOffsets(originalType, candidateRankReducedType)) 2088 return SliceVerificationResult::LayoutMismatch; 2089 2090 return SliceVerificationResult::Success; 2091 } 2092 2093 template <typename OpTy> 2094 static LogicalResult produceSubViewErrorMsg(SliceVerificationResult result, 2095 OpTy op, Type expectedType) { 2096 auto memrefType = expectedType.cast<ShapedType>(); 2097 switch (result) { 2098 case SliceVerificationResult::Success: 2099 return success(); 2100 case SliceVerificationResult::RankTooLarge: 2101 return op.emitError("expected result rank to be smaller or equal to ") 2102 << "the source rank. "; 2103 case SliceVerificationResult::SizeMismatch: 2104 return op.emitError("expected result type to be ") 2105 << expectedType 2106 << " or a rank-reduced version. (mismatch of result sizes) "; 2107 case SliceVerificationResult::ElemTypeMismatch: 2108 return op.emitError("expected result element type to be ") 2109 << memrefType.getElementType(); 2110 case SliceVerificationResult::MemSpaceMismatch: 2111 return op.emitError("expected result and source memory spaces to match."); 2112 case SliceVerificationResult::LayoutMismatch: 2113 return op.emitError("expected result type to be ") 2114 << expectedType 2115 << " or a rank-reduced version. (mismatch of result layout) "; 2116 } 2117 llvm_unreachable("unexpected subview verification result"); 2118 } 2119 2120 /// Verifier for SubViewOp. 2121 LogicalResult SubViewOp::verify() { 2122 MemRefType baseType = getSourceType(); 2123 MemRefType subViewType = getType(); 2124 2125 // The base memref and the view memref should be in the same memory space. 2126 if (baseType.getMemorySpace() != subViewType.getMemorySpace()) 2127 return emitError("different memory spaces specified for base memref " 2128 "type ") 2129 << baseType << " and subview memref type " << subViewType; 2130 2131 // Verify that the base memref type has a strided layout map. 2132 if (!isStrided(baseType)) 2133 return emitError("base type ") << baseType << " is not strided"; 2134 2135 // Verify result type against inferred type. 2136 auto expectedType = SubViewOp::inferResultType( 2137 baseType, extractFromI64ArrayAttr(static_offsets()), 2138 extractFromI64ArrayAttr(static_sizes()), 2139 extractFromI64ArrayAttr(static_strides())); 2140 2141 auto result = isRankReducedMemRefType(expectedType.cast<MemRefType>(), 2142 subViewType, getMixedSizes()); 2143 return produceSubViewErrorMsg(result, *this, expectedType); 2144 } 2145 2146 raw_ostream &mlir::operator<<(raw_ostream &os, const Range &range) { 2147 return os << "range " << range.offset << ":" << range.size << ":" 2148 << range.stride; 2149 } 2150 2151 /// Return the list of Range (i.e. offset, size, stride). Each Range 2152 /// entry contains either the dynamic value or a ConstantIndexOp constructed 2153 /// with `b` at location `loc`. 2154 SmallVector<Range, 8> mlir::getOrCreateRanges(OffsetSizeAndStrideOpInterface op, 2155 OpBuilder &b, Location loc) { 2156 std::array<unsigned, 3> ranks = op.getArrayAttrMaxRanks(); 2157 assert(ranks[0] == ranks[1] && "expected offset and sizes of equal ranks"); 2158 assert(ranks[1] == ranks[2] && "expected sizes and strides of equal ranks"); 2159 SmallVector<Range, 8> res; 2160 unsigned rank = ranks[0]; 2161 res.reserve(rank); 2162 for (unsigned idx = 0; idx < rank; ++idx) { 2163 Value offset = 2164 op.isDynamicOffset(idx) 2165 ? op.getDynamicOffset(idx) 2166 : b.create<arith::ConstantIndexOp>(loc, op.getStaticOffset(idx)); 2167 Value size = 2168 op.isDynamicSize(idx) 2169 ? op.getDynamicSize(idx) 2170 : b.create<arith::ConstantIndexOp>(loc, op.getStaticSize(idx)); 2171 Value stride = 2172 op.isDynamicStride(idx) 2173 ? op.getDynamicStride(idx) 2174 : b.create<arith::ConstantIndexOp>(loc, op.getStaticStride(idx)); 2175 res.emplace_back(Range{offset, size, stride}); 2176 } 2177 return res; 2178 } 2179 2180 /// Compute the canonical result type of a SubViewOp. Call `inferResultType` to 2181 /// deduce the result type for the given `sourceType`. Additionally, reduce the 2182 /// rank of the inferred result type if `currentResultType` is lower rank than 2183 /// `currentSourceType`. Use this signature if `sourceType` is updated together 2184 /// with the result type. In this case, it is important to compute the dropped 2185 /// dimensions using `currentSourceType` whose strides align with 2186 /// `currentResultType`. 2187 static MemRefType getCanonicalSubViewResultType( 2188 MemRefType currentResultType, MemRefType currentSourceType, 2189 MemRefType sourceType, ArrayRef<OpFoldResult> mixedOffsets, 2190 ArrayRef<OpFoldResult> mixedSizes, ArrayRef<OpFoldResult> mixedStrides) { 2191 auto nonRankReducedType = SubViewOp::inferResultType(sourceType, mixedOffsets, 2192 mixedSizes, mixedStrides) 2193 .cast<MemRefType>(); 2194 llvm::Optional<llvm::SmallBitVector> unusedDims = 2195 computeMemRefRankReductionMask(currentSourceType, currentResultType, 2196 mixedSizes); 2197 // Return nullptr as failure mode. 2198 if (!unusedDims) 2199 return nullptr; 2200 SmallVector<int64_t> shape; 2201 for (const auto &sizes : llvm::enumerate(nonRankReducedType.getShape())) { 2202 if (unusedDims->test(sizes.index())) 2203 continue; 2204 shape.push_back(sizes.value()); 2205 } 2206 AffineMap layoutMap = nonRankReducedType.getLayout().getAffineMap(); 2207 if (!layoutMap.isIdentity()) 2208 layoutMap = getProjectedMap(layoutMap, unusedDims.getValue()); 2209 return MemRefType::get(shape, nonRankReducedType.getElementType(), layoutMap, 2210 nonRankReducedType.getMemorySpace()); 2211 } 2212 2213 /// Compute the canonical result type of a SubViewOp. Call `inferResultType` to 2214 /// deduce the result type. Additionally, reduce the rank of the inferred result 2215 /// type if `currentResultType` is lower rank than `sourceType`. 2216 static MemRefType getCanonicalSubViewResultType( 2217 MemRefType currentResultType, MemRefType sourceType, 2218 ArrayRef<OpFoldResult> mixedOffsets, ArrayRef<OpFoldResult> mixedSizes, 2219 ArrayRef<OpFoldResult> mixedStrides) { 2220 return getCanonicalSubViewResultType(currentResultType, sourceType, 2221 sourceType, mixedOffsets, mixedSizes, 2222 mixedStrides); 2223 } 2224 2225 /// Helper method to check if a `subview` operation is trivially a no-op. This 2226 /// is the case if the all offsets are zero, all strides are 1, and the source 2227 /// shape is same as the size of the subview. In such cases, the subview can be 2228 /// folded into its source. 2229 static bool isTrivialSubViewOp(SubViewOp subViewOp) { 2230 if (subViewOp.getSourceType().getRank() != subViewOp.getType().getRank()) 2231 return false; 2232 2233 auto mixedOffsets = subViewOp.getMixedOffsets(); 2234 auto mixedSizes = subViewOp.getMixedSizes(); 2235 auto mixedStrides = subViewOp.getMixedStrides(); 2236 2237 // Check offsets are zero. 2238 if (llvm::any_of(mixedOffsets, [](OpFoldResult ofr) { 2239 Optional<int64_t> intValue = getConstantIntValue(ofr); 2240 return !intValue || intValue.getValue() != 0; 2241 })) 2242 return false; 2243 2244 // Check strides are one. 2245 if (llvm::any_of(mixedStrides, [](OpFoldResult ofr) { 2246 Optional<int64_t> intValue = getConstantIntValue(ofr); 2247 return !intValue || intValue.getValue() != 1; 2248 })) 2249 return false; 2250 2251 // Check all size values are static and matches the (static) source shape. 2252 ArrayRef<int64_t> sourceShape = subViewOp.getSourceType().getShape(); 2253 for (const auto &size : llvm::enumerate(mixedSizes)) { 2254 Optional<int64_t> intValue = getConstantIntValue(size.value()); 2255 if (!intValue || intValue.getValue() != sourceShape[size.index()]) 2256 return false; 2257 } 2258 // All conditions met. The `SubViewOp` is foldable as a no-op. 2259 return true; 2260 } 2261 2262 namespace { 2263 /// Pattern to rewrite a subview op with MemRefCast arguments. 2264 /// This essentially pushes memref.cast past its consuming subview when 2265 /// `canFoldIntoConsumerOp` is true. 2266 /// 2267 /// Example: 2268 /// ``` 2269 /// %0 = memref.cast %V : memref<16x16xf32> to memref<?x?xf32> 2270 /// %1 = memref.subview %0[0, 0][3, 4][1, 1] : 2271 /// memref<?x?xf32> to memref<3x4xf32, offset:?, strides:[?, 1]> 2272 /// ``` 2273 /// is rewritten into: 2274 /// ``` 2275 /// %0 = memref.subview %V: memref<16x16xf32> to memref<3x4xf32, #[[map0]]> 2276 /// %1 = memref.cast %0: memref<3x4xf32, offset:0, strides:[16, 1]> to 2277 /// memref<3x4xf32, offset:?, strides:[?, 1]> 2278 /// ``` 2279 class SubViewOpMemRefCastFolder final : public OpRewritePattern<SubViewOp> { 2280 public: 2281 using OpRewritePattern<SubViewOp>::OpRewritePattern; 2282 2283 LogicalResult matchAndRewrite(SubViewOp subViewOp, 2284 PatternRewriter &rewriter) const override { 2285 // Any constant operand, just return to let SubViewOpConstantFolder kick in. 2286 if (llvm::any_of(subViewOp.getOperands(), [](Value operand) { 2287 return matchPattern(operand, matchConstantIndex()); 2288 })) 2289 return failure(); 2290 2291 auto castOp = subViewOp.source().getDefiningOp<CastOp>(); 2292 if (!castOp) 2293 return failure(); 2294 2295 if (!CastOp::canFoldIntoConsumerOp(castOp)) 2296 return failure(); 2297 2298 // Compute the SubViewOp result type after folding the MemRefCastOp. Use the 2299 // MemRefCastOp source operand type to infer the result type and the current 2300 // SubViewOp source operand type to compute the dropped dimensions if the 2301 // operation is rank-reducing. 2302 auto resultType = getCanonicalSubViewResultType( 2303 subViewOp.getType(), subViewOp.getSourceType(), 2304 castOp.source().getType().cast<MemRefType>(), 2305 subViewOp.getMixedOffsets(), subViewOp.getMixedSizes(), 2306 subViewOp.getMixedStrides()); 2307 if (!resultType) 2308 return failure(); 2309 2310 Value newSubView = rewriter.create<SubViewOp>( 2311 subViewOp.getLoc(), resultType, castOp.source(), subViewOp.offsets(), 2312 subViewOp.sizes(), subViewOp.strides(), subViewOp.static_offsets(), 2313 subViewOp.static_sizes(), subViewOp.static_strides()); 2314 rewriter.replaceOpWithNewOp<CastOp>(subViewOp, subViewOp.getType(), 2315 newSubView); 2316 return success(); 2317 } 2318 }; 2319 2320 /// Canonicalize subview ops that are no-ops. When the source shape is not same 2321 /// as a result shape due to use of `affine_map`. 2322 class TrivialSubViewOpFolder final : public OpRewritePattern<SubViewOp> { 2323 public: 2324 using OpRewritePattern<SubViewOp>::OpRewritePattern; 2325 2326 LogicalResult matchAndRewrite(SubViewOp subViewOp, 2327 PatternRewriter &rewriter) const override { 2328 if (!isTrivialSubViewOp(subViewOp)) 2329 return failure(); 2330 if (subViewOp.getSourceType() == subViewOp.getType()) { 2331 rewriter.replaceOp(subViewOp, subViewOp.source()); 2332 return success(); 2333 } 2334 rewriter.replaceOpWithNewOp<CastOp>(subViewOp, subViewOp.getType(), 2335 subViewOp.source()); 2336 return success(); 2337 } 2338 }; 2339 } // namespace 2340 2341 /// Return the canonical type of the result of a subview. 2342 struct SubViewReturnTypeCanonicalizer { 2343 MemRefType operator()(SubViewOp op, ArrayRef<OpFoldResult> mixedOffsets, 2344 ArrayRef<OpFoldResult> mixedSizes, 2345 ArrayRef<OpFoldResult> mixedStrides) { 2346 return getCanonicalSubViewResultType(op.getType(), op.getSourceType(), 2347 mixedOffsets, mixedSizes, 2348 mixedStrides); 2349 } 2350 }; 2351 2352 /// A canonicalizer wrapper to replace SubViewOps. 2353 struct SubViewCanonicalizer { 2354 void operator()(PatternRewriter &rewriter, SubViewOp op, SubViewOp newOp) { 2355 rewriter.replaceOpWithNewOp<CastOp>(op, op.getType(), newOp); 2356 } 2357 }; 2358 2359 void SubViewOp::getCanonicalizationPatterns(RewritePatternSet &results, 2360 MLIRContext *context) { 2361 results 2362 .add<OpWithOffsetSizesAndStridesConstantArgumentFolder< 2363 SubViewOp, SubViewReturnTypeCanonicalizer, SubViewCanonicalizer>, 2364 SubViewOpMemRefCastFolder, TrivialSubViewOpFolder>(context); 2365 } 2366 2367 OpFoldResult SubViewOp::fold(ArrayRef<Attribute> operands) { 2368 auto resultShapedType = getResult().getType().cast<ShapedType>(); 2369 auto sourceShapedType = source().getType().cast<ShapedType>(); 2370 2371 if (resultShapedType.hasStaticShape() && 2372 resultShapedType == sourceShapedType) { 2373 return getViewSource(); 2374 } 2375 2376 return {}; 2377 } 2378 2379 //===----------------------------------------------------------------------===// 2380 // TransposeOp 2381 //===----------------------------------------------------------------------===// 2382 2383 /// Build a strided memref type by applying `permutationMap` tp `memRefType`. 2384 static MemRefType inferTransposeResultType(MemRefType memRefType, 2385 AffineMap permutationMap) { 2386 auto rank = memRefType.getRank(); 2387 auto originalSizes = memRefType.getShape(); 2388 // Compute permuted sizes. 2389 SmallVector<int64_t, 4> sizes(rank, 0); 2390 for (const auto &en : llvm::enumerate(permutationMap.getResults())) 2391 sizes[en.index()] = 2392 originalSizes[en.value().cast<AffineDimExpr>().getPosition()]; 2393 2394 // Compute permuted strides. 2395 int64_t offset; 2396 SmallVector<int64_t, 4> strides; 2397 auto res = getStridesAndOffset(memRefType, strides, offset); 2398 assert(succeeded(res) && strides.size() == static_cast<unsigned>(rank)); 2399 (void)res; 2400 auto map = 2401 makeStridedLinearLayoutMap(strides, offset, memRefType.getContext()); 2402 map = permutationMap ? map.compose(permutationMap) : map; 2403 return MemRefType::Builder(memRefType) 2404 .setShape(sizes) 2405 .setLayout(AffineMapAttr::get(map)); 2406 } 2407 2408 void TransposeOp::build(OpBuilder &b, OperationState &result, Value in, 2409 AffineMapAttr permutation, 2410 ArrayRef<NamedAttribute> attrs) { 2411 auto permutationMap = permutation.getValue(); 2412 assert(permutationMap); 2413 2414 auto memRefType = in.getType().cast<MemRefType>(); 2415 // Compute result type. 2416 MemRefType resultType = inferTransposeResultType(memRefType, permutationMap); 2417 2418 build(b, result, resultType, in, attrs); 2419 result.addAttribute(TransposeOp::getPermutationAttrName(), permutation); 2420 } 2421 2422 // transpose $in $permutation attr-dict : type($in) `to` type(results) 2423 void TransposeOp::print(OpAsmPrinter &p) { 2424 p << " " << in() << " " << permutation(); 2425 p.printOptionalAttrDict((*this)->getAttrs(), {getPermutationAttrName()}); 2426 p << " : " << in().getType() << " to " << getType(); 2427 } 2428 2429 ParseResult TransposeOp::parse(OpAsmParser &parser, OperationState &result) { 2430 OpAsmParser::UnresolvedOperand in; 2431 AffineMap permutation; 2432 MemRefType srcType, dstType; 2433 if (parser.parseOperand(in) || parser.parseAffineMap(permutation) || 2434 parser.parseOptionalAttrDict(result.attributes) || 2435 parser.parseColonType(srcType) || 2436 parser.resolveOperand(in, srcType, result.operands) || 2437 parser.parseKeywordType("to", dstType) || 2438 parser.addTypeToList(dstType, result.types)) 2439 return failure(); 2440 2441 result.addAttribute(TransposeOp::getPermutationAttrName(), 2442 AffineMapAttr::get(permutation)); 2443 return success(); 2444 } 2445 2446 LogicalResult TransposeOp::verify() { 2447 if (!permutation().isPermutation()) 2448 return emitOpError("expected a permutation map"); 2449 if (permutation().getNumDims() != getShapedType().getRank()) 2450 return emitOpError("expected a permutation map of same rank as the input"); 2451 2452 auto srcType = in().getType().cast<MemRefType>(); 2453 auto dstType = getType().cast<MemRefType>(); 2454 auto transposedType = inferTransposeResultType(srcType, permutation()); 2455 if (dstType != transposedType) 2456 return emitOpError("output type ") 2457 << dstType << " does not match transposed input type " << srcType 2458 << ", " << transposedType; 2459 return success(); 2460 } 2461 2462 OpFoldResult TransposeOp::fold(ArrayRef<Attribute>) { 2463 if (succeeded(foldMemRefCast(*this))) 2464 return getResult(); 2465 return {}; 2466 } 2467 2468 //===----------------------------------------------------------------------===// 2469 // ViewOp 2470 //===----------------------------------------------------------------------===// 2471 2472 LogicalResult ViewOp::verify() { 2473 auto baseType = getOperand(0).getType().cast<MemRefType>(); 2474 auto viewType = getType(); 2475 2476 // The base memref should have identity layout map (or none). 2477 if (!baseType.getLayout().isIdentity()) 2478 return emitError("unsupported map for base memref type ") << baseType; 2479 2480 // The result memref should have identity layout map (or none). 2481 if (!viewType.getLayout().isIdentity()) 2482 return emitError("unsupported map for result memref type ") << viewType; 2483 2484 // The base memref and the view memref should be in the same memory space. 2485 if (baseType.getMemorySpace() != viewType.getMemorySpace()) 2486 return emitError("different memory spaces specified for base memref " 2487 "type ") 2488 << baseType << " and view memref type " << viewType; 2489 2490 // Verify that we have the correct number of sizes for the result type. 2491 unsigned numDynamicDims = viewType.getNumDynamicDims(); 2492 if (sizes().size() != numDynamicDims) 2493 return emitError("incorrect number of size operands for type ") << viewType; 2494 2495 return success(); 2496 } 2497 2498 Value ViewOp::getViewSource() { return source(); } 2499 2500 namespace { 2501 2502 struct ViewOpShapeFolder : public OpRewritePattern<ViewOp> { 2503 using OpRewritePattern<ViewOp>::OpRewritePattern; 2504 2505 LogicalResult matchAndRewrite(ViewOp viewOp, 2506 PatternRewriter &rewriter) const override { 2507 // Return if none of the operands are constants. 2508 if (llvm::none_of(viewOp.getOperands(), [](Value operand) { 2509 return matchPattern(operand, matchConstantIndex()); 2510 })) 2511 return failure(); 2512 2513 // Get result memref type. 2514 auto memrefType = viewOp.getType(); 2515 2516 // Get offset from old memref view type 'memRefType'. 2517 int64_t oldOffset; 2518 SmallVector<int64_t, 4> oldStrides; 2519 if (failed(getStridesAndOffset(memrefType, oldStrides, oldOffset))) 2520 return failure(); 2521 assert(oldOffset == 0 && "Expected 0 offset"); 2522 2523 SmallVector<Value, 4> newOperands; 2524 2525 // Offset cannot be folded into result type. 2526 2527 // Fold any dynamic dim operands which are produced by a constant. 2528 SmallVector<int64_t, 4> newShapeConstants; 2529 newShapeConstants.reserve(memrefType.getRank()); 2530 2531 unsigned dynamicDimPos = 0; 2532 unsigned rank = memrefType.getRank(); 2533 for (unsigned dim = 0, e = rank; dim < e; ++dim) { 2534 int64_t dimSize = memrefType.getDimSize(dim); 2535 // If this is already static dimension, keep it. 2536 if (!ShapedType::isDynamic(dimSize)) { 2537 newShapeConstants.push_back(dimSize); 2538 continue; 2539 } 2540 auto *defOp = viewOp.sizes()[dynamicDimPos].getDefiningOp(); 2541 if (auto constantIndexOp = 2542 dyn_cast_or_null<arith::ConstantIndexOp>(defOp)) { 2543 // Dynamic shape dimension will be folded. 2544 newShapeConstants.push_back(constantIndexOp.value()); 2545 } else { 2546 // Dynamic shape dimension not folded; copy operand from old memref. 2547 newShapeConstants.push_back(dimSize); 2548 newOperands.push_back(viewOp.sizes()[dynamicDimPos]); 2549 } 2550 dynamicDimPos++; 2551 } 2552 2553 // Create new memref type with constant folded dims. 2554 MemRefType newMemRefType = 2555 MemRefType::Builder(memrefType).setShape(newShapeConstants); 2556 // Nothing new, don't fold. 2557 if (newMemRefType == memrefType) 2558 return failure(); 2559 2560 // Create new ViewOp. 2561 auto newViewOp = rewriter.create<ViewOp>(viewOp.getLoc(), newMemRefType, 2562 viewOp.getOperand(0), 2563 viewOp.byte_shift(), newOperands); 2564 // Insert a cast so we have the same type as the old memref type. 2565 rewriter.replaceOpWithNewOp<CastOp>(viewOp, viewOp.getType(), newViewOp); 2566 return success(); 2567 } 2568 }; 2569 2570 struct ViewOpMemrefCastFolder : public OpRewritePattern<ViewOp> { 2571 using OpRewritePattern<ViewOp>::OpRewritePattern; 2572 2573 LogicalResult matchAndRewrite(ViewOp viewOp, 2574 PatternRewriter &rewriter) const override { 2575 Value memrefOperand = viewOp.getOperand(0); 2576 CastOp memrefCastOp = memrefOperand.getDefiningOp<CastOp>(); 2577 if (!memrefCastOp) 2578 return failure(); 2579 Value allocOperand = memrefCastOp.getOperand(); 2580 AllocOp allocOp = allocOperand.getDefiningOp<AllocOp>(); 2581 if (!allocOp) 2582 return failure(); 2583 rewriter.replaceOpWithNewOp<ViewOp>(viewOp, viewOp.getType(), allocOperand, 2584 viewOp.byte_shift(), viewOp.sizes()); 2585 return success(); 2586 } 2587 }; 2588 2589 } // namespace 2590 2591 void ViewOp::getCanonicalizationPatterns(RewritePatternSet &results, 2592 MLIRContext *context) { 2593 results.add<ViewOpShapeFolder, ViewOpMemrefCastFolder>(context); 2594 } 2595 2596 //===----------------------------------------------------------------------===// 2597 // AtomicRMWOp 2598 //===----------------------------------------------------------------------===// 2599 2600 LogicalResult AtomicRMWOp::verify() { 2601 if (getMemRefType().getRank() != getNumOperands() - 2) 2602 return emitOpError( 2603 "expects the number of subscripts to be equal to memref rank"); 2604 switch (kind()) { 2605 case arith::AtomicRMWKind::addf: 2606 case arith::AtomicRMWKind::maxf: 2607 case arith::AtomicRMWKind::minf: 2608 case arith::AtomicRMWKind::mulf: 2609 if (!value().getType().isa<FloatType>()) 2610 return emitOpError() << "with kind '" 2611 << arith::stringifyAtomicRMWKind(kind()) 2612 << "' expects a floating-point type"; 2613 break; 2614 case arith::AtomicRMWKind::addi: 2615 case arith::AtomicRMWKind::maxs: 2616 case arith::AtomicRMWKind::maxu: 2617 case arith::AtomicRMWKind::mins: 2618 case arith::AtomicRMWKind::minu: 2619 case arith::AtomicRMWKind::muli: 2620 case arith::AtomicRMWKind::ori: 2621 case arith::AtomicRMWKind::andi: 2622 if (!value().getType().isa<IntegerType>()) 2623 return emitOpError() << "with kind '" 2624 << arith::stringifyAtomicRMWKind(kind()) 2625 << "' expects an integer type"; 2626 break; 2627 default: 2628 break; 2629 } 2630 return success(); 2631 } 2632 2633 OpFoldResult AtomicRMWOp::fold(ArrayRef<Attribute> operands) { 2634 /// atomicrmw(memrefcast) -> atomicrmw 2635 if (succeeded(foldMemRefCast(*this, value()))) 2636 return getResult(); 2637 return OpFoldResult(); 2638 } 2639 2640 //===----------------------------------------------------------------------===// 2641 // TableGen'd op method definitions 2642 //===----------------------------------------------------------------------===// 2643 2644 #define GET_OP_CLASSES 2645 #include "mlir/Dialect/MemRef/IR/MemRefOps.cpp.inc" 2646