1 //===- TestDialect.cpp - MLIR Dialect for Testing -------------------------===// 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 "TestDialect.h" 10 #include "TestTypes.h" 11 #include "mlir/Dialect/StandardOps/IR/Ops.h" 12 #include "mlir/IR/DialectImplementation.h" 13 #include "mlir/IR/Function.h" 14 #include "mlir/IR/Module.h" 15 #include "mlir/IR/PatternMatch.h" 16 #include "mlir/IR/TypeUtilities.h" 17 #include "mlir/Transforms/FoldUtils.h" 18 #include "mlir/Transforms/InliningUtils.h" 19 #include "llvm/ADT/SetVector.h" 20 #include "llvm/ADT/StringSwitch.h" 21 22 using namespace mlir; 23 24 void mlir::registerTestDialect(DialectRegistry ®istry) { 25 registry.insert<TestDialect>(); 26 } 27 28 //===----------------------------------------------------------------------===// 29 // TestDialect Interfaces 30 //===----------------------------------------------------------------------===// 31 32 namespace { 33 34 // Test support for interacting with the AsmPrinter. 35 struct TestOpAsmInterface : public OpAsmDialectInterface { 36 using OpAsmDialectInterface::OpAsmDialectInterface; 37 38 void getAsmResultNames(Operation *op, 39 OpAsmSetValueNameFn setNameFn) const final { 40 if (auto asmOp = dyn_cast<AsmDialectInterfaceOp>(op)) 41 setNameFn(asmOp, "result"); 42 } 43 44 void getAsmBlockArgumentNames(Block *block, 45 OpAsmSetValueNameFn setNameFn) const final { 46 auto op = block->getParentOp(); 47 auto arrayAttr = op->getAttrOfType<ArrayAttr>("arg_names"); 48 if (!arrayAttr) 49 return; 50 auto args = block->getArguments(); 51 auto e = std::min(arrayAttr.size(), args.size()); 52 for (unsigned i = 0; i < e; ++i) { 53 if (auto strAttr = arrayAttr[i].dyn_cast<StringAttr>()) 54 setNameFn(args[i], strAttr.getValue()); 55 } 56 } 57 }; 58 59 struct TestDialectFoldInterface : public DialectFoldInterface { 60 using DialectFoldInterface::DialectFoldInterface; 61 62 /// Registered hook to check if the given region, which is attached to an 63 /// operation that is *not* isolated from above, should be used when 64 /// materializing constants. 65 bool shouldMaterializeInto(Region *region) const final { 66 // If this is a one region operation, then insert into it. 67 return isa<OneRegionOp>(region->getParentOp()); 68 } 69 }; 70 71 /// This class defines the interface for handling inlining with standard 72 /// operations. 73 struct TestInlinerInterface : public DialectInlinerInterface { 74 using DialectInlinerInterface::DialectInlinerInterface; 75 76 //===--------------------------------------------------------------------===// 77 // Analysis Hooks 78 //===--------------------------------------------------------------------===// 79 80 bool isLegalToInline(Region *, Region *, BlockAndValueMapping &) const final { 81 // Inlining into test dialect regions is legal. 82 return true; 83 } 84 bool isLegalToInline(Operation *, Region *, 85 BlockAndValueMapping &) const final { 86 return true; 87 } 88 89 bool shouldAnalyzeRecursively(Operation *op) const final { 90 // Analyze recursively if this is not a functional region operation, it 91 // froms a separate functional scope. 92 return !isa<FunctionalRegionOp>(op); 93 } 94 95 //===--------------------------------------------------------------------===// 96 // Transformation Hooks 97 //===--------------------------------------------------------------------===// 98 99 /// Handle the given inlined terminator by replacing it with a new operation 100 /// as necessary. 101 void handleTerminator(Operation *op, 102 ArrayRef<Value> valuesToRepl) const final { 103 // Only handle "test.return" here. 104 auto returnOp = dyn_cast<TestReturnOp>(op); 105 if (!returnOp) 106 return; 107 108 // Replace the values directly with the return operands. 109 assert(returnOp.getNumOperands() == valuesToRepl.size()); 110 for (const auto &it : llvm::enumerate(returnOp.getOperands())) 111 valuesToRepl[it.index()].replaceAllUsesWith(it.value()); 112 } 113 114 /// Attempt to materialize a conversion for a type mismatch between a call 115 /// from this dialect, and a callable region. This method should generate an 116 /// operation that takes 'input' as the only operand, and produces a single 117 /// result of 'resultType'. If a conversion can not be generated, nullptr 118 /// should be returned. 119 Operation *materializeCallConversion(OpBuilder &builder, Value input, 120 Type resultType, 121 Location conversionLoc) const final { 122 // Only allow conversion for i16/i32 types. 123 if (!(resultType.isSignlessInteger(16) || 124 resultType.isSignlessInteger(32)) || 125 !(input.getType().isSignlessInteger(16) || 126 input.getType().isSignlessInteger(32))) 127 return nullptr; 128 return builder.create<TestCastOp>(conversionLoc, resultType, input); 129 } 130 }; 131 } // end anonymous namespace 132 133 //===----------------------------------------------------------------------===// 134 // TestDialect 135 //===----------------------------------------------------------------------===// 136 137 void TestDialect::initialize() { 138 addOperations< 139 #define GET_OP_LIST 140 #include "TestOps.cpp.inc" 141 >(); 142 addInterfaces<TestOpAsmInterface, TestDialectFoldInterface, 143 TestInlinerInterface>(); 144 addTypes<TestType, TestRecursiveType, 145 #define GET_TYPEDEF_LIST 146 #include "TestTypeDefs.cpp.inc" 147 >(); 148 allowUnknownOperations(); 149 } 150 151 static Type parseTestType(MLIRContext *ctxt, DialectAsmParser &parser, 152 llvm::SetVector<Type> &stack) { 153 StringRef typeTag; 154 if (failed(parser.parseKeyword(&typeTag))) 155 return Type(); 156 157 auto genType = generatedTypeParser(ctxt, parser, typeTag); 158 if (genType != Type()) 159 return genType; 160 161 if (typeTag == "test_type") 162 return TestType::get(parser.getBuilder().getContext()); 163 164 if (typeTag != "test_rec") 165 return Type(); 166 167 StringRef name; 168 if (parser.parseLess() || parser.parseKeyword(&name)) 169 return Type(); 170 auto rec = TestRecursiveType::get(parser.getBuilder().getContext(), name); 171 172 // If this type already has been parsed above in the stack, expect just the 173 // name. 174 if (stack.contains(rec)) { 175 if (failed(parser.parseGreater())) 176 return Type(); 177 return rec; 178 } 179 180 // Otherwise, parse the body and update the type. 181 if (failed(parser.parseComma())) 182 return Type(); 183 stack.insert(rec); 184 Type subtype = parseTestType(ctxt, parser, stack); 185 stack.pop_back(); 186 if (!subtype || failed(parser.parseGreater()) || failed(rec.setBody(subtype))) 187 return Type(); 188 189 return rec; 190 } 191 192 Type TestDialect::parseType(DialectAsmParser &parser) const { 193 llvm::SetVector<Type> stack; 194 return parseTestType(getContext(), parser, stack); 195 } 196 197 static void printTestType(Type type, DialectAsmPrinter &printer, 198 llvm::SetVector<Type> &stack) { 199 if (succeeded(generatedTypePrinter(type, printer))) 200 return; 201 if (type.isa<TestType>()) { 202 printer << "test_type"; 203 return; 204 } 205 206 auto rec = type.cast<TestRecursiveType>(); 207 printer << "test_rec<" << rec.getName(); 208 if (!stack.contains(rec)) { 209 printer << ", "; 210 stack.insert(rec); 211 printTestType(rec.getBody(), printer, stack); 212 stack.pop_back(); 213 } 214 printer << ">"; 215 } 216 217 void TestDialect::printType(Type type, DialectAsmPrinter &printer) const { 218 llvm::SetVector<Type> stack; 219 printTestType(type, printer, stack); 220 } 221 222 LogicalResult TestDialect::verifyOperationAttribute(Operation *op, 223 NamedAttribute namedAttr) { 224 if (namedAttr.first == "test.invalid_attr") 225 return op->emitError() << "invalid to use 'test.invalid_attr'"; 226 return success(); 227 } 228 229 LogicalResult TestDialect::verifyRegionArgAttribute(Operation *op, 230 unsigned regionIndex, 231 unsigned argIndex, 232 NamedAttribute namedAttr) { 233 if (namedAttr.first == "test.invalid_attr") 234 return op->emitError() << "invalid to use 'test.invalid_attr'"; 235 return success(); 236 } 237 238 LogicalResult 239 TestDialect::verifyRegionResultAttribute(Operation *op, unsigned regionIndex, 240 unsigned resultIndex, 241 NamedAttribute namedAttr) { 242 if (namedAttr.first == "test.invalid_attr") 243 return op->emitError() << "invalid to use 'test.invalid_attr'"; 244 return success(); 245 } 246 247 //===----------------------------------------------------------------------===// 248 // TestBranchOp 249 //===----------------------------------------------------------------------===// 250 251 Optional<MutableOperandRange> 252 TestBranchOp::getMutableSuccessorOperands(unsigned index) { 253 assert(index == 0 && "invalid successor index"); 254 return targetOperandsMutable(); 255 } 256 257 //===----------------------------------------------------------------------===// 258 // TestFoldToCallOp 259 //===----------------------------------------------------------------------===// 260 261 namespace { 262 struct FoldToCallOpPattern : public OpRewritePattern<FoldToCallOp> { 263 using OpRewritePattern<FoldToCallOp>::OpRewritePattern; 264 265 LogicalResult matchAndRewrite(FoldToCallOp op, 266 PatternRewriter &rewriter) const override { 267 rewriter.replaceOpWithNewOp<CallOp>(op, TypeRange(), op.calleeAttr(), 268 ValueRange()); 269 return success(); 270 } 271 }; 272 } // end anonymous namespace 273 274 void FoldToCallOp::getCanonicalizationPatterns( 275 OwningRewritePatternList &results, MLIRContext *context) { 276 results.insert<FoldToCallOpPattern>(context); 277 } 278 279 //===----------------------------------------------------------------------===// 280 // Test Format* operations 281 //===----------------------------------------------------------------------===// 282 283 //===----------------------------------------------------------------------===// 284 // Parsing 285 286 static ParseResult parseCustomDirectiveOperands( 287 OpAsmParser &parser, OpAsmParser::OperandType &operand, 288 Optional<OpAsmParser::OperandType> &optOperand, 289 SmallVectorImpl<OpAsmParser::OperandType> &varOperands) { 290 if (parser.parseOperand(operand)) 291 return failure(); 292 if (succeeded(parser.parseOptionalComma())) { 293 optOperand.emplace(); 294 if (parser.parseOperand(*optOperand)) 295 return failure(); 296 } 297 if (parser.parseArrow() || parser.parseLParen() || 298 parser.parseOperandList(varOperands) || parser.parseRParen()) 299 return failure(); 300 return success(); 301 } 302 static ParseResult 303 parseCustomDirectiveResults(OpAsmParser &parser, Type &operandType, 304 Type &optOperandType, 305 SmallVectorImpl<Type> &varOperandTypes) { 306 if (parser.parseColon()) 307 return failure(); 308 309 if (parser.parseType(operandType)) 310 return failure(); 311 if (succeeded(parser.parseOptionalComma())) { 312 if (parser.parseType(optOperandType)) 313 return failure(); 314 } 315 if (parser.parseArrow() || parser.parseLParen() || 316 parser.parseTypeList(varOperandTypes) || parser.parseRParen()) 317 return failure(); 318 return success(); 319 } 320 static ParseResult 321 parseCustomDirectiveWithTypeRefs(OpAsmParser &parser, Type operandType, 322 Type optOperandType, 323 const SmallVectorImpl<Type> &varOperandTypes) { 324 if (parser.parseKeyword("type_refs_capture")) 325 return failure(); 326 327 Type operandType2, optOperandType2; 328 SmallVector<Type, 1> varOperandTypes2; 329 if (parseCustomDirectiveResults(parser, operandType2, optOperandType2, 330 varOperandTypes2)) 331 return failure(); 332 333 if (operandType != operandType2 || optOperandType != optOperandType2 || 334 varOperandTypes != varOperandTypes2) 335 return failure(); 336 337 return success(); 338 } 339 static ParseResult parseCustomDirectiveOperandsAndTypes( 340 OpAsmParser &parser, OpAsmParser::OperandType &operand, 341 Optional<OpAsmParser::OperandType> &optOperand, 342 SmallVectorImpl<OpAsmParser::OperandType> &varOperands, Type &operandType, 343 Type &optOperandType, SmallVectorImpl<Type> &varOperandTypes) { 344 if (parseCustomDirectiveOperands(parser, operand, optOperand, varOperands) || 345 parseCustomDirectiveResults(parser, operandType, optOperandType, 346 varOperandTypes)) 347 return failure(); 348 return success(); 349 } 350 static ParseResult parseCustomDirectiveRegions( 351 OpAsmParser &parser, Region ®ion, 352 SmallVectorImpl<std::unique_ptr<Region>> &varRegions) { 353 if (parser.parseRegion(region)) 354 return failure(); 355 if (failed(parser.parseOptionalComma())) 356 return success(); 357 std::unique_ptr<Region> varRegion = std::make_unique<Region>(); 358 if (parser.parseRegion(*varRegion)) 359 return failure(); 360 varRegions.emplace_back(std::move(varRegion)); 361 return success(); 362 } 363 static ParseResult 364 parseCustomDirectiveSuccessors(OpAsmParser &parser, Block *&successor, 365 SmallVectorImpl<Block *> &varSuccessors) { 366 if (parser.parseSuccessor(successor)) 367 return failure(); 368 if (failed(parser.parseOptionalComma())) 369 return success(); 370 Block *varSuccessor; 371 if (parser.parseSuccessor(varSuccessor)) 372 return failure(); 373 varSuccessors.append(2, varSuccessor); 374 return success(); 375 } 376 static ParseResult parseCustomDirectiveAttributes(OpAsmParser &parser, 377 IntegerAttr &attr, 378 IntegerAttr &optAttr) { 379 if (parser.parseAttribute(attr)) 380 return failure(); 381 if (succeeded(parser.parseOptionalComma())) { 382 if (parser.parseAttribute(optAttr)) 383 return failure(); 384 } 385 return success(); 386 } 387 388 //===----------------------------------------------------------------------===// 389 // Printing 390 391 static void printCustomDirectiveOperands(OpAsmPrinter &printer, Value operand, 392 Value optOperand, 393 OperandRange varOperands) { 394 printer << operand; 395 if (optOperand) 396 printer << ", " << optOperand; 397 printer << " -> (" << varOperands << ")"; 398 } 399 static void printCustomDirectiveResults(OpAsmPrinter &printer, Type operandType, 400 Type optOperandType, 401 TypeRange varOperandTypes) { 402 printer << " : " << operandType; 403 if (optOperandType) 404 printer << ", " << optOperandType; 405 printer << " -> (" << varOperandTypes << ")"; 406 } 407 static void printCustomDirectiveWithTypeRefs(OpAsmPrinter &printer, 408 Type operandType, 409 Type optOperandType, 410 TypeRange varOperandTypes) { 411 printer << " type_refs_capture "; 412 printCustomDirectiveResults(printer, operandType, optOperandType, 413 varOperandTypes); 414 } 415 static void 416 printCustomDirectiveOperandsAndTypes(OpAsmPrinter &printer, Value operand, 417 Value optOperand, OperandRange varOperands, 418 Type operandType, Type optOperandType, 419 TypeRange varOperandTypes) { 420 printCustomDirectiveOperands(printer, operand, optOperand, varOperands); 421 printCustomDirectiveResults(printer, operandType, optOperandType, 422 varOperandTypes); 423 } 424 static void printCustomDirectiveRegions(OpAsmPrinter &printer, Region ®ion, 425 MutableArrayRef<Region> varRegions) { 426 printer.printRegion(region); 427 if (!varRegions.empty()) { 428 printer << ", "; 429 for (Region ®ion : varRegions) 430 printer.printRegion(region); 431 } 432 } 433 static void printCustomDirectiveSuccessors(OpAsmPrinter &printer, 434 Block *successor, 435 SuccessorRange varSuccessors) { 436 printer << successor; 437 if (!varSuccessors.empty()) 438 printer << ", " << varSuccessors.front(); 439 } 440 static void printCustomDirectiveAttributes(OpAsmPrinter &printer, 441 Attribute attribute, 442 Attribute optAttribute) { 443 printer << attribute; 444 if (optAttribute) 445 printer << ", " << optAttribute; 446 } 447 448 //===----------------------------------------------------------------------===// 449 // Test IsolatedRegionOp - parse passthrough region arguments. 450 //===----------------------------------------------------------------------===// 451 452 static ParseResult parseIsolatedRegionOp(OpAsmParser &parser, 453 OperationState &result) { 454 OpAsmParser::OperandType argInfo; 455 Type argType = parser.getBuilder().getIndexType(); 456 457 // Parse the input operand. 458 if (parser.parseOperand(argInfo) || 459 parser.resolveOperand(argInfo, argType, result.operands)) 460 return failure(); 461 462 // Parse the body region, and reuse the operand info as the argument info. 463 Region *body = result.addRegion(); 464 return parser.parseRegion(*body, argInfo, argType, 465 /*enableNameShadowing=*/true); 466 } 467 468 static void print(OpAsmPrinter &p, IsolatedRegionOp op) { 469 p << "test.isolated_region "; 470 p.printOperand(op.getOperand()); 471 p.shadowRegionArgs(op.region(), op.getOperand()); 472 p.printRegion(op.region(), /*printEntryBlockArgs=*/false); 473 } 474 475 //===----------------------------------------------------------------------===// 476 // Test SSACFGRegionOp 477 //===----------------------------------------------------------------------===// 478 479 RegionKind SSACFGRegionOp::getRegionKind(unsigned index) { 480 return RegionKind::SSACFG; 481 } 482 483 //===----------------------------------------------------------------------===// 484 // Test GraphRegionOp 485 //===----------------------------------------------------------------------===// 486 487 static ParseResult parseGraphRegionOp(OpAsmParser &parser, 488 OperationState &result) { 489 // Parse the body region, and reuse the operand info as the argument info. 490 Region *body = result.addRegion(); 491 return parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{}); 492 } 493 494 static void print(OpAsmPrinter &p, GraphRegionOp op) { 495 p << "test.graph_region "; 496 p.printRegion(op.region(), /*printEntryBlockArgs=*/false); 497 } 498 499 RegionKind GraphRegionOp::getRegionKind(unsigned index) { 500 return RegionKind::Graph; 501 } 502 503 //===----------------------------------------------------------------------===// 504 // Test AffineScopeOp 505 //===----------------------------------------------------------------------===// 506 507 static ParseResult parseAffineScopeOp(OpAsmParser &parser, 508 OperationState &result) { 509 // Parse the body region, and reuse the operand info as the argument info. 510 Region *body = result.addRegion(); 511 return parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{}); 512 } 513 514 static void print(OpAsmPrinter &p, AffineScopeOp op) { 515 p << "test.affine_scope "; 516 p.printRegion(op.region(), /*printEntryBlockArgs=*/false); 517 } 518 519 //===----------------------------------------------------------------------===// 520 // Test parser. 521 //===----------------------------------------------------------------------===// 522 523 static ParseResult parseWrappedKeywordOp(OpAsmParser &parser, 524 OperationState &result) { 525 StringRef keyword; 526 if (parser.parseKeyword(&keyword)) 527 return failure(); 528 result.addAttribute("keyword", parser.getBuilder().getStringAttr(keyword)); 529 return success(); 530 } 531 532 static void print(OpAsmPrinter &p, WrappedKeywordOp op) { 533 p << WrappedKeywordOp::getOperationName() << " " << op.keyword(); 534 } 535 536 //===----------------------------------------------------------------------===// 537 // Test WrapRegionOp - wrapping op exercising `parseGenericOperation()`. 538 539 static ParseResult parseWrappingRegionOp(OpAsmParser &parser, 540 OperationState &result) { 541 if (parser.parseKeyword("wraps")) 542 return failure(); 543 544 // Parse the wrapped op in a region 545 Region &body = *result.addRegion(); 546 body.push_back(new Block); 547 Block &block = body.back(); 548 Operation *wrapped_op = parser.parseGenericOperation(&block, block.begin()); 549 if (!wrapped_op) 550 return failure(); 551 552 // Create a return terminator in the inner region, pass as operand to the 553 // terminator the returned values from the wrapped operation. 554 SmallVector<Value, 8> return_operands(wrapped_op->getResults()); 555 OpBuilder builder(parser.getBuilder().getContext()); 556 builder.setInsertionPointToEnd(&block); 557 builder.create<TestReturnOp>(wrapped_op->getLoc(), return_operands); 558 559 // Get the results type for the wrapping op from the terminator operands. 560 Operation &return_op = body.back().back(); 561 result.types.append(return_op.operand_type_begin(), 562 return_op.operand_type_end()); 563 564 // Use the location of the wrapped op for the "test.wrapping_region" op. 565 result.location = wrapped_op->getLoc(); 566 567 return success(); 568 } 569 570 static void print(OpAsmPrinter &p, WrappingRegionOp op) { 571 p << op.getOperationName() << " wraps "; 572 p.printGenericOp(&op.region().front().front()); 573 } 574 575 //===----------------------------------------------------------------------===// 576 // Test PolyForOp - parse list of region arguments. 577 //===----------------------------------------------------------------------===// 578 579 static ParseResult parsePolyForOp(OpAsmParser &parser, OperationState &result) { 580 SmallVector<OpAsmParser::OperandType, 4> ivsInfo; 581 // Parse list of region arguments without a delimiter. 582 if (parser.parseRegionArgumentList(ivsInfo)) 583 return failure(); 584 585 // Parse the body region. 586 Region *body = result.addRegion(); 587 auto &builder = parser.getBuilder(); 588 SmallVector<Type, 4> argTypes(ivsInfo.size(), builder.getIndexType()); 589 return parser.parseRegion(*body, ivsInfo, argTypes); 590 } 591 592 //===----------------------------------------------------------------------===// 593 // Test removing op with inner ops. 594 //===----------------------------------------------------------------------===// 595 596 namespace { 597 struct TestRemoveOpWithInnerOps 598 : public OpRewritePattern<TestOpWithRegionPattern> { 599 using OpRewritePattern<TestOpWithRegionPattern>::OpRewritePattern; 600 601 LogicalResult matchAndRewrite(TestOpWithRegionPattern op, 602 PatternRewriter &rewriter) const override { 603 rewriter.eraseOp(op); 604 return success(); 605 } 606 }; 607 } // end anonymous namespace 608 609 void TestOpWithRegionPattern::getCanonicalizationPatterns( 610 OwningRewritePatternList &results, MLIRContext *context) { 611 results.insert<TestRemoveOpWithInnerOps>(context); 612 } 613 614 OpFoldResult TestOpWithRegionFold::fold(ArrayRef<Attribute> operands) { 615 return operand(); 616 } 617 618 OpFoldResult TestOpConstant::fold(ArrayRef<Attribute> operands) { 619 return getValue(); 620 } 621 622 LogicalResult TestOpWithVariadicResultsAndFolder::fold( 623 ArrayRef<Attribute> operands, SmallVectorImpl<OpFoldResult> &results) { 624 for (Value input : this->operands()) { 625 results.push_back(input); 626 } 627 return success(); 628 } 629 630 OpFoldResult TestOpInPlaceFold::fold(ArrayRef<Attribute> operands) { 631 assert(operands.size() == 1); 632 if (operands.front()) { 633 setAttr("attr", operands.front()); 634 return getResult(); 635 } 636 return {}; 637 } 638 639 LogicalResult OpWithInferTypeInterfaceOp::inferReturnTypes( 640 MLIRContext *, Optional<Location> location, ValueRange operands, 641 DictionaryAttr attributes, RegionRange regions, 642 SmallVectorImpl<Type> &inferredReturnTypes) { 643 if (operands[0].getType() != operands[1].getType()) { 644 return emitOptionalError(location, "operand type mismatch ", 645 operands[0].getType(), " vs ", 646 operands[1].getType()); 647 } 648 inferredReturnTypes.assign({operands[0].getType()}); 649 return success(); 650 } 651 652 LogicalResult OpWithShapedTypeInferTypeInterfaceOp::inferReturnTypeComponents( 653 MLIRContext *context, Optional<Location> location, ValueRange operands, 654 DictionaryAttr attributes, RegionRange regions, 655 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) { 656 // Create return type consisting of the last element of the first operand. 657 auto operandType = *operands.getTypes().begin(); 658 auto sval = operandType.dyn_cast<ShapedType>(); 659 if (!sval) { 660 return emitOptionalError(location, "only shaped type operands allowed"); 661 } 662 int64_t dim = 663 sval.hasRank() ? sval.getShape().front() : ShapedType::kDynamicSize; 664 auto type = IntegerType::get(17, context); 665 inferredReturnShapes.push_back(ShapedTypeComponents({dim}, type)); 666 return success(); 667 } 668 669 LogicalResult OpWithShapedTypeInferTypeInterfaceOp::reifyReturnTypeShapes( 670 OpBuilder &builder, llvm::SmallVectorImpl<Value> &shapes) { 671 shapes = SmallVector<Value, 1>{ 672 builder.createOrFold<DimOp>(getLoc(), getOperand(0), 0)}; 673 return success(); 674 } 675 676 //===----------------------------------------------------------------------===// 677 // Test SideEffect interfaces 678 //===----------------------------------------------------------------------===// 679 680 namespace { 681 /// A test resource for side effects. 682 struct TestResource : public SideEffects::Resource::Base<TestResource> { 683 StringRef getName() final { return "<Test>"; } 684 }; 685 } // end anonymous namespace 686 687 void SideEffectOp::getEffects( 688 SmallVectorImpl<MemoryEffects::EffectInstance> &effects) { 689 // Check for an effects attribute on the op instance. 690 ArrayAttr effectsAttr = getAttrOfType<ArrayAttr>("effects"); 691 if (!effectsAttr) 692 return; 693 694 // If there is one, it is an array of dictionary attributes that hold 695 // information on the effects of this operation. 696 for (Attribute element : effectsAttr) { 697 DictionaryAttr effectElement = element.cast<DictionaryAttr>(); 698 699 // Get the specific memory effect. 700 MemoryEffects::Effect *effect = 701 StringSwitch<MemoryEffects::Effect *>( 702 effectElement.get("effect").cast<StringAttr>().getValue()) 703 .Case("allocate", MemoryEffects::Allocate::get()) 704 .Case("free", MemoryEffects::Free::get()) 705 .Case("read", MemoryEffects::Read::get()) 706 .Case("write", MemoryEffects::Write::get()); 707 708 // Check for a result to affect. 709 Value value; 710 if (effectElement.get("on_result")) 711 value = getResult(); 712 713 // Check for a non-default resource to use. 714 SideEffects::Resource *resource = SideEffects::DefaultResource::get(); 715 if (effectElement.get("test_resource")) 716 resource = TestResource::get(); 717 718 effects.emplace_back(effect, value, resource); 719 } 720 } 721 722 //===----------------------------------------------------------------------===// 723 // StringAttrPrettyNameOp 724 //===----------------------------------------------------------------------===// 725 726 // This op has fancy handling of its SSA result name. 727 static ParseResult parseStringAttrPrettyNameOp(OpAsmParser &parser, 728 OperationState &result) { 729 // Add the result types. 730 for (size_t i = 0, e = parser.getNumResults(); i != e; ++i) 731 result.addTypes(parser.getBuilder().getIntegerType(32)); 732 733 if (parser.parseOptionalAttrDictWithKeyword(result.attributes)) 734 return failure(); 735 736 // If the attribute dictionary contains no 'names' attribute, infer it from 737 // the SSA name (if specified). 738 bool hadNames = llvm::any_of(result.attributes, [](NamedAttribute attr) { 739 return attr.first == "names"; 740 }); 741 742 // If there was no name specified, check to see if there was a useful name 743 // specified in the asm file. 744 if (hadNames || parser.getNumResults() == 0) 745 return success(); 746 747 SmallVector<StringRef, 4> names; 748 auto *context = result.getContext(); 749 750 for (size_t i = 0, e = parser.getNumResults(); i != e; ++i) { 751 auto resultName = parser.getResultName(i); 752 StringRef nameStr; 753 if (!resultName.first.empty() && !isdigit(resultName.first[0])) 754 nameStr = resultName.first; 755 756 names.push_back(nameStr); 757 } 758 759 auto namesAttr = parser.getBuilder().getStrArrayAttr(names); 760 result.attributes.push_back({Identifier::get("names", context), namesAttr}); 761 return success(); 762 } 763 764 static void print(OpAsmPrinter &p, StringAttrPrettyNameOp op) { 765 p << "test.string_attr_pretty_name"; 766 767 // Note that we only need to print the "name" attribute if the asmprinter 768 // result name disagrees with it. This can happen in strange cases, e.g. 769 // when there are conflicts. 770 bool namesDisagree = op.names().size() != op.getNumResults(); 771 772 SmallString<32> resultNameStr; 773 for (size_t i = 0, e = op.getNumResults(); i != e && !namesDisagree; ++i) { 774 resultNameStr.clear(); 775 llvm::raw_svector_ostream tmpStream(resultNameStr); 776 p.printOperand(op.getResult(i), tmpStream); 777 778 auto expectedName = op.names()[i].dyn_cast<StringAttr>(); 779 if (!expectedName || 780 tmpStream.str().drop_front() != expectedName.getValue()) { 781 namesDisagree = true; 782 } 783 } 784 785 if (namesDisagree) 786 p.printOptionalAttrDictWithKeyword(op.getAttrs()); 787 else 788 p.printOptionalAttrDictWithKeyword(op.getAttrs(), {"names"}); 789 } 790 791 // We set the SSA name in the asm syntax to the contents of the name 792 // attribute. 793 void StringAttrPrettyNameOp::getAsmResultNames( 794 function_ref<void(Value, StringRef)> setNameFn) { 795 796 auto value = names(); 797 for (size_t i = 0, e = value.size(); i != e; ++i) 798 if (auto str = value[i].dyn_cast<StringAttr>()) 799 if (!str.getValue().empty()) 800 setNameFn(getResult(i), str.getValue()); 801 } 802 803 //===----------------------------------------------------------------------===// 804 // RegionIfOp 805 //===----------------------------------------------------------------------===// 806 807 static void print(OpAsmPrinter &p, RegionIfOp op) { 808 p << RegionIfOp::getOperationName() << " "; 809 p.printOperands(op.getOperands()); 810 p << ": " << op.getOperandTypes(); 811 p.printArrowTypeList(op.getResultTypes()); 812 p << " then"; 813 p.printRegion(op.thenRegion(), 814 /*printEntryBlockArgs=*/true, 815 /*printBlockTerminators=*/true); 816 p << " else"; 817 p.printRegion(op.elseRegion(), 818 /*printEntryBlockArgs=*/true, 819 /*printBlockTerminators=*/true); 820 p << " join"; 821 p.printRegion(op.joinRegion(), 822 /*printEntryBlockArgs=*/true, 823 /*printBlockTerminators=*/true); 824 } 825 826 static ParseResult parseRegionIfOp(OpAsmParser &parser, 827 OperationState &result) { 828 SmallVector<OpAsmParser::OperandType, 2> operandInfos; 829 SmallVector<Type, 2> operandTypes; 830 831 result.regions.reserve(3); 832 Region *thenRegion = result.addRegion(); 833 Region *elseRegion = result.addRegion(); 834 Region *joinRegion = result.addRegion(); 835 836 // Parse operand, type and arrow type lists. 837 if (parser.parseOperandList(operandInfos) || 838 parser.parseColonTypeList(operandTypes) || 839 parser.parseArrowTypeList(result.types)) 840 return failure(); 841 842 // Parse all attached regions. 843 if (parser.parseKeyword("then") || parser.parseRegion(*thenRegion, {}, {}) || 844 parser.parseKeyword("else") || parser.parseRegion(*elseRegion, {}, {}) || 845 parser.parseKeyword("join") || parser.parseRegion(*joinRegion, {}, {})) 846 return failure(); 847 848 return parser.resolveOperands(operandInfos, operandTypes, 849 parser.getCurrentLocation(), result.operands); 850 } 851 852 OperandRange RegionIfOp::getSuccessorEntryOperands(unsigned index) { 853 assert(index < 2 && "invalid region index"); 854 return getOperands(); 855 } 856 857 void RegionIfOp::getSuccessorRegions( 858 Optional<unsigned> index, ArrayRef<Attribute> operands, 859 SmallVectorImpl<RegionSuccessor> ®ions) { 860 // We always branch to the join region. 861 if (index.hasValue()) { 862 if (index.getValue() < 2) 863 regions.push_back(RegionSuccessor(&joinRegion(), getJoinArgs())); 864 else 865 regions.push_back(RegionSuccessor(getResults())); 866 return; 867 } 868 869 // The then and else regions are the entry regions of this op. 870 regions.push_back(RegionSuccessor(&thenRegion(), getThenArgs())); 871 regions.push_back(RegionSuccessor(&elseRegion(), getElseArgs())); 872 } 873 874 #include "TestOpEnums.cpp.inc" 875 #include "TestOpStructs.cpp.inc" 876 #include "TestTypeInterfaces.cpp.inc" 877 878 #define GET_OP_CLASSES 879 #include "TestOps.cpp.inc" 880