1 //===- Shape.cpp - MLIR Shape Operations ----------------------------------===// 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/Shape/IR/Shape.h" 10 11 #include "mlir/Dialect/StandardOps/IR/Ops.h" 12 #include "mlir/Dialect/Traits.h" 13 #include "mlir/IR/Builders.h" 14 #include "mlir/IR/DialectImplementation.h" 15 #include "mlir/IR/PatternMatch.h" 16 #include "mlir/IR/StandardTypes.h" 17 #include "mlir/Transforms/InliningUtils.h" 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/ADT/TypeSwitch.h" 20 #include "llvm/Support/raw_ostream.h" 21 22 using namespace mlir; 23 using namespace mlir::shape; 24 25 namespace { 26 #include "ShapeCanonicalization.inc" 27 } 28 29 RankedTensorType shape::getExtentTensorType(MLIRContext *ctx) { 30 return RankedTensorType::get({ShapedType::kDynamicSize}, IndexType::get(ctx)); 31 } 32 33 static bool isErrorPropagationPossible(TypeRange operandTypes) { 34 for (Type ty : operandTypes) 35 if (ty.isa<SizeType>() || ty.isa<ShapeType>() || ty.isa<ValueShapeType>()) 36 return true; 37 return false; 38 } 39 40 static LogicalResult verifySizeOrIndexOp(Operation *op) { 41 assert(op != nullptr && op->getNumResults() == 1); 42 Type resultTy = op->getResultTypes().front(); 43 if (isErrorPropagationPossible(op->getOperandTypes())) { 44 if (!resultTy.isa<SizeType>()) 45 return op->emitOpError() 46 << "if at least one of the operands can hold error values then " 47 "the result must be of type `size` to propagate them"; 48 } 49 return success(); 50 } 51 52 static LogicalResult verifyShapeOrExtentTensorOp(Operation *op) { 53 assert(op != nullptr && op->getNumResults() == 1); 54 Type resultTy = op->getResultTypes().front(); 55 if (isErrorPropagationPossible(op->getOperandTypes())) { 56 if (!resultTy.isa<ShapeType>()) 57 return op->emitOpError() 58 << "if at least one of the operands can hold error values then " 59 "the result must be of type `shape` to propagate them"; 60 } 61 return success(); 62 } 63 64 //===----------------------------------------------------------------------===// 65 // InlinerInterface 66 //===----------------------------------------------------------------------===// 67 68 namespace { 69 /// This class defines the interface for inlining shape dialect ops. 70 struct ShapeInlinerInterface : public DialectInlinerInterface { 71 using DialectInlinerInterface::DialectInlinerInterface; 72 73 // Returns true if the given region 'src' can be inlined into the region 74 // 'dest' that is attached to an operation registered to the current dialect. 75 bool isLegalToInline(Region *dest, Region *src, 76 BlockAndValueMapping &) const final { 77 return true; 78 } 79 80 // Returns true if the given operation 'op', that is registered to this 81 // dialect, can be inlined into the region 'dest' that is attached to an 82 // operation registered to the current dialect. 83 bool isLegalToInline(Operation *op, Region *dest, 84 BlockAndValueMapping &) const final { 85 return true; 86 } 87 }; 88 } // namespace 89 90 void ShapeDialect::initialize() { 91 addOperations< 92 #define GET_OP_LIST 93 #include "mlir/Dialect/Shape/IR/ShapeOps.cpp.inc" 94 >(); 95 addTypes<ComponentType, ElementType, ShapeType, SizeType, ValueShapeType, 96 WitnessType>(); 97 addInterfaces<ShapeInlinerInterface>(); 98 // Allow unknown operations during prototyping and testing. As the dialect is 99 // still evolving it makes it simple to start with an unregistered ops and 100 // try different variants before actually defining the op. 101 allowUnknownOperations(); 102 } 103 104 Operation *ShapeDialect::materializeConstant(OpBuilder &builder, 105 Attribute value, Type type, 106 Location loc) { 107 if (type.isa<ShapeType>() || 108 type == getExtentTensorType(builder.getContext())) 109 return builder.create<ConstShapeOp>(loc, type, 110 value.cast<DenseIntElementsAttr>()); 111 if (type.isa<SizeType>()) 112 return builder.create<ConstSizeOp>(loc, type, value.cast<IntegerAttr>()); 113 if (type.isa<WitnessType>()) 114 return builder.create<ConstWitnessOp>(loc, type, value.cast<BoolAttr>()); 115 if (type.isa<IndexType>()) 116 return builder.create<ConstantOp>(loc, type, value); 117 return nullptr; 118 } 119 120 /// Parse a type registered to this dialect. 121 Type ShapeDialect::parseType(DialectAsmParser &parser) const { 122 StringRef keyword; 123 if (parser.parseKeyword(&keyword)) 124 return Type(); 125 126 if (keyword == "component") 127 return ComponentType::get(getContext()); 128 if (keyword == "element") 129 return ElementType::get(getContext()); 130 if (keyword == "shape") 131 return ShapeType::get(getContext()); 132 if (keyword == "size") 133 return SizeType::get(getContext()); 134 if (keyword == "value_shape") 135 return ValueShapeType::get(getContext()); 136 if (keyword == "witness") 137 return WitnessType::get(getContext()); 138 139 parser.emitError(parser.getNameLoc(), "unknown shape type: ") << keyword; 140 return Type(); 141 } 142 143 /// Print a type registered to this dialect. 144 void ShapeDialect::printType(Type type, DialectAsmPrinter &os) const { 145 TypeSwitch<Type>(type) 146 .Case<ComponentType>([&](Type) { os << "component"; }) 147 .Case<ElementType>([&](Type) { os << "element"; }) 148 .Case<ShapeType>([&](Type) { os << "shape"; }) 149 .Case<SizeType>([&](Type) { os << "size"; }) 150 .Case<ValueShapeType>([&](Type) { os << "value_shape"; }) 151 .Case<WitnessType>([&](Type) { os << "witness"; }) 152 .Default([](Type) { llvm_unreachable("unexpected 'shape' type kind"); }); 153 } 154 155 //===----------------------------------------------------------------------===// 156 // AnyOp 157 //===----------------------------------------------------------------------===// 158 159 // TODO: Canonicalization should be implemented for shapes that can be 160 // determined through mixtures of the known dimensions of the inputs. 161 OpFoldResult AnyOp::fold(ArrayRef<Attribute> operands) { 162 // Only the last operand is checked because AnyOp is commutative. 163 if (operands.back()) 164 return operands.back(); 165 166 return nullptr; 167 } 168 169 //===----------------------------------------------------------------------===// 170 // AssumingOp 171 //===----------------------------------------------------------------------===// 172 173 static ParseResult parseAssumingOp(OpAsmParser &parser, 174 OperationState &result) { 175 result.regions.reserve(1); 176 Region *doRegion = result.addRegion(); 177 178 auto &builder = parser.getBuilder(); 179 OpAsmParser::OperandType cond; 180 if (parser.parseOperand(cond) || 181 parser.resolveOperand(cond, builder.getType<WitnessType>(), 182 result.operands)) 183 return failure(); 184 185 // Parse optional results type list. 186 if (parser.parseOptionalArrowTypeList(result.types)) 187 return failure(); 188 189 // Parse the region and add a terminator if elided. 190 if (parser.parseRegion(*doRegion, /*arguments=*/{}, /*argTypes=*/{})) 191 return failure(); 192 AssumingOp::ensureTerminator(*doRegion, parser.getBuilder(), result.location); 193 194 // Parse the optional attribute list. 195 if (parser.parseOptionalAttrDict(result.attributes)) 196 return failure(); 197 return success(); 198 } 199 200 static void print(OpAsmPrinter &p, AssumingOp op) { 201 bool yieldsResults = !op.results().empty(); 202 203 p << AssumingOp::getOperationName() << " " << op.witness(); 204 if (yieldsResults) { 205 p << " -> (" << op.getResultTypes() << ")"; 206 } 207 p.printRegion(op.doRegion(), 208 /*printEntryBlockArgs=*/false, 209 /*printBlockTerminators=*/yieldsResults); 210 p.printOptionalAttrDict(op.getAttrs()); 211 } 212 213 namespace { 214 // Removes AssumingOp with a passing witness and inlines the region. 215 struct AssumingWithTrue : public OpRewritePattern<AssumingOp> { 216 using OpRewritePattern<AssumingOp>::OpRewritePattern; 217 218 LogicalResult matchAndRewrite(AssumingOp op, 219 PatternRewriter &rewriter) const override { 220 auto witness = op.witness().getDefiningOp<ConstWitnessOp>(); 221 if (!witness || !witness.passingAttr()) 222 return failure(); 223 224 AssumingOp::inlineRegionIntoParent(op, rewriter); 225 return success(); 226 } 227 }; 228 } // namespace 229 230 void AssumingOp::getCanonicalizationPatterns(OwningRewritePatternList &patterns, 231 MLIRContext *context) { 232 // If taking a passing witness, inline region. 233 patterns.insert<AssumingWithTrue>(context); 234 } 235 236 void AssumingOp::inlineRegionIntoParent(AssumingOp &op, 237 PatternRewriter &rewriter) { 238 auto *blockBeforeAssuming = rewriter.getInsertionBlock(); 239 auto *assumingBlock = op.getBody(); 240 auto initPosition = rewriter.getInsertionPoint(); 241 auto *blockAfterAssuming = 242 rewriter.splitBlock(blockBeforeAssuming, initPosition); 243 244 // Remove the AssumingOp and AssumingYieldOp. 245 auto &yieldOp = assumingBlock->back(); 246 rewriter.inlineRegionBefore(op.doRegion(), blockAfterAssuming); 247 rewriter.replaceOp(op, yieldOp.getOperands()); 248 rewriter.eraseOp(&yieldOp); 249 250 // Merge blocks together as there was no branching behavior from the 251 // AssumingOp. 252 rewriter.mergeBlocks(assumingBlock, blockBeforeAssuming); 253 rewriter.mergeBlocks(blockAfterAssuming, blockBeforeAssuming); 254 } 255 256 //===----------------------------------------------------------------------===// 257 // AssumingAllOp 258 //===----------------------------------------------------------------------===// 259 OpFoldResult AssumingAllOp::fold(ArrayRef<Attribute> operands) { 260 // Iterate in reverse to first handle all constant operands. They are 261 // guaranteed to be the tail of the inputs because this is commutative. 262 for (int idx = operands.size() - 1; idx >= 0; idx--) { 263 Attribute a = operands[idx]; 264 // Cannot fold if any inputs are not constant; 265 if (!a) 266 return nullptr; 267 268 // We do not need to keep statically known values after handling them in 269 // this method. 270 getOperation()->eraseOperand(idx); 271 272 // Always false if any input is statically known false 273 if (!a.cast<BoolAttr>().getValue()) 274 return a; 275 } 276 // If this is reached, all inputs were statically known passing. 277 return BoolAttr::get(true, getContext()); 278 } 279 280 static LogicalResult verify(AssumingAllOp op) { 281 // Ensure that AssumingAllOp contains at least one operand 282 if (op.getNumOperands() == 0) 283 return op.emitOpError("no operands specified"); 284 285 return success(); 286 } 287 288 //===----------------------------------------------------------------------===// 289 // BroadcastOp 290 //===----------------------------------------------------------------------===// 291 292 OpFoldResult BroadcastOp::fold(ArrayRef<Attribute> operands) { 293 if (!operands[1]) 294 return nullptr; 295 296 auto rhsShape = llvm::to_vector<6>( 297 operands[1].cast<DenseIntElementsAttr>().getValues<int64_t>()); 298 if (rhsShape.empty()) 299 return lhs(); 300 301 if (!operands[0]) 302 return nullptr; 303 304 auto lhsShape = llvm::to_vector<6>( 305 operands[0].cast<DenseIntElementsAttr>().getValues<int64_t>()); 306 if (lhsShape.empty()) 307 return rhs(); 308 309 SmallVector<int64_t, 6> resultShape; 310 // If the shapes are not compatible, we can't fold it. 311 // TODO: Fold to an "error". 312 if (!OpTrait::util::getBroadcastedShape(lhsShape, rhsShape, resultShape)) 313 return nullptr; 314 Builder builder(getContext()); 315 return builder.getIndexTensorAttr(resultShape); 316 } 317 318 //===----------------------------------------------------------------------===// 319 // ConcatOp 320 //===----------------------------------------------------------------------===// 321 322 OpFoldResult ConcatOp::fold(ArrayRef<Attribute> operands) { 323 if (!operands[0] || !operands[1]) 324 return nullptr; 325 auto lhsShape = llvm::to_vector<6>( 326 operands[0].cast<DenseIntElementsAttr>().getValues<int64_t>()); 327 auto rhsShape = llvm::to_vector<6>( 328 operands[1].cast<DenseIntElementsAttr>().getValues<int64_t>()); 329 SmallVector<int64_t, 6> resultShape; 330 resultShape.append(lhsShape.begin(), lhsShape.end()); 331 resultShape.append(rhsShape.begin(), rhsShape.end()); 332 Builder builder(getContext()); 333 return builder.getIndexTensorAttr(resultShape); 334 } 335 336 //===----------------------------------------------------------------------===// 337 // ConstShapeOp 338 //===----------------------------------------------------------------------===// 339 340 static void print(OpAsmPrinter &p, ConstShapeOp &op) { 341 p << "shape.const_shape "; 342 p.printOptionalAttrDict(op.getAttrs(), /*elidedAttrs=*/{"shape"}); 343 p << "["; 344 interleaveComma(op.shape().getValues<int64_t>(), p, 345 [&](int64_t i) { p << i; }); 346 p << "] : "; 347 p.printType(op.getType()); 348 } 349 350 static ParseResult parseConstShapeOp(OpAsmParser &parser, 351 OperationState &result) { 352 if (parser.parseOptionalAttrDict(result.attributes)) 353 return failure(); 354 // We piggy-back on ArrayAttr parsing, though we don't internally store the 355 // shape as an ArrayAttr. 356 // TODO: Implement custom parser and maybe make syntax a bit more concise. 357 Attribute extentsRaw; 358 NamedAttrList dummy; 359 if (parser.parseAttribute(extentsRaw, "dummy", dummy)) 360 return failure(); 361 auto extentsArray = extentsRaw.dyn_cast<ArrayAttr>(); 362 if (!extentsArray) 363 return failure(); 364 SmallVector<int64_t, 6> ints; 365 for (Attribute extent : extentsArray) { 366 IntegerAttr attr = extent.dyn_cast<IntegerAttr>(); 367 if (!attr) 368 return failure(); 369 ints.push_back(attr.getInt()); 370 } 371 Builder &builder = parser.getBuilder(); 372 result.addAttribute("shape", builder.getIndexTensorAttr(ints)); 373 Type resultTy; 374 if (parser.parseColonType(resultTy)) 375 return failure(); 376 result.types.push_back(resultTy); 377 return success(); 378 } 379 380 OpFoldResult ConstShapeOp::fold(ArrayRef<Attribute>) { return shapeAttr(); } 381 382 //===----------------------------------------------------------------------===// 383 // CstrBroadcastableOp 384 //===----------------------------------------------------------------------===// 385 386 namespace { 387 // Given an input shape Value, try to obtain the shape's values. 388 LogicalResult getShapeVec(Value input, SmallVectorImpl<int64_t> &shapeValues) { 389 if (auto inputOp = input.getDefiningOp<ShapeOfOp>()) { 390 auto type = inputOp.arg().getType().dyn_cast<ShapedType>(); 391 if (!type.hasRank()) 392 return failure(); 393 shapeValues = llvm::to_vector<6>(type.getShape()); 394 return success(); 395 } else if (auto inputOp = input.getDefiningOp<ConstShapeOp>()) { 396 shapeValues = llvm::to_vector<6>(inputOp.shape().getValues<int64_t>()); 397 return success(); 398 } else { 399 return failure(); 400 } 401 } 402 } // namespace 403 404 void CstrBroadcastableOp::getCanonicalizationPatterns( 405 OwningRewritePatternList &patterns, MLIRContext *context) { 406 // Canonicalization patterns have overlap with the considerations during 407 // folding in case additional shape information is inferred at some point that 408 // does not result in folding. 409 patterns.insert<CstrBroadcastableEqOps>(context); 410 } 411 412 OpFoldResult CstrBroadcastableOp::fold(ArrayRef<Attribute> operands) { 413 // Both operands are not needed if one is a scalar. 414 if (operands[0] && 415 operands[0].cast<DenseIntElementsAttr>().getNumElements() == 0) 416 return BoolAttr::get(true, getContext()); 417 if (operands[1] && 418 operands[1].cast<DenseIntElementsAttr>().getNumElements() == 0) 419 return BoolAttr::get(true, getContext()); 420 421 if (operands[0] && operands[1]) { 422 auto lhsShape = llvm::to_vector<6>( 423 operands[0].cast<DenseIntElementsAttr>().getValues<int64_t>()); 424 auto rhsShape = llvm::to_vector<6>( 425 operands[1].cast<DenseIntElementsAttr>().getValues<int64_t>()); 426 SmallVector<int64_t, 6> resultShape; 427 if (OpTrait::util::staticallyKnownBroadcastable(lhsShape, rhsShape)) 428 return BoolAttr::get(true, getContext()); 429 } 430 431 // Lastly, see if folding can be completed based on what constraints are known 432 // on the input shapes. 433 SmallVector<int64_t, 6> lhsShape, rhsShape; 434 if (failed(getShapeVec(lhs(), lhsShape))) 435 return nullptr; 436 if (failed(getShapeVec(rhs(), rhsShape))) 437 return nullptr; 438 439 if (OpTrait::util::staticallyKnownBroadcastable(lhsShape, rhsShape)) 440 return BoolAttr::get(true, getContext()); 441 442 // Because a failing witness result here represents an eventual assertion 443 // failure, we do not replace it with a constant witness. 444 return nullptr; 445 } 446 447 //===----------------------------------------------------------------------===// 448 // CstrEqOp 449 //===----------------------------------------------------------------------===// 450 451 void CstrEqOp::getCanonicalizationPatterns(OwningRewritePatternList &patterns, 452 MLIRContext *context) { 453 // If inputs are equal, return passing witness 454 patterns.insert<CstrEqEqOps>(context); 455 } 456 457 OpFoldResult CstrEqOp::fold(ArrayRef<Attribute> operands) { 458 if (llvm::all_of(operands, 459 [&](Attribute a) { return a && a == operands[0]; })) 460 return BoolAttr::get(true, getContext()); 461 462 // Because a failing witness result here represents an eventual assertion 463 // failure, we do not try to replace it with a constant witness. Similarly, we 464 // cannot if there are any non-const inputs. 465 return nullptr; 466 } 467 468 //===----------------------------------------------------------------------===// 469 // ConstSizeOp 470 //===----------------------------------------------------------------------===// 471 472 void ConstSizeOp::build(OpBuilder &builder, OperationState &result, 473 int64_t value) { 474 build(builder, result, builder.getIndexAttr(value)); 475 } 476 477 OpFoldResult ConstSizeOp::fold(ArrayRef<Attribute>) { return valueAttr(); } 478 479 void ConstSizeOp::getAsmResultNames( 480 llvm::function_ref<void(Value, StringRef)> setNameFn) { 481 SmallString<4> buffer; 482 llvm::raw_svector_ostream os(buffer); 483 os << "c" << value(); 484 setNameFn(getResult(), os.str()); 485 } 486 487 //===----------------------------------------------------------------------===// 488 // ConstWitnessOp 489 //===----------------------------------------------------------------------===// 490 491 OpFoldResult ConstWitnessOp::fold(ArrayRef<Attribute>) { return passingAttr(); } 492 493 //===----------------------------------------------------------------------===// 494 // CstrRequireOp 495 //===----------------------------------------------------------------------===// 496 497 OpFoldResult CstrRequireOp::fold(ArrayRef<Attribute> operands) { 498 return operands[0]; 499 } 500 501 //===----------------------------------------------------------------------===// 502 // ShapeEqOp 503 //===----------------------------------------------------------------------===// 504 505 OpFoldResult ShapeEqOp::fold(ArrayRef<Attribute> operands) { 506 auto lhs = operands[0].dyn_cast_or_null<DenseIntElementsAttr>(); 507 if (lhs == nullptr) 508 return {}; 509 auto rhs = operands[1].dyn_cast_or_null<DenseIntElementsAttr>(); 510 if (rhs == nullptr) 511 return {}; 512 return BoolAttr::get(lhs == rhs, getContext()); 513 } 514 515 //===----------------------------------------------------------------------===// 516 // IndexToSizeOp 517 //===----------------------------------------------------------------------===// 518 519 OpFoldResult IndexToSizeOp::fold(ArrayRef<Attribute> operands) { 520 // Constant values of both types, `shape.size` and `index`, are represented as 521 // `IntegerAttr`s which makes constant folding simple. 522 if (Attribute arg = operands[0]) 523 return arg; 524 return {}; 525 } 526 527 void IndexToSizeOp::getCanonicalizationPatterns( 528 OwningRewritePatternList &patterns, MLIRContext *context) { 529 patterns.insert<SizeToIndexToSizeCanonicalization>(context); 530 } 531 532 //===----------------------------------------------------------------------===// 533 // FromExtentsOp 534 //===----------------------------------------------------------------------===// 535 536 OpFoldResult FromExtentsOp::fold(ArrayRef<Attribute> operands) { 537 if (llvm::any_of(operands, [](Attribute a) { return !a; })) 538 return nullptr; 539 SmallVector<int64_t, 6> extents; 540 for (auto attr : operands) 541 extents.push_back(attr.cast<IntegerAttr>().getInt()); 542 Builder builder(getContext()); 543 return builder.getIndexTensorAttr(extents); 544 } 545 546 //===----------------------------------------------------------------------===// 547 // GetExtentOp 548 //===----------------------------------------------------------------------===// 549 550 Optional<int64_t> GetExtentOp::getConstantDim() { 551 if (auto constSizeOp = dim().getDefiningOp<ConstSizeOp>()) 552 return constSizeOp.value().getLimitedValue(); 553 if (auto constantOp = dim().getDefiningOp<ConstantOp>()) 554 return constantOp.value().cast<IntegerAttr>().getInt(); 555 return llvm::None; 556 } 557 558 OpFoldResult GetExtentOp::fold(ArrayRef<Attribute> operands) { 559 auto elements = operands[0].dyn_cast_or_null<DenseIntElementsAttr>(); 560 if (!elements) 561 return nullptr; 562 Optional<int64_t> dim = getConstantDim(); 563 if (!dim.hasValue()) 564 return nullptr; 565 if (dim.getValue() >= elements.getNumElements()) 566 return nullptr; 567 return elements.getValue({(uint64_t)dim.getValue()}); 568 } 569 570 void GetExtentOp::build(OpBuilder &builder, OperationState &result, Value shape, 571 int64_t dim) { 572 auto loc = result.location; 573 auto dimAttr = builder.getIndexAttr(dim); 574 if (shape.getType().isa<ShapeType>()) { 575 Value dim = builder.create<ConstSizeOp>(loc, dimAttr); 576 build(builder, result, builder.getType<SizeType>(), shape, dim); 577 } else { 578 Value dim = 579 builder.create<ConstantOp>(loc, builder.getIndexType(), dimAttr); 580 build(builder, result, builder.getIndexType(), shape, dim); 581 } 582 } 583 584 //===----------------------------------------------------------------------===// 585 // RankOp 586 //===----------------------------------------------------------------------===// 587 588 OpFoldResult shape::RankOp::fold(ArrayRef<Attribute> operands) { 589 auto shape = operands[0].dyn_cast_or_null<DenseIntElementsAttr>(); 590 if (!shape) 591 return {}; 592 int64_t rank = shape.getNumElements(); 593 Builder builder(getContext()); 594 return builder.getIndexAttr(rank); 595 } 596 597 /// Evaluate the `rank` operation for shapes of ranked tensors at compile time. 598 /// Constant folding fails in cases where only the rank is constant, not the 599 /// shape itself. 600 /// This canonicalization matches `shape.rank(shape.shape_of(%ranked_tensor))`. 601 /// 602 /// Example: 603 /// 604 /// %shape = shape.shape_of %ranked_tensor : tensor<1x2x?xf32> 605 /// %rank = shape.rank %shape 606 /// 607 /// becomes 608 /// 609 /// %rank = shape.const_size 3 610 611 namespace { 612 struct RankShapeOfCanonicalizationPattern 613 : public OpRewritePattern<shape::RankOp> { 614 using OpRewritePattern<shape::RankOp>::OpRewritePattern; 615 616 LogicalResult matchAndRewrite(shape::RankOp op, 617 PatternRewriter &rewriter) const override { 618 auto shapeOfOp = op.shape().getDefiningOp<ShapeOfOp>(); 619 if (!shapeOfOp) 620 return failure(); 621 auto rankedTensorType = 622 shapeOfOp.arg().getType().dyn_cast<RankedTensorType>(); 623 if (!rankedTensorType) 624 return failure(); 625 int64_t rank = rankedTensorType.getRank(); 626 if (op.getType().isa<IndexType>()) { 627 rewriter.replaceOpWithNewOp<ConstantIndexOp>(op.getOperation(), rank); 628 } else if (op.getType().isa<shape::SizeType>()) { 629 rewriter.replaceOpWithNewOp<shape::ConstSizeOp>(op.getOperation(), rank); 630 } else { 631 return failure(); 632 } 633 return success(); 634 } 635 }; 636 } // namespace 637 638 void shape::RankOp::getCanonicalizationPatterns( 639 OwningRewritePatternList &patterns, MLIRContext *context) { 640 patterns.insert<RankShapeOfCanonicalizationPattern>(context); 641 } 642 643 //===----------------------------------------------------------------------===// 644 // NumElementsOp 645 //===----------------------------------------------------------------------===// 646 647 OpFoldResult NumElementsOp::fold(ArrayRef<Attribute> operands) { 648 649 // Fold only when argument constant. 650 Attribute shape = operands[0]; 651 if (!shape) 652 return {}; 653 654 APInt product(64, 1); 655 for (auto value : shape.cast<DenseIntElementsAttr>()) 656 product *= value; 657 Builder builder(getContext()); 658 return builder.getIndexAttr(product.getLimitedValue()); 659 } 660 661 void NumElementsOp::build(OpBuilder &builder, OperationState &result, 662 Value shape) { 663 if (shape.getType().isa<ShapedType>()) { 664 auto type = builder.getIndexType(); 665 return build(builder, result, type, shape); 666 } 667 auto type = SizeType::get(builder.getContext()); 668 return build(builder, result, type, shape); 669 } 670 671 //===----------------------------------------------------------------------===// 672 // MulOp 673 //===----------------------------------------------------------------------===// 674 675 OpFoldResult MulOp::fold(ArrayRef<Attribute> operands) { 676 auto lhs = operands[0].dyn_cast_or_null<IntegerAttr>(); 677 if (!lhs) 678 return nullptr; 679 auto rhs = operands[1].dyn_cast_or_null<IntegerAttr>(); 680 if (!rhs) 681 return nullptr; 682 APInt folded = lhs.getValue() * rhs.getValue(); 683 Type indexTy = IndexType::get(getContext()); 684 return IntegerAttr::get(indexTy, folded); 685 } 686 687 //===----------------------------------------------------------------------===// 688 // ShapeOfOp 689 //===----------------------------------------------------------------------===// 690 691 OpFoldResult ShapeOfOp::fold(ArrayRef<Attribute>) { 692 auto type = getOperand().getType().dyn_cast<ShapedType>(); 693 if (!type || !type.hasStaticShape()) 694 return nullptr; 695 Builder builder(getContext()); 696 return builder.getIndexTensorAttr(type.getShape()); 697 } 698 699 void ShapeOfOp::build(OpBuilder &builder, OperationState &result, Value arg) { 700 Type type = arg.getType().isa<ShapedType>() 701 ? (Type)getExtentTensorType(builder.getContext()) 702 : (Type)builder.getType<ShapeType>(); 703 return ShapeOfOp::build(builder, result, type, arg); 704 } 705 706 namespace { 707 struct ShapeOfWithTensor : public OpRewritePattern<shape::ShapeOfOp> { 708 using OpRewritePattern<shape::ShapeOfOp>::OpRewritePattern; 709 710 LogicalResult matchAndRewrite(shape::ShapeOfOp op, 711 PatternRewriter &rewriter) const override { 712 if (!op.arg().getType().isa<ShapedType>()) 713 return failure(); 714 if (op.getType().isa<ShapedType>()) 715 return failure(); 716 717 rewriter.replaceOpWithNewOp<shape::ShapeOfOp>(op.getOperation(), op.arg()); 718 return success(); 719 } 720 }; 721 } // namespace 722 723 void ShapeOfOp::getCanonicalizationPatterns(OwningRewritePatternList &patterns, 724 MLIRContext *context) { 725 patterns.insert<ShapeOfWithTensor>(context); 726 } 727 728 //===----------------------------------------------------------------------===// 729 // SizeToIndexOp 730 //===----------------------------------------------------------------------===// 731 732 OpFoldResult SizeToIndexOp::fold(ArrayRef<Attribute> operands) { 733 // Constant values of both types, `shape.size` and `index`, are represented as 734 // `IntegerAttr`s which makes constant folding simple. 735 if (Attribute arg = operands[0]) 736 return arg; 737 return impl::foldCastOp(*this); 738 } 739 740 void SizeToIndexOp::getCanonicalizationPatterns( 741 OwningRewritePatternList &patterns, MLIRContext *context) { 742 patterns.insert<IndexToSizeToIndexCanonicalization>(context); 743 } 744 745 //===----------------------------------------------------------------------===// 746 // YieldOp 747 //===----------------------------------------------------------------------===// 748 749 static LogicalResult verify(shape::YieldOp op) { 750 auto *parentOp = op.getParentOp(); 751 auto results = parentOp->getResults(); 752 auto operands = op.getOperands(); 753 754 if (parentOp->getNumResults() != op.getNumOperands()) 755 return op.emitOpError() << "number of operands does not match number of " 756 "results of its parent"; 757 for (auto e : llvm::zip(results, operands)) 758 if (std::get<0>(e).getType() != std::get<1>(e).getType()) 759 return op.emitOpError() 760 << "types mismatch between yield op and its parent"; 761 762 return success(); 763 } 764 765 //===----------------------------------------------------------------------===// 766 // SplitAtOp 767 //===----------------------------------------------------------------------===// 768 769 LogicalResult SplitAtOp::fold(ArrayRef<Attribute> operands, 770 SmallVectorImpl<OpFoldResult> &results) { 771 if (!operands[0] || !operands[1]) 772 return failure(); 773 auto shapeVec = llvm::to_vector<6>( 774 operands[0].cast<DenseIntElementsAttr>().getValues<int64_t>()); 775 auto shape = llvm::makeArrayRef(shapeVec); 776 auto splitPoint = operands[1].cast<IntegerAttr>().getInt(); 777 // Verify that the split point is in the correct range. 778 // TODO: Constant fold to an "error". 779 int64_t rank = shape.size(); 780 if (!(-rank <= splitPoint && splitPoint <= rank)) 781 return failure(); 782 if (splitPoint < 0) 783 splitPoint += shape.size(); 784 Builder builder(operands[0].getContext()); 785 results.push_back(builder.getIndexTensorAttr(shape.take_front(splitPoint))); 786 results.push_back(builder.getIndexTensorAttr(shape.drop_front(splitPoint))); 787 return success(); 788 } 789 790 //===----------------------------------------------------------------------===// 791 // ToExtentTensorOp 792 //===----------------------------------------------------------------------===// 793 794 OpFoldResult ToExtentTensorOp::fold(ArrayRef<Attribute> operands) { 795 if (!operands[0]) 796 return impl::foldCastOp(*this); 797 Builder builder(getContext()); 798 auto shape = llvm::to_vector<6>( 799 operands[0].cast<DenseIntElementsAttr>().getValues<int64_t>()); 800 auto type = RankedTensorType::get({static_cast<int64_t>(shape.size())}, 801 builder.getIndexType()); 802 return DenseIntElementsAttr::get(type, shape); 803 } 804 805 //===----------------------------------------------------------------------===// 806 // ReduceOp 807 //===----------------------------------------------------------------------===// 808 809 void ReduceOp::build(OpBuilder &builder, OperationState &result, Value shape, 810 ValueRange initVals) { 811 result.addOperands(shape); 812 result.addOperands(initVals); 813 814 Region *bodyRegion = result.addRegion(); 815 bodyRegion->push_back(new Block); 816 Block &bodyBlock = bodyRegion->front(); 817 bodyBlock.addArgument(builder.getIndexType()); 818 819 Type elementType; 820 if (auto tensorType = shape.getType().dyn_cast<TensorType>()) 821 elementType = tensorType.getElementType(); 822 else 823 elementType = SizeType::get(builder.getContext()); 824 bodyBlock.addArgument(elementType); 825 826 for (Type initValType : initVals.getTypes()) { 827 bodyBlock.addArgument(initValType); 828 result.addTypes(initValType); 829 } 830 } 831 832 static LogicalResult verify(ReduceOp op) { 833 // Verify block arg types. 834 Block &block = op.region().front(); 835 836 // The block takes index, extent, and aggregated values as arguments. 837 auto blockArgsCount = op.initVals().size() + 2; 838 if (block.getNumArguments() != blockArgsCount) 839 return op.emitOpError() << "ReduceOp body is expected to have " 840 << blockArgsCount << " arguments"; 841 842 // The first block argument is the index and must always be of type `index`. 843 if (!block.getArgument(0).getType().isa<IndexType>()) 844 return op.emitOpError( 845 "argument 0 of ReduceOp body is expected to be of IndexType"); 846 847 // The second block argument is the extent and must be of type `size` or 848 // `index`, depending on whether the reduce operation is applied to a shape or 849 // to an extent tensor. 850 Type extentTy = block.getArgument(1).getType(); 851 if (op.shape().getType().isa<ShapeType>()) { 852 if (!extentTy.isa<SizeType>()) 853 return op.emitOpError("argument 1 of ReduceOp body is expected to be of " 854 "SizeType if the ReduceOp operates on a ShapeType"); 855 } else { 856 if (!extentTy.isa<IndexType>()) 857 return op.emitOpError( 858 "argument 1 of ReduceOp body is expected to be of IndexType if the " 859 "ReduceOp operates on an extent tensor"); 860 } 861 862 for (auto type : llvm::enumerate(op.initVals())) 863 if (block.getArgument(type.index() + 2).getType() != type.value().getType()) 864 return op.emitOpError() 865 << "type mismatch between argument " << type.index() + 2 866 << " of ReduceOp body and initial value " << type.index(); 867 return success(); 868 } 869 870 static ParseResult parseReduceOp(OpAsmParser &parser, OperationState &result) { 871 // Parse operands. 872 SmallVector<OpAsmParser::OperandType, 3> operands; 873 Type shapeOrExtentTensorType; 874 if (parser.parseOperandList(operands, /*requiredOperandCount=*/-1, 875 OpAsmParser::Delimiter::Paren) || 876 parser.parseColonType(shapeOrExtentTensorType) || 877 parser.parseOptionalArrowTypeList(result.types)) 878 return failure(); 879 880 // Resolve operands. 881 auto initVals = llvm::makeArrayRef(operands).drop_front(); 882 if (parser.resolveOperand(operands.front(), shapeOrExtentTensorType, 883 result.operands) || 884 parser.resolveOperands(initVals, result.types, parser.getNameLoc(), 885 result.operands)) 886 return failure(); 887 888 // Parse the body. 889 Region *body = result.addRegion(); 890 if (parser.parseRegion(*body, /*args=*/{}, /*argTypes=*/{})) 891 return failure(); 892 893 // Parse attributes. 894 if (parser.parseOptionalAttrDict(result.attributes)) 895 return failure(); 896 897 return success(); 898 } 899 900 static void print(OpAsmPrinter &p, ReduceOp op) { 901 p << op.getOperationName() << '(' << op.shape() << ", " << op.initVals() 902 << ") : " << op.shape().getType(); 903 p.printOptionalArrowTypeList(op.getResultTypes()); 904 p.printRegion(op.region()); 905 p.printOptionalAttrDict(op.getAttrs()); 906 } 907 908 #define GET_OP_CLASSES 909 #include "mlir/Dialect/Shape/IR/ShapeOps.cpp.inc" 910