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